diff --git a/docs/roadmap/audit/06-error-handling.md b/docs/roadmap/audit/06-error-handling.md new file mode 100644 index 0000000..8f02fa9 --- /dev/null +++ b/docs/roadmap/audit/06-error-handling.md @@ -0,0 +1,179 @@ +# Error-Handling Audit + +Reviewed on 2026-11-24 at source revision +`8cfe330194ea0a4d06ede98655d886ede0dcc4e1`. + +## Scope And Results + +Reviewed error detection, wrapping, classification, diagnostics, serialization +fallbacks, file/output failures, configuration/bootstrap failures, cancellation, +and shutdown across application packages and their dependency boundaries. +Used codebase-memory-mcp for discovery and source inspection, checked contracts +and existing tests, and ran standalone diagnostics against the real CLI. +Checked the selected PromptKit v0.25.0 and CommandKit v0.8.0 behavior where it +determines what the executable actually reports. This was not an exhaustive +audit of upstream library implementations. + +One additional operator-diagnostic weakness warrants consideration. The existing +canceled-file-read defect and test failure-cleanup weakness also remain relevant. +No other substantiated error-handling defect was found in the reviewed paths. +The diagnostic recommendation below does not establish a requirement to render +all causes, change exit classifications, or expose sensitive internal details. + +## Current Architecture + +ConfigKit owns resolved configuration and native load diagnostics; PromptKit +owns definitions, preparation, execution, and framework errors. CommandKit and +its integrations own CLI outcomes and presentation finalization. Scriptorium +maps these values into application CLI effects and HTTP responses, owns server +lifecycle, and shares one engine across HTTP requests. HTTP errors are deliberately +coarse and omit wrapped causes. ReleaseKit owns release mechanics. See the +[component overview](../../internal/overview.md) and +[adapter internals](../../internal/adapters.md). + +## 1. Actionable CLI Startup Context Survives Only In The Returned Cause (P3) + +**Relevant code:** `newEngine` in +[engine.go](../../../internal/adapter/cli/engine.go), `runPrompt` in +[native_run.go](../../../internal/adapter/cli/native_run.go), `frameworkFailure` +and `requestFailure`, lines 23–68 of +[outcomes.go](../../../internal/adapter/cli/outcomes.go), listener failure at +lines 52–54 of [server.go](../../../internal/adapter/cli/server.go), and the +status-only process handoff at line 26 of +[main.go](../../../cmd/scriptorium/main.go). + +**Failure conditions:** An otherwise resolved configuration contains a malformed +message template or an unavailable `content_file`; alternatively, the configured +HTTP listen address cannot be used. These are plausible operator-correctable +startup failures, not provider-payload errors. + +**Expected improvement:** Preserve current failure classification and privacy +choices while giving operators focused, useful context about the affected +resource and failure category. The operations workflow depends on captured +diagnostics to locate and correct faults. This is an actionability weakness, +not a violation of a promise that arbitrary error causes appear on stderr. + +**Actual behavior and evidence:** A temporary program called the real +`cli.Execute` with synthetic configurations and captured both streams and its +returned Outcome. All failing cases below returned status 1 with empty stdout. + +| Condition | Terminal explanation | Useful information retained only in Cause | +| --- | --- | --- | +| Message content `{{` | Could not initialize PromptKit configuration. | `/promptkit/prompts/0/messages/0`, invalid template syntax, unclosed action. | +| Missing message file | Could not initialize PromptKit configuration. | The `content_file` configuration path, unavailable filename, and not-found cause. | +| Invalid listen address | Could not listen for HTTP requests. | The selected address and address-syntax failure. | + +The template/file cases behaved the same for `run` and `serve`; verbose mode +did not add the cause. Debug mode added dispatch/outcome tracing, but still +omitted the useful failure context. Native `promptkit list prompts` also failed +with a generic list explanation because its engine factory encountered the +same capture error. The complete wrapped cause remained available to the Go +caller throughout, so error identity and Go-level propagation are not broken. +The executable returns only the outcome's Status, making that cause unavailable +to its operator. + +CommandKit deliberately separates Cause from operator-facing Explanation; it +does not automatically render causes. The constructor errors in these examples +match PromptKit's ErrInvalidConfig but are not ConfigKit LoadErrors, so the +existing `frameworkFailure` diagnostic adapter does not enrich them. Merely +routing `run` through that helper would not resolve these examples. +Ordinary `config validate` correctly succeeded for the template/file fixtures: +configuration inspection deliberately does not capture message resources or +compile templates. Moving that work into configuration inspection would change +an established lifecycle, not repair the reporting gap. + +**Potential remediation:** Add deliberate, safe operator-facing context for +application-owned startup failures, using native Explanation/details rather +than relying on WithCause to print it. For listener failures, the application +already has the selected address and typed network error context. For framework +capture failures, prefer upstream-supported structured diagnostics and their +native ckprompt presentation; request upstream support if the public API lacks +the necessary safe resource/category information. Keep native workflows and +typed causes intact. Do not parse formatted error strings, import upstream +internals, or indiscriminately print Cause: those approaches risk exposing +provider payloads, prompt content, or credentials. Changing status 1 to status 2 +is not part of this recommendation. + +## Previously Recorded Failure-Path Findings + +- **Canceled file reads (production, P2):** `Read` checks context only before + entering file helpers in + [artifact_reader.go](../../../internal/adapter/http/artifact_reader.go). + Expected cooperative handling would carry cancellation through acquisition + and avoid successful completion after it has been observed. Actual FIFO + acquisition can remain blocked after cancellation and later return a nil + reader error; an engine timeout may be reported only after external input + releases the read. Thread context through the helpers, check it during reads + and before success, and align unsupported-file handling with the ordinary + upstream reader. See + [correctness finding 3](01-correctness.md#3-restricted-file-reads-discard-cancellation-and-can-stall-on-fifos-p2) + and the [HTTP cancellation evidence](04-concurrency.md#1-file-acquisition-can-outlive-request-cancellation-p2-previously-known). + This does not require immediate interruption of every synchronous operation. +- **Capacity-test failure cleanup (test only, P3):** The shared-capacity test in + [handler_test.go](../../../internal/adapter/http/handler_test.go) releases and + joins its first worker only after several assertions. An early fatal failure + bypasses cleanup, and an incorrectly admitted second synchronous request can + stall before release. Expected failure cleanup would cancel and join owned + workers regardless of assertion outcome. Use test-controlled cancellation, + cleanup registered before launch, and a bounded second request. See + [concurrency finding 2](04-concurrency.md#2-shared-capacity-test-does-not-own-workers-on-failure-paths-p3-test-only). + +These are unresolved existing findings, not additional discoveries of this pass. + +## Deliberate Behavior And Checks That Do Not Justify New Requirements + +- **Ignored reporter returns:** Report/Info/Warning/Progress delivery failures + are retained by CommandKit and considered during native finalization, even + when the immediate return is ignored. Existing partial-output and failed- + diagnostic-writer tests exercise this. Adding a parallel failure accumulator + would duplicate upstream behavior. +- **Wrapping and mapping:** Configuration, engine, and file wrappers preserve + causes with `%w`; report rendering/close failures are joined. HTTP uses typed + identities, including specific artifact errors before broader categories. + Operation timeout, parent cancellation, and provider-only timeout retain + their documented precedence. Completed invalid content remains a delivered + domain result, not an operational error. +- **HTTP explanations and writes:** Generic messages intentionally protect + internal causes. After a response write fails or is partial, another JSON + response cannot reliably repair the connection. No contract requires a new + logging channel or retry of the already executed prompt. Success is not + retroactively reclassified because cancellation races with formatting. +- **Serialization fallback:** Marshal failure selects a fixed string-only + internal-error envelope; encoded overflow selects the compact response-too- + large envelope. That fallback is intentionally not re-limited and does not + carry an execution report. No recursive fitting algorithm is needed. +- **Partial delivery and state:** A requested report is attempted after main + output failure, close/render errors survive, and an existing nonzero domain + status is retained on report-file failure. Partial/truncated files and + resultless failures leaving old reports untouched are documented choices, + not missing rollback. ConfigKit owns native secrets-bootstrap environment + effects; later failure does not imply an application rollback requirement. +- **Cleanup and lifecycle:** Read-only file Close is best-effort; report-file + Close errors are reported. Shutdown joins its cancellation callback and keeps + Serve/Close/cancellation causes, without promising arbitrary handler drain. + The release launcher propagates host-tool failures and exec status; the + adopted workflow fails its explicit checks. No local retry/recovery framework + or publication rollback was inferred from those paths. + +The [CLI](../../cli.md), [HTTP API](../../api.md), +[source internals](../../internal/sources.md), and +[subprocess contract](../../integrations/subprocess.md) remain the owners of +these established behaviors. Other earlier correctness/resource findings are +not reclassified as new error-handling defects here. + +## Validation And Limits + +- Go 1.27.0 on Linux/amd64: uncached repository-wide tests selected by + `Failure|Error|Invalid|Reject|Cancellation|Deadline|Timeout|Partial|TooLarge` + passed. These include error mapping/privacy, malformed inputs, bootstrap + failure, partial delivery, report failure, and cancellation/timeout cases. +- Standalone CLI diagnostics for template capture, missing content files, + native inspection, verbose/debug reporting, and listener failure completed + under the race detector. They used only synthetic data and no provider or + credentials. +- Application/tool code remains unchanged from the preceding audits; their + successful full race-suite/vet checks were not repeated as unrelated new + coverage. Documentation links and whitespace were checked. +- Only this document was added. No production code or repository tests were + modified. Passing tests and these diagnostics do not establish correct error + handling for every dependency failure or unexercised path.