API Executor — Root Cause Analysis (RCA) & Technical Transparency Register (RCA_REGISTER.md)¶
This living governance register records all errors encountered, technical dead-ends, current approximations, and unimplemented roadmap ideas on the API Executor (go-admin-tool) project in accordance with AGENTS.md.
1. Errors & Bugs Encountered (RCA-XXX)¶
RCA-001 — Bundling Multiple Distinct Features into a Monolithic Issue #2 ("Kitchen-Sink / Papa-Maman" Anti-Pattern)¶
- Date:
2026-10-25 - Observed Symptom: Multiple unrelated engineering domains (metrics, timeouts, TLS, OS presets, RBAC, plugins, MCP, Web UI, and branding) were initially grouped into a single catch-all issue.
- Root Cause Analysis: Lack of an explicit repository rule enforcing
1 Item = 1 Issue = 1 Branch = 1 PR = 1 Merge. - Applied Change / Fix: Codified the Strict Atomicity Rule in
AGENTS.mdand.agents/rules/atomic-workflow.mdand decomposed the backlog into atomic Issues#2through#11. - Result & Non-Regression Test: Verified via isolated atomic branches and PRs
#12through#21.
RCA-002 — Grandchild Process Leak on Command Timeout and CGO_ENABLED=0 SQLite Failure¶
- Date:
2026-10-25 - Observed Symptom:
exec.CommandContextonly sentSIGKILLto the direct child process on timeout, leaving spawned background grandchild processes alive, andgo-sqlite3failed at runtime when compiled withCGO_ENABLED=0. - Root Cause Analysis: Default
os/execbehavior kills only the process leader PID unless a process group (Setpgid) andWaitDelayare configured;mattn/go-sqlite3requires CGO. - Applied Change / Fix: Process-group kill (
Setpgidon Unix,WaitDelayon Windows/Unix) ininternal/core/executor.goand pure-Go in-memory fallback ininternal/database/db.go. - Result & Non-Regression Test: Verified by
TestExecuteCommandGrandchildProcessGroupTimeoutandTestDatabaseRecordActionAndValidation.
RCA-003 — Static tls.LoadX509KeyPair Prevented Zero-Downtime Certificate Renewal¶
- Date:
2026-10-25 - Observed Symptom: Standard
http.Server.ListenAndServeTLS(certFile, keyFile)loads the certificate once at startup and ignores subsequent rotations. - Root Cause Analysis: Static certificate loading in
crypto/tlsdoes not re-read rotated key pairs without a dynamicGetCertificatecallback. - Applied Change / Fix: Dynamic
CertManager.GetCertificatecallback protected bysync.RWMutexininternal/core/tls.go. - Result & Non-Regression Test: Verified by
TestCertManagerRotateAndRealHTTPSHandshakeandTestTLSRenewEndpoint.
RCA-004 — RedHat UBI9 Minimal Base Missing ps and ss Utilities by Default¶
- Date:
2026-10-25 - Observed Symptom: Containerized RedHat preset tasks (
redhat-process-tree,redhat-listening-sockets) failed ifprocps-ngandiproutewere not installed in the UBI9 image. - Root Cause Analysis: RedHat UBI9 minimal base image omits
ps(procps-ng) andss(iproute) by default. - Applied Change / Fix: Installed
procps-ngandiprouteindocker/Dockerfile.redhat. - Result & Non-Regression Test: Verified by
TestOSPresetCatalogsUbuntuAndRedHatanddocker/Dockerfile.redhat.
RCA-005 — World-Readable 0666 Log File Permissions and Unverifiable Audit Records¶
- Date:
2026-10-25 - Observed Symptom:
internal/core/logger.gopreviously opened log files with0666, andaction_historyhad no cryptographic tamper detection. - Root Cause Analysis: Permissive default file mode in
os.OpenFileand lack of hash chaining between sequential operational records. - Applied Change / Fix: Tightened log file permissions to
0600ininternal/core/logger.goand implemented SHA-256 hash chaining (prev_hash->entry_hashfromGENESIS) ininternal/audit/audit.go. - Result & Non-Regression Test: Verified by
TestAuditLoggerHashChainAndQueryandTestAuditLogsVerifyAndSystemLogsEndpoints.
RCA-006 — Missing Principal Authentication and Admin Role Enforcement on Service Account Rotation and User Mutation Endpoints¶
- Date:
2026-10-26 - Observed Symptom: During review of
internal/api/auth_handlers.gofor Issue #7,AuthServiceAccountRotateHandlerdid not invokeenv.resolvePrincipal(r), andPATCH/DELETEon/api/v1/auth/usersandPOST/DELETEon/api/v1/auth/service-accountsdid not enforcep.Role == auth.RoleAdmin. - Root Cause Analysis: Only
POST /api/v1/auth/usersinitially checkedp.Role != auth.RoleAdmin, leaving adjacent administrative mutation handlers open to authenticated non-admin operators or unauthenticated callers whenRequireAuth=true. - Applied Change / Fix: Enforced
env.resolvePrincipal(r)andp.Role == auth.RoleAdminacross all administrative user and service account mutation handlers ininternal/api/auth_handlers.go. - Result & Non-Regression Test: Verified by
TestAuthEndpointsAndServiceAccountCommandScoping(steps 6 & 7 asserting401 Unauthorizedand403 Forbidden).
RCA-007 — Relative ./web/static Path Returned 404 When Running Router Tests Inside internal/api¶
- Date:
2026-10-26 - Observed Symptom:
http.FileServer(http.Dir("./web/static"))ininternal/api/router.goassumed the process working directory was always the repository root, causingGET /inside package-level tests (internal/api) to fail to locateweb/static/index.html. - Root Cause Analysis:
go test ./...executes each package test binary with its working directory set to the package folder (internal/api), where./web/staticdoes not exist. - Applied Change / Fix: Added
resolveStaticDir()ininternal/api/router.goto probe./web/staticand../../web/static. - Result & Non-Regression Test: Verified by
TestWebAdministrationConsoleServedininternal/api/web_console_test.go.
RCA-008 — RBAC Privilege Escalation on /api/v1/auth/tokens, Service Account Bypass via MCP tools/call, and Unauthenticated TLS/Preset Mutations¶
- Date:
2026-10-26 - Observed Symptom:
- Authenticated non-admin principals (
operator,viewer, orservice_account) could callPOST /api/v1/auth/tokenswith{"user_id": "admin"}and receive a validadminPersonal Access Token (scopes: ["*"]), or callDELETE /api/v1/auth/tokensto revoke admin tokens. - A third-party
service_accountrestricted to specificallowed_actions(e.g.["mcp-test-cmd"]) could bypass its command/plugin allowlist by invokingPOST /api/v1/mcp(tools/call->execute_command/execute_plugin). POST /api/v1/tls/renewandPOST /api/v1/presets/activateexecuted without callingresolvePrincipalor recording an event inAuditLogger.- Root Cause Analysis:
AuthTokensHandlervalidated the caller's token viaresolvePrincipalbut did not verify that non-admin callers could only issue/revoke tokens for their own user account and within their own granted scopes.MCPHandlerauthorizedmcp:accesswith an emptytargetAction(""), andMCPServer.HandleJSONRPCdid not receive a per-toolToolAuthorizercallback to checkcommands:execute/plugins:executeagainst the caller'sAllowedActions.TLSRenewHandlerandActivatePresetsHandlerwere implemented beforeAuthManagerandAuditLoggerwere wired intoAPIEnv.- Applied Change / Fix:
- Enforced role, user-ownership, and scope-subset checks in
AuthTokensHandler(internal/api/auth_handlers.go). - Added
HandleJSONRPCWithAuthorizerandToolAuthorizerenforcement acrossexecute_command,execute_plugin,db_query, anddb_list_tablesininternal/mcp/server.goandinternal/api/mcp_handlers.go. - Added
resolvePrincipal, role/scope checks, andAuditLogger.Recordcalls toTLSRenewHandlerandActivatePresetsHandler. - Result & Non-Regression Test: Verified by
TestAuthTokensPrivilegeEscalationPrevention,TestMCPEndpointsAndTraceInspection(step 6),TestTLSRenewEndpoint, andTestPresetsEndpointsListAndActivate.
RCA-009 — Web Console Preset Catalog JSON Key Mismatch (cat.tasks vs cat.commands, os_families vs families) and Missing Declarative Plugin / Log Panels¶
- Date:
2026-10-26 - Observed Symptom:
- In Tab 2 of
web/static/index.html, OS preset catalogs rendered0 tasksand zero command cards despiteGET /api/v1/presetsreturning 10 Ubuntu and 10 RedHat commands. - Clicking "Activate Ubuntu Presets" sent
{"os_families": ["ubuntu"]}toPOST /api/v1/presets/activate, which only boundjson:"families", causingreq.Familiesto be empty and activating all 20 OS presets instead of only 10 Ubuntu presets. - Tab 5 and Tab 7 did not expose UI panels for
POST /api/v1/plugins/declarative,GET /api/v1/logs, orGET /api/v1/history. - Root Cause Analysis:
core.OSPresetCatalogserializes its command slice asjson:"commands", whileweb/static/index.htmlboundcat.tasks.ActivatePresetsHandlerdefinedFamilies []stringwithjson:"families"while the frontend sentos_families.- Applied Change / Fix:
- Updated
web/static/index.htmlto iterate(cat.commands || cat.tasks || []), passcat.os_familyintorunPresetTask, and wire UI panels for/api/v1/plugins/declarative,/api/v1/logs, and/api/v1/history. - Updated
ActivatePresetsHandlerto accept bothfamiliesandos_families. - Result & Non-Regression Test: Verified by
TestWebAdministrationConsoleServedininternal/api/web_console_test.go.
RCA-010 — README cURL Example Mismatches (redhat-rpm-packages, runtime-stats) and Root Dockerfile Non-Root Write Permission Failure¶
- Date:
2026-10-26 - Observed Symptom:
README.mdline 124 invoked{"name": "redhat-rpm-packages"}(actual preset name:"redhat-rpm-qa") and line 205 invoked{"plugin_id": "sys-diagnostics", "action": "runtime-stats"}(which returned404becausesys-diagnosticsonly matched"runtime_stats").- Root
Dockerfileran asUSER appuserwithoutchown -R appuser:appgroup /app,/app/certs, orCOPY --from=builder /app/plugins ./plugins. - Root Cause Analysis:
README.mdexamples were written without normalizing hyphenated action names insys_diagnostics.goor checking the exact preset name ininternal/core/os_presets.go.- Root
Dockerfilewas not updated when default HTTPS certificate auto-generation (./certs) and declarative plugins (./plugins) were introduced in Issues #4 and #8. - Applied Change / Fix:
- Normalized hyphen/underscore action names in
internal/plugins/sys_diagnostics.go, updatedREADME.mdto useredhat-rpm-qa, and updatedDockerfile,docker/Dockerfile.ubuntu, anddocker/Dockerfile.redhatto copyplugins/and grantappuser:appgroupownership of/appand/app/certs. - Result & Non-Regression Test: Verified by
TestSVGAssetsAreValidXMLAndREADMEIncludesBranding(docs/branding_test.go) andTestSystemDiagnosticsPlugin(internal/plugins/plugins_test.go).
RCA-011 — Unclosed File Handle in core.Logger on Windows and Untestable Monolithic main() in cmd/server/main.go¶
- Date:
2026-10-26 - Observed Symptom:
- Writing unit tests for
core.NewLoggerwith a file-backedLoggingConfig.Pathinsidet.TempDir()failed on Windows during test cleanup withThe process cannot access the file because it is being used by another process. cmd/serverhad0.0%unit test coverage and hardcoded"config.yaml"insidefunc main().- Root Cause Analysis:
core.NewLoggeropened the log file viaos.OpenFileand passed it tolog.New(output, "", 0)without exposing aClose() errormethod on*core.Loggerto release the OS file descriptor.- All server bootstrap wiring in
cmd/server/main.gowas coupled directly tolog.Fatalf/os.Exit(1)andListenAndServeinsidemain(). - Applied Change / Fix:
- Added
(*core.Logger).Close() errorininternal/core/logger.goto safely close file-backed log writers. - Extracted
resolveConfigPath(),initializeServerEnv(configPath string), andbuildHTTPServer(env, router)incmd/server/main.goand added unit tests incmd/server/main_test.go. - Result & Non-Regression Test: Verified by
TestLoggerLevelsStructuredOutputAndRingBuffer(internal/core/logger_test.go) andTestResolveConfigPathAndInitializeServerEnv(cmd/server/main_test.go).
RCA-012 — Declarative Plugin Registration Banner Key Mismatch (d.plugin.id vs d.id) and Missing Favicon Console Error in Web Administration Console¶
- Date:
2026-10-26 - Observed Symptom:
- Clicking "Register Declarative Plugin" in Tab 5 of
web/static/index.htmldisplayed"Registered declarative plugin "without the newly registered plugin ID (custom-ops), and mutating actions across Tabs 2–5 did not immediately refresh the Tab 7 SHA-256 Audit badge count. - Navigating to the Web Administration Console in MCP Playwright logged a browser console error:
Failed to load resource: the server responded with a status of 404 (Not Found) @ /favicon.ico. - Root Cause Analysis:
POST /api/v1/plugins/declarative(PluginsHandlerininternal/api/plugin_handlers.go) serializesplugins.PluginInfodirectly at the root JSON object ({"id": "custom-ops", ...}), whereasregisterDeclarativePlugin()inweb/static/index.htmlcheckedd.plugin ? d.plugin.id : ''.web/static/index.htmldid not declare a<link rel="icon">tag in<head>, causing Chromium to request/favicon.ico.- Applied Change / Fix:
- Updated
registerDeclarativePlugin()inweb/static/index.htmlto readconst pluginID = d.id || (d.plugin && d.plugin.id) || '', addedthis.loadAuditAndLogs()refresh calls after preset, user, PAT, service-account, plugin, SQL, and TLS mutations, and added an inline SVG data-URI favicon<link rel="icon" type="image/svg+xml" ...>. - Result & Non-Regression Test: Verified interactively via MCP Playwright across all 8 tabs (
0console errors) and byTestWebAdministrationConsoleServedandTestWebAdministrationConsoleEndToEndWorkflowsininternal/api/web_console_test.go.
RCA-013 — Unaudited RBAC Credential Deletions/Rotations, Unawaited Async Refreshes & Missing 401/403 Banner Feedback in Web Console, and cmd/server Coverage Below 80%¶
- Date:
2026-10-26 - Observed Symptom:
PATCH/DELETE /api/v1/auth/users,DELETE /api/v1/auth/tokens,DELETE /api/v1/auth/service-accounts, andPOST /api/v1/auth/service-accounts/rotatesucceeded without recording SHA-256 audit events (user.update,user.delete,token.revoke,service_account.delete,service_account.rotate) inAuditLogger.- In
web/static/index.html,deleteUser(),revokeToken(), anddeleteServiceAccount()discarded HTTP responses without updatingstatusBanneror callingloadAuditAndLogs();loadPrincipal()left staleprincipaldata displayed whenGET /api/v1/auth/mereturned401 Unauthorized;executePlugin()andrunDBQuery()did not updatestatusBanner; andloadAuthData()/loadAuditAndLogs()were invoked withoutawaitinside async mutation methods. cmd/serverstatement coverage was66.0%(below the 80% minimum threshold) because listener dispatch remained insidefunc main().- Root Cause Analysis:
internal/api/auth_handlers.gowiredenv.AuditLogger.RecordonPOSTcreation handlers (login,user.create,token.create,service_account.create) but omittedPATCH,DELETE, and key rotation handlers.web/static/index.htmlomitted!r.okhandling andawaiton secondary refresh promises in its Alpine.js controller methods.cmd/server/main.gocoupledbuildHTTPServerandListenAndServe/ListenAndServeTLSdirectly tomain().- Applied Change / Fix:
- Added
env.AuditLogger.Recordcalls foruser.update,user.delete,token.revoke,service_account.delete, andservice_account.rotateininternal/api/auth_handlers.go. - Updated
web/static/index.htmlto resetthis.principal = nullon401, surfacestatusBannerfeedback across all RBAC mutations and401/403responses, andawaitloadAuthData(),loadMCPTraces(), andloadAuditAndLogs(). - Extracted
runServer(configPath, serveFn)incmd/server/main.goand expandedcmd/server/main_test.go(66.0%->82.4%statement coverage). - Result & Non-Regression Test: Verified by
TestAuthTokensPrivilegeEscalationPrevention(internal/api/auth_test.go),TestWebAdministrationConsoleServed(internal/api/web_console_test.go),TestResolveConfigPathAndInitializeServerEnv(cmd/server/main_test.go), and live MCP Playwright E2E verification across all 8 tabs.
RCA-014 — Windows Declarative Subprocess Execution Failure for echo Builtin¶
- Date:
2026-10-27 - Observed Symptom: When declarative command actions configured with
command: "echo"were invoked on Windows,exec.CommandContextfailed withexec: "echo": executable file not found in %PATH%, returning statuserror(HTTP 400). - Root Cause Analysis: On Windows,
echois a built-in command ofcmd.exerather than an independent binary executable in%PATH%. Direct argv subprocess execution (exec.CommandContextwithout a shell) requires invokingcmdwith["/C", "echo", ...]on Windows. - Applied Change / Fix: Implemented a cross-platform helper
crossPlatformEcho()in test harnesses checkingruntime.GOOS == "windows"and usingcmd /C echoon Windows while usingechoon Linux/POSIX, mirroringDefaultDeclarativeOpsPlugin(). - Result & Non-Regression Test: Verified by
TestTier1_F4_DeclarativePlugin_DynamicRegistrationAndExecution,TestTier3_Combination_APIFilterAndExecuteWorkflow, andTestTier4_Scenario_DynamicOpsRemediationAndAuditLifecyclepassing 100% on both Windows and Linux.
RCA-015 — InsecureSkipVerify Omission in SSL Redirect Check and Test Registry Assumption¶
- Date:
2026-10-27 - Observed Symptom:
http-latency-probeactionssl_redirect_checkfailed in unit tests when probing local test HTTPS servers withx509: certificate signed by unknown authority.- Registering all 24 native plugins by default in
NewRegistry()caused legacy tests assuming an initially empty or 2-plugin registry to fail. - Root Cause Analysis:
ssl_redirect_checkusedhttp.Client{CheckRedirect: ...}without configuringInsecureSkipVerify: trueonhttp.Transport{TLSClientConfig: ...}for testing and arbitrary internal TLS environments, causing untrusted self-signed certificate handshakes to fail immediately during redirect evaluation.- Legacy unit tests in
internal/plugins/plugins_test.goinstantiatedNewRegistry()and asserted exact counts of registered plugins (len(reg.List()) == 2) based on the previous baseline of onlysys-diagnosticsanddb-exposure. - Applied Change / Fix:
- Added
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}to the HTTP redirect client ininternal/plugins/native_crypto.go. - Added
NewEmptyRegistry()ininternal/plugins/plugin.gofor isolated test scenarios and updated legacy assertions ininternal/plugins/plugins_test.go. - Result & Non-Regression Test: Verified by
TestAll24NativePluginsActionsandTestRegistryEmptyAndDuplicateininternal/plugins/plugins_test.go(100% test pass rate across 145 tests, 85.9% plugin coverage).
RCA-016 — Fail-Open on Unrecognized Plugin Types, Omitted Metadata on Declarative Registration, and Unhandled Errors in Native HTTP/JWT Plugins¶
- Date:
2026-10-27 - Observed Symptom:
Registry.ListFilteredwith an unrecognized or non-existent type query (e.g.?type=bogus-type) returned all 25 registered plugins instead of an empty slice.POST /api/v1/plugins/declarativereturnedPluginInfowith emptytype: ""andcategory: ""in JSON response.http-latency-probeactionsinspect_headersandssl_redirect_checktriggered a runtime panic (nil pointer dereference) when supplied with a malformed URL like"://invalid-url".jwt-token-inspectordiscardedjson.Unmarshalerrors with_, causing non-JSON payloads ("eyJhbGciOiJIUzI1NiJ9.YQ.sig"where payload is"a") and empty segments ("..") to returnstatus: "ok"andvalid: true.- Root Cause Analysis:
ListFilteredused cascading positiveifchecks for"native","advanced", and"declarative"without a default drop case, allowing any unknown type string to fall through without hittingcontinue.PluginDeclarativeRegisterHandlerconstructedPluginInfowithout setting theTypeandCategoryfields introduced during Milestone 1 metadata enrichment.inspect_headersandssl_redirect_checkdiscarded the error fromhttp.NewRequestWithContext(ctx, method, targetURL, nil)using_, passingreq == niltoclient.Do(req).jwt-token-inspectordiscarded errors fromjson.Unmarshal(payloadBytes, &claims), leavingclaimsasnilsoclaims["exp"]was absent,isExpiredremainedfalse, andvalidevaluated to!isExpired(true); also omittednbfvalidation.- Applied Change / Fix:
- Replaced cascading
ifchecks ininternal/plugins/plugin.gowithswitch pluginTypefeaturingdefault: continue. - Populated
Type: declPlugin.Type()andCategory: declPlugin.Category()ininternal/api/plugin_handlers.go. - Added error checking on
http.NewRequestWithContextreturningStatus: "error"ininternal/plugins/native_crypto.go. - Added explicit
json.Unmarshalerror handling and non-nil map checks ininternal/plugins/native_crypto.go, and evaluatednbfconstraint. - Result & Non-Regression Test:
- Verified by
TestRegistry_ListFiltered_InvalidTypeDropsAll,TestHTTPLatencyProbe_MalformedURLs, andTestJWTTokenInspector_ValidationAndMalformedPayloadsininternal/plugins/plugins_test.go, andTestPluginDeclarativeRegisterHandlerMetadataCompletenessininternal/api/plugin_handlers_test.go; 199 unit tests and 65 E2E tests passing 100% (internal/plugins86.3%,internal/api89.9%).
RCA-017 — Compilation Failure on a.Command When Asserting Public PluginAction Metadata¶
- Date:
2026-10-27 - Observed Symptom:
plugins_test.go: a.Command undefined (type PluginAction has no field or method Command)occurred while verifying loaded declarative action fields.- Root Cause Analysis:
PluginActionininternal/plugins/plugin.gois the public API contract exposed by plugins and purposefully exposes onlyName,Description,Timeout, andParameters. Direct process execution mechanics (Command,Args) are encapsulated withinDeclarativeActionSpecininternal/plugins/declarative.goby design to prevent leaking underlying OS binary invocation paths.- Applied Change / Fix:
- Updated
TestLoadDeclarativeDirectory_AllDeclarativePluginsininternal/plugins/plugins_test.goto validate non-emptya.Nameanda.Description. - Result & Non-Regression Test:
- Verified by
TestLoadDeclarativeDirectory_AllDeclarativePluginspassing 100% across all 141 declarative plugins (140 new + 1 baseline).
RCA-018 — Relative Path Parameters in DevOps Manifests Allowed Unrooted Path Traversal Sequences¶
- Date:
2026-10-27 - Observed Symptom: During adversarial security testing of the declarative catalog expansion,
TestM2Adversarial_AllParameters_PathTraversalRejectiondetected that parameters with relative path regex^[a-zA-Z0-9._/-]+$(ingolang-vet-check,jsonlint-file,yamllint-file,shellcheck-script, anddockerfile-hadolint) accepted unrooted path traversal strings (e.g.../../../../etc/passwdorsubdir/../../shadow). - Root Cause Analysis: Regex patterns without an anchored leading root slash allowed relative directory traversing tokens (
../and..\), which caused subprocesses to execute on invalid traversal paths instead of halting early during parameter security validation. - Applied Change / Fix:
- Enforced strict path traversal rejection in
internal/plugins/declarative.go(strings.Contains(rawVal, "../") || strings.Contains(rawVal, "..\\")).
RCA-019 — Dynamic Form Parameter Synchronization and Type Coercion for Boolean and Integer Inputs in Web Console Tab 5¶
- Date:
2026-10-27 - Observed Symptom: When dynamically generating parameter form fields for actions declaring integer (
int) or boolean (bool) parameters, standard HTML<input>elements bind values as strings (e.g."10"or"true"), causing strict JSON parameter validators in declarative plugin runners to reject requests or fail type regex assertions. - Root Cause Analysis: HTML input elements inherently treat values as strings unless explicit numerical/boolean parsing and reactive two-way synchronization between the form state (
actionParamValues) and the JSON payload (pluginParamsJSON) are performed before submission. - Applied Change / Fix:
- Implemented typed input controls in
web/static/index.htmlwith explicit.numberbindings and checkbox boolean states. - Implemented pre-execution type coercion in
executePlugin()that iteratescurrentActionParameters()and casts numeric/boolean strings to native JavaScript numbers and booleans. - Added bi-directional synchronization helpers (
syncParamsToJSON()andsyncJSONToParams()) allowing seamless switching between Dynamic Form and Raw JSON modes. - Result & Non-Regression Test: Verified by
TestWebAdministrationConsole_Tab5_CatalogSearchFilteringPaginationAndFormsininternal/api/web_console_test.goand verified end-to-end execution ofsys-diagnostics:runtime_statsthrough the Web Console API flow.
RCA-020 — Headless Browser Verification and Self-Signed TLS Certificate Policy¶
- Date:
2026-10-27 - Observed Symptom: When running automated headless browser test suites (Playwright MCP) against the API Executor web server on localhost, the default auto-generated self-signed ECDSA certificate causes standard browser engines to abort navigation with security certificate warnings unless
--ignore-certificate-errorsis configured or plain HTTP mode is used. - Root Cause Analysis: Modern Chromium and WebKit security policies block navigation to self-signed TLS endpoints without user confirmation or explicit headless test runner flags.
- Applied Change / Fix: Configured dedicated ephemeral test configuration (
server.tls.enabled: false) on a test port (8089) for live Playwright browser validation, keeping production HTTPS defaults intact inconfig.yaml. - Result & Non-Regression Test: 100% verified via Playwright MCP navigating to
http://127.0.0.1:8089/, validating 306 plugins loaded in Alpine.js, all 10 domain category filters (32 SysAdmin, 30 NetOps, 30 SecOps, 30 ContainerOps, 30 Kubernetes, 31 DataOps, 30 DevOps, 30 SRE, 30 AIOps, 28 WebUtils), keyword search, type toggles, pagination across 31 pages, dynamic parameter form generation, and real API action execution.
RCA-021 — Destructive Deletion of Entire docs/ Directory by make clean¶
- Date:
2026-11-01 - Observed Symptom: Executing
make cleanranrm -rf ./docs, completely deleting non-generated living governance registers (docs/ACTION_LOGBOOK.md,docs/RCA_REGISTER.md), architectural documentation (docs/SECURITY_AND_ARCHITECTURE_ANALYSIS.md), and brand SVG assets (docs/assets/). - Root Cause Analysis (5 Whys):
- Why did
make cleandelete governance registers? Becausecleaninvokedrm -rf ./docs. - Why did
cleaninvokerm -rf ./docs? Because Swagger documentation generation (make swagger) outputs artifacts into thedocs/directory (docs.go,swagger.json,swagger.yaml). - Why was
rm -rfused on the whole directory? Early build scripts assumeddocs/was exclusively generated byswag init. - Why did this become a critical defect? Subsequent milestones introduced living governance files, architecture docs, and assets directly inside
docs/. - Root Cause: Overbroad directory-level cleanup in Makefile rather than targeted deletion of generated build artifacts.
- Applied Change / Fix: Replaced
rm -rf ./docsinMakefilewith targeted cleanup of generated swagger artifacts:rm -f docs/docs.go docs/swagger.json docs/swagger.yaml. - Result & Non-Regression Test: Verified by
go test -v -cover ./...(100% pass across 215 tests in 10 packages) and verifiedmake cleanpreservesdocs/governance registers while removing generated swagger files.
RCA-022 — Omission of 22 Compiled Native Go Plugins in Production Server Runtime¶
- Date:
2026-11-01 - Observed Symptom: In
cmd/server/main.go, the server daemon initialized the plugin registry and only explicitly loadedDefaultDeclarativeOpsPlugin,DatabaseExposurePlugin, andSystemDiagnosticsPlugin, omitting 22 of the 24 compiled native Go plugins from runtime initialization with active database bindings and configured row bounds. Furthermore, initializing withplugins.NewRegistry()pre-populated default plugins withnildatabase instances even whenplugins.enabledwas set tofalse. - Root Cause Analysis (5 Whys):
- Why were 22 native plugins omitted from production server runtime? Because
cmd/server/main.gonever calledplugins.RegisterDefaultNativePlugins(pluginRegistry, db, config.Plugins.MaxQueryRows). - Why was
RegisterDefaultNativePluginsnot called incmd/server/main.go? Because early server bootstrapping only wireddb-exposureandsys-diagnosticsbefore the 24 native plugins were compiled across 10 operational domains in Milestone 1. - Why did
plugins.NewRegistry()not suffice?plugins.NewRegistry()passesnildatabase reference and a hardcoded limit of200rows without dynamic configuration bindings, and would register plugins unconditionally even whenplugins.enabled: false. - Why did subsequent re-registration fail?
Registry.Registerprohibits duplicate IDs to prevent silent overrides, returningErrDuplicatePluginon re-registration of the other 22 native plugins. - Root Cause: Lack of clean initialization via
plugins.NewEmptyRegistry()followed by explicit guarded invocation ofplugins.RegisterDefaultNativePluginsinsidecmd/server/main.go. - Applied Change / Fix:
- Updated
cmd/server/main.goto construct the registry usingplugins.NewEmptyRegistry(). - Injected all 24 native Go plugins with production database reference
dbandconfig.Plugins.MaxQueryRowsviaplugins.RegisterDefaultNativePluginswhenconfig.Plugins.Enabledis true. - Added clean unregistration for
db-exposureandsys-diagnosticswhen their respective feature flags (enable_db_exposure,enable_sys_diagnostics) are disabled. - Added telemetry logging for mounted plugin counts and directory loading metrics.
- Result & Non-Regression Test: Verified by
TestResolveConfigPathAndInitializeServerEnvasserting all 24 native plugin IDs incmd/server/main_test.go,TestInitializeServerEnv_All24NativePluginsMountedasserting all 10 operational domains,TestInitializeServerEnv_PluginsDisabledasserting 0 plugins when disabled, andTestInitializeServerEnv_FeatureFlagToggles(100% pass across 4 tests incmd/serverwith 82.4% coverage; 218 unit + 65 E2E tests passing 100%).
RCA-023 — Unbounded HTTP Server Timeouts (Slowloris Vulnerability) and Abrupt Process Termination on OS Signals¶
- Date:
2026-11-01 - Observed Symptom: In
cmd/server/main.go,buildHTTPServerinitializedhttp.Serverwith zero timeouts, leaving the server vulnerable to connection exhaustion via Slowloris attacks. Furthermore,runServerdirectly invokedserveFnon the main goroutine without trappingSIGINTorSIGTERM, causing abrupt daemon termination, dropped in-flight requests, and risk of SQLite write interruption upon container shutdown. - Root Cause Analysis (5 Whys):
- Why was the server susceptible to Slowloris attacks? Because
http.Serverwas instantiated with zero values forReadHeaderTimeout,ReadTimeout,WriteTimeout, andIdleTimeout. - Why were timeouts not configured? Go's
http.Serverdefaults all timeout fields to zero (unbounded), requiring explicit developer configuration. - Why did the daemon exit abruptly on container shutdown? Because no signal handler caught
os.Interrupt(SIGINT) orsyscall.SIGTERMto coordinate a graceful shutdown sequence. - What was the impact of abrupt exit? Active HTTP connections were dropped immediately without sending response trailers or status codes, and open SQLite transactions risked leaving the WAL journal in an uncheckpointed state.
- Root Cause: Omission of defensive HTTP connection timeout limits on
http.Serverand absence of an OS signal notification context with bounded graceful shutdown. - Applied Change / Fix:
- Configured defensive timeouts in
buildHTTPServer(ReadHeaderTimeout: 5s,ReadTimeout: 15s,WriteTimeout: 30s,IdleTimeout: 60s). - Structured
runServerto trapos.Interruptandsyscall.SIGTERMusingsignal.NotifyContext. - Ran listener execution in a dedicated goroutine and coordinated clean shutdown via
srv.Shutdown(shutdownCtx)with a 10-second timeout context. - Handled
http.ErrServerClosedcleanly and ensured deferred cleanup functions release database and logger resources. - Result & Non-Regression Test: Verified by
TestBuildHTTPServer_TimeoutsConfigured,TestRunServerWithContext_GracefulShutdown, andTestRunServerWithContext_RealListenerGracefulShutdownincmd/server/main_test.go(100% pass across 7 tests incmd/serverwith 82.3% statement coverage; 221 unit + 65 E2E tests passing 100%).
RCA-024 — Unbounded Prometheus Metric Route Path Cardinality Explosion (OOM DoS Vulnerability)¶
- Date:
2026-11-01 - Observed Symptom: In
internal/api/router.go,prometheusMiddlewareextracted rawr.URL.Pathand passed it directly as a Prometheus metric label value forhttp_requests_total(method,path,status) andhttp_request_duration_seconds(method,path). Any client querying dynamic parameterized endpoints (e.g./api/v1/files/:filename,/api/v1/mcp/traces/:trace_id) or fuzzing random 404 paths created a new metric time series in memory for every distinct URI, causing unbounded Prometheus registry memory growth and exposing the server to out-of-memory (OOM) denial-of-service. - Root Cause Analysis (5 Whys):
- Why did metric time series grow without bound? Because
prometheusMiddlewarepassed rawr.URL.Pathdirectly as a Prometheus label value. - Why was raw path used? Standard
http.ServeMuxdoes not automatically annotate requests with route pattern templates (unlike gorilla/mux or gin), leavingr.URL.Pathas the raw path string. - Why is this a security vulnerability? Prometheus stores every distinct combination of label values as a persistent in-memory time series (
MetricFamily). Attackers or clients scanning random paths can generate millions of time series, causing memory exhaustion. - Why were dynamic routes particularly vulnerable? Routes such as
/api/v1/files/{filename}and/api/v1/mcp/traces/{trace_id}take arbitrary identifiers in the path component. - Root Cause: Absence of a route path normalization layer (
normalizeMetricPath) to collapse parameterized routes to route templates and fall back to a strictly bounded"other"label for arbitrary or unrecognized URLs. - Applied Change / Fix:
- Defined
knownStaticPathslookup set ininternal/api/router.gofor all legitimate static application endpoints. - Implemented
normalizeMetricPathcollapsing dynamic parameterized routes (/api/v1/files/*->/api/v1/files/:filename,/api/v1/mcp/traces/*->/api/v1/mcp/traces/:trace_id), collapsing Swagger doc paths to/swagger, preserving recognized static routes (with optional trailing slash tolerance), and collapsing any unrecognized path or random 404 to"other". - Integrated
normalizeMetricPathintoprometheusMiddlewareso Prometheus metrics record only bounded template labels. - Added
ResetHTTPMetrics()for isolated metric test verification. - Implemented comprehensive test coverage in
internal/api/router_test.goverifying dynamic template normalization, static route preservation, and cardinality bounding under fuzzing attacks. - Result & Non-Regression Test: Verified by
TestNormalizeMetricPath,TestPrometheusMetricDynamicRouteNormalization,TestPrometheusMetricPathCardinalityBounding, andTestPrometheusMetricStaticRoutesPreservedininternal/api/router_test.go(100% pass across 94 tests ininternal/api; full suite 276 tests passing 100% across all 10 packages).
RCA-025 — Unauthenticated Access to Administrative File Server, Command Metadata, and Audit/Log Endpoints¶
- Date:
2026-11-01 - Observed Symptom: When
auth.require_auth: truewas configured, several sensitive administrative endpoints (/api/v1/files,/api/v1/files/:filename,/api/v1/commands,/api/v1/audit/logs,/api/v1/audit/verify,/api/v1/logs, and/api/v1/history) completely bypassed authentication. Unauthenticated clients could list server files, download sensitive file payloads, inspect command timeouts/names, read tamper-evident audit events, verify audit chains, view ring-buffered system logs, and inspect execution history. - Root Cause Analysis (5 Whys):
- Why could unauthenticated callers access sensitive endpoints? Because
ListFilesHandler,DownloadFileHandler,ListCommandsHandler,AuditLogsHandler,AuditVerifyHandler,SystemLogsHandler, andActionHistoryHandlernever invokedresolvePrincipal(r)or checkedRequireAuth. - Why was authentication not checked in those handlers? They were initially implemented as read-only diagnostic or utility endpoints prior to the introduction of the RBAC and authentication subsystem in Milestone 1.
- Why did existing auth tests not detect the gap? Existing auth tests focused on mutation endpoints (
/api/v1/execute,/api/v1/auth/*,/api/v1/tls/renew,/api/v1/presets/activate,/api/v1/plugins/execute), while file and audit tests only ran withRequireAuth: false. - What was the security impact? An unauthenticated remote attacker could enumerate server files, download arbitrary files from the secure directory, read internal application logs, and inspect audit trails even in hardened environments where authentication was strictly required.
- Root Cause: Lack of uniform authentication enforcement across all administrative and diagnostic handlers upon enabling
RequireAuth. - Applied Change / Fix:
- Added
p, err := env.resolvePrincipal(r)andRequireAuthchecks returning401 UnauthorizedacrossListFilesHandler,DownloadFileHandler, andListCommandsHandlerininternal/api/handlers.go. - Added
p, err := env.resolvePrincipal(r)andRequireAuthchecks returning401 UnauthorizedacrossAuditLogsHandler,AuditVerifyHandler,SystemLogsHandler, andActionHistoryHandlerininternal/api/audit_handlers.go. - Created
internal/api/endpoint_auth_test.goverifying 100% enforcement across all 7 endpoints for unauthenticated requests, invalid tokens, Bearer/X-API-Token credentials, and backward compatibility whenRequireAuth: false. - Result & Non-Regression Test: Verified by
TestProtectedEndpoints_RequireAuth_UnauthenticatedReturns401,TestProtectedEndpoints_RequireAuth_AuthenticatedSucceeds200,TestProtectedEndpoints_RequireAuthFalse_BackwardCompatibility, andTestProtectedEndpoints_RequireAuth_NilAuthManagerReturns401ininternal/api/endpoint_auth_test.go(100% pass across 126 tests ininternal/apiwith 90.3% coverage; 308 tests passing 100% across all 10 packages).
RCA-026 — Anonymous Authentication Privilege Escalation on Administrative Endpoints (CWE-284 / CWE-269)¶
- Date:
2026-11-02 - Observed Symptom: In
internal/api/auth_handlers.go, whenauth.require_auth: false(default configuration),resolvePrincipalreturnedauth.RoleAdminwith wildcard scopes["*"]for anonymous requests. Furthermore, administrative handlers (AuthUsersHandlerPOST/PATCH/DELETE,AuthTokensHandlerPOST/DELETE,AuthServiceAccountsHandlerPOST/DELETE,AuthServiceAccountRotateHandlerPOST) checkedif p.Type != "anonymous" && p.Role != auth.RoleAdmin, which evaluated tofalsefor any anonymous caller (p.Type == "anonymous"), allowing unauthenticated remote clients to create admin users, delete user accounts, issue Personal Access Tokens, and generate third-party service account credentials. - Root Cause Analysis (5 Whys):
- Why could unauthenticated callers create users and issue credentials? Because the authorization check
if p.Type != "anonymous" && p.Role != auth.RoleAdmininverted the logic by assuming anonymous callers should not be checked for admin role, whileresolvePrincipalalso assignedRoleAdminwith wildcard scopes["*"]to anonymous requests. - Why was
p.Type != "anonymous"used in the conditional? The author mistakenly intended "if authenticated but not admin, forbid", intending to exempt unauthenticated access in non-auth setups without realizing it opened administrative mutations to any unauthenticated caller. - Why did
resolvePrincipalassignRoleAdminand wildcard scopes["*"]to anonymous requests? WhenRequireAuth: falsewas implemented,resolvePrincipalgranted full administrator privileges as a shortcut so general endpoints (e.g., command execution) wouldn't be rejected byauth.Authorize. - What was the security impact? Critical privilege escalation: any unauthenticated attacker could remotely take over the tool by creating admin users, deleting legitimate accounts, or minting API tokens and service account secrets.
- Root Cause: Granting
RoleAdminwith wildcard scopes["*"]to anonymous callers inresolvePrincipalcombined with flawed boolean logicp.Type != "anonymous"that bypassed admin checks in administrative handlers. - Applied Change / Fix:
- Updated
resolvePrincipalininternal/api/auth_handlers.go: whenRequireAuth: false, anonymous principals are assignedRole: auth.RoleViewerand explicit non-admin operational scopes (commands:read,commands:execute,plugins:read,plugins:execute,mcp:access,files:read,audit:read), strippingRoleAdminand wildcard*. - Enforced strict administrative authorization across all mutation handlers in
internal/api/auth_handlers.go:if p.Type == "anonymous" || p.Role != auth.RoleAdmin { writeJSONError(w, "Admin role required...", http.StatusForbidden); return }and blocked anonymous callers from issuing or revoking Personal Access Tokens. - Added
TestAnonymousPrivilegeEscalationPreventionininternal/api/auth_test.goasserting HTTP 403 Forbidden across all 8 administrative endpoints for anonymous callers and verifying authenticated administrators retain full access. - Result & Non-Regression Test: Verified by
TestAnonymousPrivilegeEscalationPreventionininternal/api/auth_test.go(127 unit tests ininternal/apipassing 100% with 91.0% coverage; 309 tests passing 100% across all 10 packages).
RCA-027 — Concurrency Data Race on OS Preset Dynamic Activation and Residual Admin Check Bypasses¶
- Date:
2026-11-02 - Observed Symptom: In
internal/api/presets_handlers.go,ActivatePresetsHandlerdynamically mutatedenv.Config.Executor.Commands = core.MergeOSPresets(...). Concurrently, other request handler goroutines inExecuteCommandHandlerandListCommandsHandleriterated overenv.Config.Executor.Commandswithout mutex synchronization, causing a Go runtime data race on concurrent preset activation. In addition,ActivatePresetsHandler,TLSRenewHandler, andPluginDeclarativeRegisterHandlercheckedif p.Type != "anonymous" && p.Role != auth.RoleAdmin, which allowed unauthenticated anonymous callers to trigger live certificate rotations, declarative plugin registrations, and preset command expansions. - Root Cause Analysis (5 Whys):
- Why was there a data race when activating OS presets?
ActivatePresetsHandlerreassigned the slice header and mutated elements inenv.Config.Executor.CommandswhileExecuteCommandHandlerandListCommandsHandlerread the slice concurrently from separate HTTP worker goroutines without synchronization. - Why was
env.Config.Executor.Commandsnot synchronized?Commandswas originally loaded once at server startup as a static configuration slice, and dynamic runtime mutation viaMergeOSPresetswas added in Milestone 2 without introducing concurrency primitives. - Why could Prometheus metrics re-indexing cause deadlock if synchronized naively?
initConfiguredActionMetricsalso iteratesenv.Config.Executor.Commands; acquiring the same mutex insideinitConfiguredActionMetricswhen already held byActivatePresetsHandlerwould deadlock Go's non-reentrantsync.RWMutex. - Why did anonymous callers bypass admin authorization on
POST /api/v1/presets/activate,POST /api/v1/tls/renew, andPOST /api/v1/plugins/declarative? The inverted boolean checkif p.Type != "anonymous" && p.Role != auth.RoleAdminwas left in these three handlers when ACT-029 patched user and token administrative handlers, allowing anonymous callers (p.Type == "anonymous") to short-circuit the condition. - Root Cause: Lack of
sync.RWMutexsynchronization protectingenv.Config.Executor.Commandsduring runtime mutation combined with residual flawed boolean authorization conditions (p.Type != "anonymous") in administrative mutation endpoints. - Applied Change / Fix:
- Added
commandsMu sync.RWMutextoAPIEnvininternal/api/handlers.goand implemented thread-safe accessors (CommandsRLock,CommandsRUnlock,CommandsLock,CommandsUnlock,GetCommands,FindCommand). - Protected command slice reads in
ExecuteCommandHandlerviaenv.FindCommandandListCommandsHandlerviaenv.GetCommands. - Protected command slice mutation in
ActivatePresetsHandlerusingenv.commandsMu.Lock(), and separated Prometheus re-indexing intoinitConfiguredActionMetricsLockedto prevent recursive mutex deadlock. - Enforced strict admin authorization across
ActivatePresetsHandler,TLSRenewHandler, andPluginDeclarativeRegisterHandler:if p.Type == "anonymous" || p.Role != auth.RoleAdmin { writeJSONError(w, "Admin role required...", http.StatusForbidden); return }with audit logging. - Added
TestConcurrentPresetActivationAndCommandExecutionininternal/api/presets_test.goasserting thread safety across concurrent goroutines activating presets, listing commands, and executing commands. - Result & Non-Regression Test: Verified by
TestConcurrentPresetActivationAndCommandExecutionand full test suite (128 passed ininternal/apiwith 90.8% coverage, 310 passed across all 10 packages).
RCA-028 — SQLite Database Locking and Concurrency Contention under Multi-Goroutine Load¶
- Date:
2026-11-02 - Observed Symptom: Under concurrent execution of API commands, audit logging, and background workers, SQLite operations risked encountering
database is lockedorbusyerrors when multiple goroutines attempted simultaneous writes, or when concurrent readers blocked writers under default rollback journaling (journal_mode=DELETE). - Root Cause Analysis (5 Whys):
- Why did concurrent database operations encounter
database is locked? Because SQLite default rollback journaling locks the entire database file during writes, blocking concurrent readers and failing concurrent writers immediately. - Why did concurrent writers fail immediately instead of waiting? SQLite's default busy timeout is 0 ms (
busy_timeout=0), returning an immediatebusyerror if another connection holds a lock. - Why did multiple connections attempt simultaneous writes within the same Go process? Go's
database/sqlconnection pool defaults to unbounded open connections (maxOpen = 0), opening multiple physical connections to the SQLite file across HTTP handler goroutines. - Why is unbounded connection pooling problematic for SQLite? SQLite is an embedded single-writer database engine; having multiple connections in the same process attempt concurrent writes causes self-contention and lock conflicts.
- Root Cause: Lack of connection pool serialization (
SetMaxOpenConns(1)), absence of Write-Ahead Logging (journal_mode=WAL), absence of a busy wait timeout (busy_timeout=5000), and unconfigured synchronous/foreign key pragmas ininternal/database/db.go. - Applied Change / Fix:
- Bounded the Go connection pool to
SetMaxOpenConns(1),SetMaxIdleConns(1), andSetConnMaxLifetime(time.Hour)inConfigurePool. - Configured WAL mode (
PRAGMA journal_mode=WAL;), busy timeout (PRAGMA busy_timeout=5000;), synchronous NORMAL (PRAGMA synchronous=NORMAL;), and foreign keys (PRAGMA foreign_keys=ON;) inapplyPragmas. - Implemented
BuildDSNaugmenting connection strings with DSN query options for driver-level connection initialization. - Implemented
GetPragmaand connection pool getters (PoolStats,MaxOpenConns,MaxIdleConns,ConnMaxLifetime,BusyTimeout) for runtime verification. - Added comprehensive concurrency tests in
internal/database/db_test.gowith 40 parallel goroutines verifying zero locking errors on both in-memory and SQL-backed stores. - Result & Non-Regression Test: Verified by
TestBuildDSN,TestDatabaseConnectionPoolAndGetters,TestDatabasePragmasAppliedAndQueryable,TestConcurrentActionHistoryAccessInMemory, andTestConcurrentActionHistoryAccessSQLBackedininternal/database/db_test.go(100% pass across 12 tests ininternal/databasewith 95.2% coverage; 320 tests passing 100% across all 10 packages).
RCA-029 — Fake Mock Metric Fallback and Ignored Scrape Errors in SRE Prometheus Scraper Plugin¶
- Date:
2026-11-02 - Observed Symptom: In
internal/plugins/native_sre.go,PrometheusScraperPluginsilently returned hardcoded Prometheus metrics (api_executor_actions_total... 42,api_executor_heap_bytes 8452100) when HTTP scraping failed, and discarded errors returned bygetMetricsContent(content, _ := p.getMetricsContent(ctx, params)). Furthermore, non-2xx HTTP responses (e.g., 500, 404) were treated as valid exposition payloads without status validation. - Root Cause Analysis (5 Whys):
- Why did
scrape_metricsreturn fake metrics on failure? BecausegetMetricsContentcaughterr != nilfromclient.Do(req)and returned hardcoded sample metric text with anilerror to provide "mock self metrics". - Why was mock self metrics returned by default? Early prototyping intended to provide a working out-of-the-box demonstration without requiring a running Prometheus target.
- Why is this a system integrity and forensic honesty defect? It masked actual network partitions, dead endpoints, or exporter failures, emitting false telemetry and deceiving operators into believing the target service was healthy.
- Why were non-2xx HTTP responses unhandled?
resp.StatusCodewas never evaluated, reading error HTML/text bodies as if they were valid Prometheus exposition format. - Root Cause: Lack of strict error propagation in
Executeand silent fallback to synthetic mock data instead of requiring explicit opt-in (allow_mock: true). - Applied Change / Fix:
- Added
allow_mockaction parameter (default"false") toPrometheusScraperPluginactions. - Replaced default fake mock fallback in
getMetricsContentwith explicit error returns for network errors, timeouts, connection failures, and HTTP status codes outside 200-299. - Conditioned mock fallback strictly on
allow_mock: true. - Evaluated and propagated
errinExecute, returningStatus: "error"and the genuine error. - Implemented comprehensive test coverage in
internal/plugins/native_sre_test.gowithhttptest.Server. - Result & Non-Regression Test: Verified by
TestPrometheusScraperPlugin_RealScrapeSuccess,TestPrometheusScraperPlugin_UnreachableTargetGenuineError,TestPrometheusScraperPlugin_HTTP500GenuineError,TestPrometheusScraperPlugin_HTTP404GenuineError, andTestPrometheusScraperPlugin_ExplicitAllowMock(69 tests passing ininternal/plugins, full repository suite 329 tests passing 100% across all 10 packages).
RCA-030 — Inverted Authorization Check on MCP Trace Deletion, Variable-Time HMAC Verification, and Sibling Prefix Path Confinement¶
- Date:
2026-11-02 - Observed Symptom:
- In
internal/plugins/native_crypto.go,verify_hmaccompared computed digest with expected digest via standard string equality (computed == expected), vulnerable to timing side-channel attacks. - In
internal/api/handlers.go(DownloadFileHandler), path boundary check usedstrings.HasPrefix(absFilePath, absSecureDir). IfabsSecureDirwas/var/uploadsand a sibling directory/var/uploads_privateexisted,HasPrefixreturned true without verifying directory boundaries. - In
internal/api/mcp_handlers.go(DELETE /api/v1/mcp/traces), authorization check was inverted (if p.Type != "anonymous" && p.Role != auth.RoleAdmin), allowing unauthenticated anonymous callers to bypass admin checks and delete traces while blocking non-admin authenticated users. - Root Cause Analysis (5 Whys):
- Why was string equality used for HMAC verification? Standard equality was used for simplicity without considering side-channel timing discrepancy between byte-by-byte comparison and constant-time comparison.
- Why did path prefix check allow sibling directory bypasses?
strings.HasPrefixchecked raw string prefix rather than directory tree confinement (filepath.Relor path separator suffix). - Why did anonymous callers bypass the MCP trace deletion check? A Boolean logic inversion (
!= "anonymous" && != RoleAdmininstead of== "anonymous" || != RoleAdmin) left anonymous callers unchecked becausep.Type != "anonymous"evaluated to false. - Why did prior tests not catch the anonymous deletion vulnerability? The test suite previously ran
DELETE /api/v1/mcp/tracesbefore initializing auth, asserting that the anonymous call succeeded with 200 OK. - Root Cause: Inconsistent defense-in-depth patterns across handlers and lack of constant-time primitives for cryptographic verification.
- Applied Change / Fix:
- Used
crypto/subtle.ConstantTimeComparefor HMAC comparison ininternal/plugins/native_crypto.go. - Replaced path prefix check in
internal/api/handlers.gowithfilepath.RelandbaseWithSeppath separator enforcement. - Corrected authorization condition in
internal/api/mcp_handlers.gotoif p == nil || p.Type == "anonymous" || p.Role != auth.RoleAdmin. - Added unit tests across
internal/plugins/native_crypto_test.go,internal/api/files_test.go, andinternal/api/mcp_test.go. - Result & Non-Regression Test: Verified by
TestCryptoHashUtilityPlugin_VerifyHMAC_MatchingAndNonMatching,TestDownloadFileHandler_DirectoryBoundaryAndSiblingConfinement, andTestMCPEndpointsAndTraceInspection(71 tests ininternal/plugins, 129 tests ininternal/api, and 332 tests passing 100% across all 10 packages).
RCA-031 — Missing Root .dockerignore, RedHat Container Healthcheck Failure, and Suboptimal Docker Layer Caching¶
- Date:
2026-11-02 - Observed Symptom:
- The repository root had no
.dockerignorefile, transferring.git/,.worktrees/,.agents/, test databases (history.db), log files, and IDE directories into container build contexts, bloating context transfer time and risking credential/metadata leaks. - Running
docker-compose.os-test.ymlforapi-executor-redhatfailed its healthcheck (test: ["CMD", "curl", "-k", "-f", "https://localhost:8080/api/v1/commands"]) because theredhat/ubi9:latestbase image does not packagecurlby default. - In
Dockerfile,COPY . .was executed beforego mod tidyandgo install ..., invalidating Go dependency cache layers on every single application source code modification. - Root Cause Analysis (5 Whys):
- Why did the RedHat healthcheck fail? Because
curlwas missing from the container image. - Why was curl missing? RedHat UBI9 minimal images do not include
curlorca-certificatesin their standard package payload. - Why did Docker builds invalidate dependency downloads on every change? Because
COPY . .was placed before dependency resolution, busting the Docker layer cache when any repository file changed. - Why was build context unnecessarily large? No
.dockerignorefile existed at the repository root to exclude git metadata, local databases, and temporary directories. - Root Cause: Omission of
.dockerignore, absence of healthcheck dependencies in RedHat container image, and suboptimal Dockerfile instruction ordering. - Applied Change / Fix:
- Created root
.dockerignoreexcluding.git,.worktrees,.agents,bin/,tmp/,*.db,*.sqlite*,*.log,.vscode/,.idea/, and coverage artifacts. - Updated
docker/Dockerfile.redhatto installca-certificatesandcurl-minimalviadnf install -y --nodocs. - Reordered root
Dockerfileto rungo mod downloadandgo install ...immediately afterCOPY go.mod go.sum ./before copying application source. - Added
RUN go mod downloadtodocker/Dockerfile.redhatanddocker/Dockerfile.ubuntu. - Added
TestDockerHygieneAndIgnoreRulesindocs/branding_test.go. - Result & Non-Regression Test: Verified by
TestDockerHygieneAndIgnoreRulesandpython scripts/lint_dockerfile.pypassing cleanly (333 tests passing 100% across all 10 packages).
RCA-032 — Web Admin Console Spurious Initial 401 Error Banner, Unhandled Action Fetch Rejections, Outdated cURL Auth Header, and Race-Prone Refresh Coordination¶
- Date:
2026-11-02 - Observed Symptom:
- On initial page load or when unauthenticated (
!this.authToken), the Web Admin Console (web/static/index.html) displayed a red error banner ("Authentication failed (401)") becauseloadPrincipal()queriedGET /api/v1/auth/meand unconditionally setthis.statusBanner = d.error || ('Authentication failed (' + r.status + ')'). - The generated cURL snippet in
curlSnippet()emitted deprecated-H "X-API-Token: ..."instead of-H "Authorization: Bearer ...", causing cURL examples to mismatchheaders(). - Action methods executing
fetch()(activatePresets,loginUser,createUser,deleteUser,createPAT,revokeToken,createServiceAccount,rotateServiceAccount,deleteServiceAccount,registerDeclarativePlugin,loadDBTables,runDBQuery,sendRawMCP,renewTLSCertificate) lackedtry...catchblocks, triggering uncaught Promise rejections and leaving UI spinners/banners frozen upon network disconnections or server restarts. refreshAll()initiated 9 independent async functions without coordination orawait, leading to race-condition banner overwrites and unhandled background rejections.- Root Cause Analysis (5 Whys):
- Why was a red error banner visible on first page load? Because
loadPrincipal()handled 401 responses by settingstatusBannereven when the user had not yet provided an authentication credential. - Why was cURL authorization outdated? Because
curlSnippet()had not been updated when the backend was modernized to support standard Bearer authorization alongside Service Keys. - Why did UI actions crash on network drops? Because asynchronous
fetch()invocations were not enclosed in error boundaries (try...catch). - Why did panels experience race conditions? Because
refreshAll()fired async data loaders without synchronization orPromise.allSettled(). - Root Cause: Lack of unauthenticated state guards on initial load, outdated cURL string templates, absence of defensive error boundaries on user actions, and uncoordinated async panel refreshes in
web/static/index.html. - Applied Change / Fix:
- Guarded
this.statusBannerassignment inloadPrincipal()withif (this.authToken). - Updated
curlSnippet()to format-H "Authorization: Bearer ${this.authToken || 'gat_pat_<your_token>'}". - Enclosed all bare
fetch()action methods in defensivetry...catchblocks setting user-facing error banners. - Synchronized
refreshAll()usingawait Promise.allSettled([...])and updated callers to await its resolution. - Added non-regression unit tests in
internal/api/web_console_test.go(TestWebAdministrationConsole_ResilienceGuarantees). - Result & Non-Regression Test: Verified by
TestWebAdministrationConsole_ResilienceGuarantees(130 tests passing ininternal/apiand 334 tests passing 100% across all 10 packages).
RCA-033 — Quadratic Manifest File Parsing in E2E Test Setup and Redundant Duplicate Workflow Rule Files¶
- Date:
2026-11-02 - Observed Symptom:
- In
tests/e2e/setup_test.go(setupE2ETestServer), initializing an ephemeral test server invokedfilepath.WalkDiroverplugins/and executedpluginReg.LoadDeclarativeDirectory(filepath.Dir(path))on every single manifest file. Because directories contained up to 32 YAML manifests each,LoadDeclarativeDirectorywas redundantly called up to 32 times on the same folder, re-reading every file each time and causing ~7,800 unnecessary disk reads across E2E test runs. - In
.agents/rules/, three separate files (atomic-workflow.md,git-workflow.md,github-workflow.md) codified the atomic workflow with overlapping formulations and slight differences in granularity, creating rule sprawl and maintenance divergence. - Root Cause Analysis (5 Whys):
- Why did E2E server setup re-parse directories dozens of times? Because
filepath.WalkDirtriggered on individual file matches rather than directory entries, and invoked directory loading without caching previously visited folder paths. - Why was directory loading invoked per-file? Because the callback checked file extensions (
.yaml,.yml,.json) before invokingLoadDeclarativeDirectory(filepath.Dir(path)). - Why did multiple overlapping rule files exist in
.agents/rules/? Successive milestones introducedgit-workflow.mdandgithub-workflow.mdalongsideatomic-workflow.mdwithout pruning redundant predecessors. - What was the impact? Increased E2E initialization latency and potential confusion regarding which workflow rule was canonical.
- Root Cause: Lack of a directory visitation cache in
setup_test.goand absence of rule consolidation to a single canonical file in.agents/rules/. - Applied Change / Fix:
- Added
visitedDirs := make(map[string]bool)insetupE2ETestServer(tests/e2e/setup_test.go) soLoadDeclarativeDirectory(dir)executes strictly once per unique directory. - Consolidated all atomic workflow guidelines into
atomic-workflow.mdand deleted redundant copiesgit-workflow.mdandgithub-workflow.md. - Added non-regression tests in
tests/e2e/setup_test.go(TestE2ESetup_PluginDirectorySinglePassLoading) anddocs/branding_test.go(TestAgentRulesConsolidationAndDeduplication). - Result & Non-Regression Test: Verified by
TestE2ESetup_PluginDirectorySinglePassLoadingandTestAgentRulesConsolidationAndDeduplication(66 tests intests/e2e, 3 tests indocs, and full repository test suite 336 unit + 66 E2E tests passing 100%).
RCA-034 — Linear O(N) Credential Scan Under Exclusive Lock on Every Authenticated HTTP Request¶
- Date:
2026-11-08 - Observed Symptom: In
internal/auth/manager.go,Manager.AuthenticateCredentialiterated linearly over every entry inm.tokensandm.serviceAccountswhile holdingm.mu.Lock(), causingO(N)authentication latency and lock contention as the number of issued Personal Access Tokens and Service Accounts grew. - Root Cause Analysis (5 Whys):
- Why did credential authentication scale as O(N)? Because
AuthenticateCredentialranged over the fullm.tokensandm.serviceAccountsmaps keyed by entity ID (tok_...,svc_...) rather than credential hash. - Why were the maps keyed only by entity ID? Administrative CRUD operations (
RevokeToken,DeleteServiceAccount,RotateServiceAccountKey) reference credentials by their public ID rather than their secret hash. - Why did this become a hot-path bottleneck? Every authenticated API request invokes
resolvePrincipal->AuthenticateCredential, making credential lookup the most frequently executed path in the server. - Why was lock contention amplified?
AuthenticateCredentialacquiresm.mu.Lock()to updateLastUsedAtandUseCount/CallCount; holding that lock during a linear scan serialized concurrent HTTP requests. - Root Cause: Absence of secondary
O(1)hash-to-ID lookup indices (tokenByHashandserviceAccountByHash) onauth.Manager. - Applied Change / Fix:
- Added
tokenByHashandserviceAccountByHashmaps toauth.Managerininternal/auth/manager.goand implementedrebuildHashIndicesLocked(). - Synchronized index insertions, updates, and evictions across
NewManager,loadFromFile,DeleteUser,CreateToken,RevokeToken,CreateServiceAccount,RotateServiceAccountKey, andDeleteServiceAccount. - Updated
AuthenticateCredentialto performO(1)hash lookup followed byconstantTimeEqualsHexverification. - Added
TestAuthenticateCredential_O1HashIndexAndLifecycleininternal/auth/manager_test.go. - Result & Non-Regression Test: Verified by
TestAuthenticateCredential_O1HashIndexAndLifecycleininternal/auth/manager_test.go(5 tests passing ininternal/auth, full suite 337 tests passing 100% across all 10 packages).
RCA-035 — Per-Execution Regex Recompilation, Uncached Catalog Sorting, and Composite Parameter Stringification in Declarative Plugins¶
- Date:
2026-11-08 - Observed Symptom:
DeclarativePlugin.Executeininternal/plugins/declarative.gocalledregexp.Compile(paramDef.Pattern)on every action execution despiteNewDeclarativePluginalready compiling the same pattern at load time.Registry.ListFilteredininternal/plugins/plugin.goreconstructed all 305PluginInfostructs and executedsort.Slice(O(N log N)) on every catalog request.- Passing a composite value (
[]stringormap[string]any) intoparamsconverted it viafmt.Sprintf("%v", v)into"[invalid slice input]"or"map[key:value]", which matcheddocker-container-stats.yamlbecause^[a-zA-Z0-9. _\t-{}]+$contained an unescaped hyphen creating an ASCII range from\t(0x09) to{(0x7B). - Root Cause Analysis (5 Whys):
- Why was
regexp.Compilecalled on every execution?NewDeclarativePlugindiscarded the*regexp.Regexpreturned during validation instead of storing it onDeclarativePlugin. - Why did
ListFilteredsort 305 plugins on every request?Registrystored plugins only in an unorderedmap[string]Pluginwithout caching the sorted[]PluginInfoprojection. - Why did
docker-container-statsaccept slice and map inputs when Docker was running?DeclarativePlugin.Executedid not checkreflect.Kindbeforefmt.Sprintf("%v", v), and\t-{indocker-container-stats.yamlmatched[,], and:. - Why was this previously masked? When the
dockerdaemon was not running on the test host, subprocess execution failed with exit code 1, masking the validation pass. - Root Cause: Lack of pre-compiled regex storage, lack of sorted catalog caching in
Registry, missing scalar-kind enforcement inDeclarativePlugin.Execute, and an unescaped hyphen indocker-container-stats.yaml. - Applied Change / Fix:
- Stored pre-compiled
*regexp.Regexpinstances inDeclarativePlugin.compiledRegexduringNewDeclarativePluginand rejected compositereflect.Kindvalues inDeclarativePlugin.Execute. - Moved the literal hyphen to the end of the character class (
^[a-zA-Z0-9. _\t{}-]+$) inplugins/containerops/docker-container-stats.yaml. - Cached the sorted
[]PluginInfocatalog inRegistry.sortedCachewith automatic invalidation onRegister,RegisterOrReplace, andUnregister. - Added
TestDeclarativePlugin_PrecompiledRegexAndRegistryCatalogCacheininternal/plugins/plugins_test.go. - Result & Non-Regression Test: Verified by
TestDeclarativePlugin_PrecompiledRegexAndRegistryCatalogCacheandTestM2Adversarial_AllParameters_InvalidTypeRejection(72 tests passing 100% ininternal/plugins; full repository suite 338 tests passing 100% across all 10 packages).
RCA-036 — Unbounded Subprocess Output Buffering (cmd.CombinedOutput()) Risking Heap Exhaustion¶
- Date:
2026-11-08 - Observed Symptom: In
internal/core/executor.go,ExecuteCommandWithTimeoutinvokedcmd.CombinedOutput(), which reads all child stdout and stderr into an unboundedbytes.Bufferin memory, followed bystring(output)allocation and double retention insidedatabase.RecordActionandaudit.Record. A verbose or runaway command producing hundreds of megabytes of output before its timeout expired could exhaust server memory (OOM). - Root Cause Analysis (5 Whys):
- Why could a subprocess exhaust Go heap memory before its timeout fired? Because
os/exec.Cmd.CombinedOutput()uses an unrestrictedbytes.Bufferthat grows until EOF or process termination. - Why was a timeout alone insufficient to bound memory? Within a 15–30 second execution window, a fast local command can write hundreds of megabytes per second to stdout/stderr pipes.
- Why was memory pressure amplified downstream? Converting
[]bytetostring(output)duplicated the buffer on the heap, and storing that string in both the in-memoryaction_historyslice and theAuditLoggerring buffer retained the oversized payload. - Why can't the pipe simply be closed once the limit is reached? Closing the child's stdout/stderr pipe while it is still running causes
SIGPIPE/ broken-pipe failures in legitimate commands; excess bytes after the cap must be drained and discarded (len(p)returned) while marking the output as truncated. - Root Cause: Use of unbounded
cmd.CombinedOutput()instead of a boundedio.Writer(limitedOutputBuffer) capped atMaxCommandOutputBytes(1 MiB). - Applied Change / Fix:
- Defined
MaxCommandOutputBytes = 1 << 20(1 MiB) and implementedlimitedOutputBufferininternal/core/executor.go. - Replaced
cmd.CombinedOutput()inExecuteCommandWithTimeoutwithoutBuf := newLimitedOutputBuffer(MaxCommandOutputBytes)attached tocmd.Stdoutandcmd.Stderrfollowed bycmd.Run(). - Appended a deterministic truncation suffix (
\n...[output truncated at 1048576 bytes]) when output exceedsMaxCommandOutputBytes. - Added
TestLimitedOutputBufferAndMaxCommandOutputBytesininternal/core/executor_test.go. - Result & Non-Regression Test: Verified by
TestLimitedOutputBufferAndMaxCommandOutputBytesininternal/core/executor_test.go(40 tests passing 100% ininternal/core; full repository suite 339 tests passing 100% across all 10 packages).
RCA-037 — Per-Event os.OpenFile/Close Syscall Overhead Under Memory Lock and Per-Insert Statement Preparation¶
- Date:
2026-11-08 - Observed Symptom:
AuditLogger.Record(internal/audit/audit.go) calledos.OpenFileandf.Close()on every single audit event while holdingal.mu.Lock(), and also executedal.db.Execandal.logger.LogStructuredinsideal.mu.Lock(), blocking concurrent readers (Query,VerifyChain,Count) during disk and SQLite I/O.Server.recordTrace(internal/mcp/server.go) calledos.MkdirAll,os.OpenFile, andf.Close()on every MCP JSON-RPC trace event.DB.RecordAction(internal/database/db.go) calleddb.Prepare+defer stmt.Close()on every insert instead of a singledb.Execcall.- Root Cause Analysis (5 Whys):
- Why were file descriptors opened and closed on every event?
AuditLoggerandmcp.Serverstored only the path string (cfg.FilePath/cfg.TraceFilePath) instead of retaining an open*os.Filehandle across the server lifecycle. - Why did
AuditLogger.Recordblock concurrent readers during I/O?defer al.mu.Unlock()was placed at the top ofRecord, keeping the exclusive lock held across JSONL file writes, SQLite inserts, and structured log formatting. - Why did
DB.RecordActionprepare and close a statement on every call?RecordActionuseddb.Prepare+defer stmt.Close()without caching the statement, whereasdb.Execallowsdatabase/sqldrivers to execute parameterized inserts directly. - Why must persistent file handles have explicit
Close()lifecycle methods? On Windows, open file handles insidet.TempDir()prevent temporary directory removal unless closed viadefer Close()(cf.RCA-011). - Root Cause: Lack of persistent
*os.Filelifecycle management onAuditLoggerandmcp.Server, overly broad mutex scope inAuditLogger.Record, and redundant per-calldb.PrepareinDB.RecordAction. - Applied Change / Fix:
- Added persistent
file *os.FileandfileMu sync.MutextoAuditLogger(internal/audit/audit.go) andtraceFile *os.FileandfileMu sync.Mutextomcp.Server(internal/mcp/server.go), withClose() errorandHasOpenFile()/HasOpenTraceFile()methods wired intocmd/server/main.go. - Narrowed
al.mu.Lock()inAuditLogger.Recordstrictly to hash-chain computation and in-memory ring-buffer insertion, performing file, SQLite, and logger I/O afteral.mu.Unlock(). - Replaced
db.Prepare+defer stmt.Close()inDB.RecordAction(internal/database/db.go) with directdb.Exec. - Updated
internal/audit/audit_test.goandinternal/mcp/server_test.goto verify persistent handle lifecycle andClose(). - Result & Non-Regression Test: Verified by
TestAuditLoggerHashChainAndQuery,TestMCPServerLifecycleAndAllTools, andTestDatabaseSQLDriverBackedExecutionAndErrors(339 tests passing 100% across all 10 packages).
RCA-038 — 9 Copylocks Violations from Struct Embedding sync.RWMutex Value Copies¶
- Date:
2026-11-09 - Observed Symptom: Running
go vet ./internal/jobs/...returned 9 copylocks violations acrossinternal/jobs/job.go,internal/jobs/store.go, andinternal/jobs/jobs_test.go. - Root Cause Analysis (5 Whys):
- Why did
go vetflag copylocks errors? TheJobstruct embeds an unexportedmu sync.RWMutexto guard state, and several methods copied the struct value. - Where was the lock copied?
Snapshot()dereferenced the job pointer (snap := *j) and returnedJobby value, copyingj.muto the caller. - Why did
MemoryJobStorecopy locks? It was declared asjobs map[string]Job(storing values instead of pointers), causing every map lookup, assignment, and slice iteration to copy the lock. - Why did tests copy locks?
jobs_test.gopassedsnap(a value embeddingmu) directly tot.Errorf("%+v", snap), andm1_stress_challenge_test.gopassed&snap. - Root Cause: Returning struct values instead of pointer references (
*Job) for structs embedding synchronization primitives (sync.RWMutex). - Applied Change / Fix:
- Refactored
Job.Snapshot()to return*Job, allocatingsnap := &Job{...}with scalar and map fields copied explicitly, leavingsnap.mufreshly initialized and zeroed. - Refactored
MemoryJobStore.jobstomap[string]*Job, returningsnap.Snapshot()onGetJobandListJobsto maintain deep-cloning immutability without copying locks. - Formatted scalar fields in
t.Errorfinjobs_test.goand passedsnapdirectly tostore.SaveJobinm1_stress_challenge_test.go. - Result & Non-Regression Test: Verified by
go vet ./...exiting with code 0 (zero copylocks violations), and unit testsTestJobSnapshot,TestMemoryJobStoreCRUDAndFilter, andTestChallenger_MemoryJobStore_DeepCloningImmutabilitypassing 100%.
RCA-039 — Engine Log Buffer Memory Leak on Enqueue Rejection and pruneTicker Data Race / SIGSEGV on Shutdown¶
- Date:
2026-11-09 - Observed Symptom:
- When
Engine.Enqueuewas rejected due to full queue or store failure, the 2 MiBJobLogBufferremained registered ine.logBuffersindefinitely. - Completed terminal jobs never had their log buffers evicted, accumulating unbounded memory.
Engine.Shutdownsete.pruneTicker = nilwhilepruneLoopconcurrently evaluatedcase <-e.pruneTicker.C:, causing data race and fatal SIGSEGV nil pointer dereference undergo test -race.handleJobExecutionwrote directly tojob.ResultData = reswithoutjob.mu.Lock().- Root Cause Analysis (5 Whys):
- Why did
logBuffersleak on rejection?e.logBuffers[jobID]was inserted beforeSaveJobandqueue.Enqueue, without cleanup in error return blocks. - Why did terminal jobs retain buffers?
e.store.Prunepruned store records butEnginehad no log buffer pruning mechanism. - Why did
pruneLoopcrash on shutdown? Go select statement evaluates channel operands (e.pruneTicker.C) on every loop iteration; settinge.pruneTicker = nilfrom another goroutine raced and caused nil pointer dereference. - Why was
job.ResultDataunsynchronized?ResultDatalacked a mutex-guarded accessor method, unlike other state fields. - Root Cause: Missing error recovery cleanup in
Enqueue, missing memory eviction loop, unsynchronized field access, and accessing a mutable struct field inside a goroutineselectloop without local variable capture orsync.WaitGroupcoordination. - Applied Change / Fix:
- Added
delete(e.logBuffers, jobID)andjob.SetLogBuffer(nil)onEnqueueerror branches. - Implemented
pruneLogBuffers()/PruneLogBuffers()inEngineto evict terminal buffers older thanMaxJobAgeor pruned from store; resete.logBuffersonShutdown. - Passed ticker instance directly to
pruneLoop(ticker *time.Ticker)stack and coordinated shutdown withe.pruneWg sync.WaitGroup. - Added
SetResultData(res)andGetResultData()toJob, and guarded worker terminal transitions inWorkerPool.runJob. - Result & Non-Regression Test: Verified by
TestEngineLogBufferEvictionOnEnqueueFailure,TestEngineLogBufferPruning, andTestChallenger_Engine_ShutdownPruneLoopNilPointerRaceundergo test -v -racein WSL (0 races, 0 panics).
RCA-040 — Trailing Slash Normalization Inversion for Static Job Path in normalizeMetricPath¶
- Date:
2026-11-09 - Observed Symptom: Requests to
/api/v1/jobs/(with a trailing slash) were classified as"other"instead of being normalized to"/api/v1/jobs"in Prometheus metrics, failingTestNormalizeMetricPath/jobs_with_trailing_slash. - Root Cause Analysis (5 Whys):
- Why was
/api/v1/jobs/normalized to "other"? BecausenormalizeMetricPathevaluatedtrimmed := strings.TrimSuffix(path, "/")resulting in"/api/v1/jobs", and then calledsub := strings.TrimPrefix(trimmed, "/api/v1/jobs/"). - Why did TrimPrefix fail? Because
trimmedwas"/api/v1/jobs", which does not contain the trailing slash required by the prefix pattern"/api/v1/jobs/". - What happened next?
subretained the full string"/api/v1/jobs", andstrings.Split(sub, "/")produced 4 elements (["", "api", "v1", "jobs"]). - Why did that return "other"? Because
len(parts) == 4, falling through the segment boundary checks. - Root Cause: Attempting to trim a trailing-slash prefix on a string that had already been stripped of trailing slashes without checking for exact equality with the base route.
- Applied Change / Fix:
Added an explicit equality check
if trimmed == "/api/v1/jobs" { return "/api/v1/jobs" }immediately after stripping the trailing slash ininternal/api/router.go. - Result & Non-Regression Test: Verified by
TestNormalizeMetricPath(63 table cases passing 100%) andTestPrometheusMetricJobRouteNormalization.
RCA-041 — Data Race Under Go Race Detector Between Background Worker State Transition and SubmitJobHandler Response Serialization¶
- Date:
2026-11-09 - Observed Symptom: Executing
go test -race ./internal/api/...under Linux/WSL consistently triggered a Go runtime data race:Write at 0x... by goroutine (jobs.(*Job).SetRunning at job.go:222)concurrent withPrevious read at 0x... by goroutine (api.(*APIEnv).SubmitJobHandler at job_handlers.go:256). - Root Cause Analysis (5 Whys):
- Why was a data race detected? A worker goroutine called
job.SetRunning()which lockedjob.muand wrotej.Status = StatusRunning, whileSubmitJobHandlerreadjob.Statusconcurrently without acquiringjob.mu. - Why did SubmitJobHandler have the live pointer to Job?
Engine.Enqueue(jobReq)enqueued the*Jobinto the priority queue and returned the same live pointer to the HTTP handler. - Why did the worker start so quickly? The queue's condition variable immediately signaled a waiting worker in
workerLoop(), which began executingrunJob()concurrently beforeSubmitJobHandlerencoded its JSON response. - Why did SubmitJobHandler read
job.Statusdirectly? The handler constructedSubmitJobResponseusing direct struct field access rather than thread-safe accessors or the contractual submission state. - Root Cause: Lack of memory synchronization on mutable
Job.Statusin HTTP handlers; direct struct field read instead of utilizingjobs.StatusQueuedfor initial submission or thread-safe getterjob.GetStatus(). - Applied Change / Fix:
- Replaced direct read
Status: job.Statuswith constantStatus: jobs.StatusQueuedinSubmitJobHandler(internal/api/job_handlers.go:256), providing 100% deterministic conformance with the HTTP 202 Accepted submission contract and zero lock contention. - Replaced direct field read
status = job.Statuswithstatus = job.GetStatus()inGetJobLogsHandler(internal/api/job_handlers.go:479). - Replaced direct field read
if job.Status.IsTerminal()withif job.GetStatus().IsTerminal()inCancelJobHandler(internal/api/job_handlers.go:518). - Result & Non-Regression Test: Verified by
go test -race -v ./internal/api/...under WSL Ubuntu 24.04 passing 100% with 0 data races, andgo test -v -cover ./...on Windows passing 432/432 tests across all 11 packages.
RCA-042 — Asynchronous Job Process-Tree Cancellation Latency on Windows Under Multi-Core Test Concurrency¶
- Date:
2026-11-09 - Observed Symptom: During high-concurrency stress testing (
internal/jobs/m1_stress_challenge_test.goandtests/e2e/tier3_cross_feature_test.go) on Windows hosts under full multi-core parallel execution, cancelling an active asynchronous job occasionally exceeded tight 200ms test assertion timeouts. - Root Cause Analysis (5 Whys):
- Why did job cancellation take longer than 200ms on Windows? Terminating a process tree on Windows requires spawning an external helper executable (
taskkill.exe /T /F /PID <pid>), unlike Unix wheresyscall.Kill(-pgid, syscall.SIGKILL)is an instant in-kernel syscall (~1-5ms). - Why was taskkill delayed? Under intense CPU saturation (multiple parallel packages running
go test), Windows process creation and executable loading fortaskkill.exeincur scheduling latency up to 300–500ms. - Why did child process stdout/stderr pipes delay command termination? If child processes spawned sub-children holding inherited stdout/stderr file handles open, Go's
cmd.Wait()blocked until pipe EOF unless an explicit exit deadline was enforced. - How did this impact command classification? If context cancellation raced with command completion,
errreturned byexec.CommandContextcould be ambiguous without expliciterrors.Is(ctx.Err(), context.Canceled)probing. - Root Cause: Operating system disparity in process tree termination primitives (Windows
taskkillvs Unix process group signal) exacerbated by stdout/stderr pipe descriptor retention under multi-core parallel test load. - Applied Change / Fix:
- Configured
cmd.WaitDelay = 200 * time.Millisecondininternal/core/executor.goto ensure child processes holding inherited pipe handles do not block termination indefinitely. - Implemented
ErrCommandCancelledandIsCommandCancelledininternal/core/executor.goto deterministically classify cancelled commands. - Calibrated test polling intervals to 10ms and cancellation latency thresholds to 800ms for parallel Windows test suites, while maintaining sub-second SLA in production.
- Verified in
tests/e2e/setup_test.goviapollJobTerminalwith a safe 5-second deadline. - Result & Non-Regression Test: Verified by
TestTier3_Combination_AsyncJob_ImmediateCancellationSubprocessTreeKillintests/e2e/tier3_cross_feature_test.goandTestChallenger_Engine_CancellationLatencyininternal/jobs/m1_stress_challenge_test.gopassing 100% on both Windows and Linux.
RCA-043 — Windows Process-Tree Cancellation Delay Causing Backpressure E2E Test Flakiness¶
- Date:
2026-11-09 - Observed Symptom: During empirical challenger verification of release v2.1.0,
go test -v ./tests/e2e/...failed on Run 1 with exit code 1 (TestTier2_Boundary_Jobs_QueueCapacityBackpressurefailed attier2_boundary_test.go:456: expected 202 Accepted after queue drained, got 429: {"error":"Queue capacity exceeded"}). - Root Cause Analysis (5 Whys):
- Why did the test fail with HTTP 429? Because the queue was still at maximum capacity (
queued_jobs == 2) whenhttpSubmitJobwas called. - Why was the queue still full after calling
httpCancelJob? Because the cancellation request had not completed process termination: the worker had not yet killed the blocker process, updated the job status tocancelled, and dequeued the next waiting job. - Why was process termination delayed? On Windows, terminating a process tree spawns
taskkill.exe /T /F /PID <pid>. Under concurrent test execution and CPU pressure, launching and executingtaskkill.exeplus OS pipe closing takes up to 600–800ms. - Why was a fixed sleep used? The test author assumed a 500ms sleep would always suffice for process teardown and worker queue drainage.
- Root Cause: Relying on a fixed delay (
time.Sleep(500 * time.Millisecond)) for an asynchronous multi-process teardown sequence on an operating system with non-deterministic process termination latency (Windows), rather than an active polling loop with a bounded timeout. - Applied Change / Fix:
In
tests/e2e/tier2_boundary_test.go, replaced the fixed 500ms sleep with a bounded queue polling loop (evaluating every 50ms up to a 3-second deadline) untilqueued_jobs < QueueCapacitybefore submitting the subsequent job. - Result & Non-Regression Test:
Verified by
go test -v -run TestTier2_Boundary_Jobs_QueueCapacityBackpressure -count=5 ./tests/e2e/...andgo test -v ./tests/e2e/...passing 100% deterministically across consecutive runs on Windows.
2. Technical Dead-Ends & Abandoned Leads (IMP-XXX)¶
IMP-001 — Monolithic Catch-All Pull Requests¶
- Reason for Abandonment: Violates atomic engineering governance (
1 item = 1 Issue = 1 Branch = 1 PR = 1 Merge).
IMP-002 — Unbounded Dynamic Action Labels in Prometheus¶
- Reason for Abandonment: Replaced with
normalizeActionLabelcapped atMaxDynamicActionLabels = 64.
IMP-003 — Using systemctl in Containerized OS Preset Tasks¶
- Reason for Abandonment: Replaced with container-safe inspection commands (
dpkg-query,apt-get -s upgrade,rpm -qa,dnf repolist,ps -ef,ss -tuln).
IMP-004 — Storing Plaintext Personal Access Tokens or Service Account Keys¶
- Reason for Abandonment: Plaintext token storage would expose all remote credentials if
auth_store.jsonwere leaked. Replaced with one-time secret return (gat_pat_...,gat_svc_...) and SHA-256 hashed storage compared viacrypto/subtle.ConstantTimeCompare.
IMP-005 — Unsanitized {{param}} Shell Interpolation or Unrestricted SQL Execution in Plugins¶
- Reason for Abandonment: Passing declarative plugin parameters to
sh -cor allowing arbitrary SQL statements (DROP,DELETE,PRAGMA,ATTACH,--,;) indb-exposurewould enable remote code execution or data tampering. Replaced withexec.CommandContextdirect argv substitution validated against^[a-zA-Z0-9._:/-]+$(or custom regex) andValidateReadOnlySQLenforcing single-statementSELECTwithLIMITbounding.
IMP-006 — External Raster Image Links for Repository Logo and Banner¶
- Reason for Abandonment: External image URLs break in offline/air-gapped environments and cannot be verified in unit tests. Replaced with repository-local pure SVG assets (
docs/assets/logo.svg,docs/assets/header-banner.svg) validated viaencoding/xmlindocs/branding_test.go.
IMP-007 — Unbounded Dynamic Job ID or Action Labels in Prometheus Metrics¶
- Reason for Abandonment: Registering dynamic Prometheus labels such as unique UUID
job_idor unvalidated user-suppliedactionstrings on gauges or counters (job_executions_total{job_id="..."}) causes an unbounded time-series cardinality explosion (\(O(N)\) memory growth), which can exhaust server memory in Prometheus/Grafana. Replaced with normalized route patterns (/api/v1/jobs/:id,/api/v1/jobs/:id/logs,/api/v1/jobs/:id/cancel) innormalizeMetricPathand bounded action labels vianormalizeActionLabelcapped atMaxDynamicActionLabels = 64with fallback to"other".
IMP-008 — Raw String Interpolation or Unbounded In-Memory Buffering for Live Process Log Streaming¶
- Reason for Abandonment: Streaming process stdout/stderr via raw string concatenation (
str += chunk) creates quadratic GC heap churn (\(O(N^2)\) allocations), and unbounded buffering risks out-of-memory crashes (OOM) if a subprocess outputs hundreds of megabytes. Replaced withJobLogBufferenforcing a strict memory ceiling (DefaultMaxLogBytes = 2 MiB), overflow ring draining, deterministic[output truncated]marker, and offset-based chunked read semantics (GET /api/v1/jobs/{id}/logs?offset=X) returningnext_offsetandeof.
3. Current Approximations & Simplifying Assumptions (APP-XXX)¶
| ID | Module | Approximation / Assumption | Impact | Condition for Removal |
|---|---|---|---|---|
APP-001 |
internal/database, internal/jobs |
SQLite local file storage (history.db) for action_history and job_history, with pure-Go in-memory fallback (MemoryJobStore) when compiled with CGO_ENABLED=0. |
Single-node persistence; in-memory mode resets on process restart. | Enable CGO in container builds or add pure-Go SQLite / PostgreSQL driver. |
APP-002 |
internal/core/tls |
Self-signed ECDSA P-256 certificate generated by default when no external CA-signed cert is mounted. | Browsers and curl require -k or downloading /api/v1/tls/certificate into trust store. |
Mount enterprise PKI certificate or enable ACME (IDEA-002). |
APP-003 |
internal/audit |
Sliding window in-memory audit cache (MaxMemoryLog = 1000) alongside optional JSONL file / SQLite table. Cryptographic SHA-256 tamper-evident chaining verified across Category: "job". |
In-memory query window is bounded to prevent heap growth; tamper-evident verification covers complete lifecycle (job.enqueued, job.started, job.completed, job.cancelled). |
Query persistent SQLite/SIEM store for historical archives beyond 1,000 events. |
APP-004 |
internal/auth |
Pure-Go iterated SHA-256 (10,000 rounds + 128-bit random salt) password hashing and RequireAuth: false default unless configured. |
Avoids external golang.org/x/crypto dependency while preserving backward compatibility for unauthenticated local configs. |
Set auth.require_auth: true in production and optionally migrate to Argon2id (IDEA-001). |
APP-005 |
internal/plugins |
db-exposure simulates SELECT projection over action_history when running in pure-Go in-memory fallback mode (db.Conn() == nil). |
Ensures identical read-only SQL validation and deterministic test/runtime behavior even when compiled with CGO_ENABLED=0. |
Compile with CGO SQLite or connect to an external SQL engine. |
APP-006 |
internal/mcp |
Synchronous HTTP JSON-RPC 2.0 transport (POST /api/v1/mcp) with bounded in-memory ring buffer (MaxTraces = 500) + SQLite/JSONL persistence. |
Request/response RPC calls complete in a single HTTP round-trip without requiring long-lived SSE state. | Add Streamable HTTP / SSE server-initiated notification transport if bidirectional MCP server-to-client sampling is required (IDEA-005). |
APP-007 |
web/static |
Single-file zero-build Web Administration Console (web/static/index.html) using Alpine.js and Tailwind CSS via CDN. |
Requires no Node.js/npm build step; air-gapped deployments without internet access need vendored static CSS/JS assets. | Vendor Alpine.js and compiled CSS into web/static/vendor/ for offline air-gapped environments. |
APP-008 |
tests/e2e |
Synthetic domain catalog fixtures pre-populated in test harness to guarantee 300+ plugins across 10 domains. | Allows full catalog scale and multi-domain operations testing before domain pack manifests are integrated into plugins/. |
Fully fulfilled and replaced in Milestones 2, 3, and 5 by 281 live filesystem declarative plugin YAML manifests and 24 native pure-Go plugins (total 305/306 plugins). |
APP-009 |
internal/jobs |
In-memory log buffer retained per active job bounded to 2 MiB (DefaultMaxLogBytes = 2 MiB), with completed log eviction upon engine pruning. |
Bounded memory consumption; historical logs after memory eviction rely on output summaries stored in JobStore. |
Add persistent chunked log archive to disk or object storage if unbounded historical log retrieval is needed (IDEA-007). |
APP-010 |
internal/api |
In-memory chunked log streaming via JobLogBuffer returns eof=true and empty chunk after buffer eviction, relying on output summary in JobStore. |
Historical logs after buffer eviction cannot be re-streamed byte-for-byte via the chunked log endpoint. | Add persistent chunked log archive to disk or object storage (IDEA-007). |
4. Unimplemented Ideas & Future Roadmap (IDEA-XXX)¶
| ID | Priority | Target Module | Description |
|---|---|---|---|
IDEA-001 |
P2 |
internal/auth |
External OIDC / OAuth2 identity provider federation and Argon2id password KDF. |
IDEA-002 |
P2 |
internal/core/tls |
Automatic ACME / Let's Encrypt certificate provisioning. |
IDEA-003 |
P3 |
internal/audit |
Remote syslog / OpenTelemetry OTLP sink for audit events. |
IDEA-004 |
P3 |
internal/plugins |
Out-of-process gRPC / WebAssembly (WASI) plugin sandboxing for untrusted third-party modules. |
IDEA-005 |
P3 |
internal/mcp |
Streamable HTTP / SSE notification stream and stdio CLI bridge for local desktop MCP hosts. |
IDEA-006 |
P3 |
web/static |
Virtualized catalog scrolling / infinite scroll for Web Console Tab 5 when plugin ecosystem scales beyond 1,000 plugins. |
IDEA-007 |
P2 |
internal/jobs |
Distributed Redis / PostgreSQL queue backend and persistent S3/MinIO chunked log streaming for multi-node deployments. |
IDEA-008 |
P2 |
internal/api |
WebSocket / Server-Sent Events (SSE) live push streaming endpoint (/api/v1/jobs/{id}/stream) for real-time output and status updates without client HTTP offset polling. |
IDEA-009 |
P3 |
internal/jobs |
Job Dependency DAG & Workflow Chaining: Allow defining multi-step workflow pipelines where downstream jobs execute only upon successful completion of prerequisite jobs (e.g., diagnostic run followed by automated remediation). |
IDEA-010 |
P3 |
web/static |
Web Console Live Output Terminal via xterm.js: Upgrade Tab 9 log modal with ANSI color escape code rendering and interactive terminal controls. |