# Maintainability And Complexity Audit Reviewed on 2026-11-24 at source revision `8e31004270f52211e2c7f05d257c1237f1512ea1`. ## Scope And Method Reviewed application-owned functions, file responsibilities, package boundaries, and representative integration tests. Used codebase-memory-mcp's function and method inventory, cyclomatic/cognitive estimates, and call/import information to locate candidates, then checked the source. Graph resolution can confuse identically named symbols; source imports and actual calls determined package relationships. Separate `gocyclo`, `gocognit`, and `golangci-lint` commands were not installed. No performance measurements or empirical testing were needed. The following production hotspots illustrate the graph's estimates. These are navigation aids, not standardized measurements, refactoring requirements, or proposed complexity limits. | Function | Source lines | Cyclomatic estimate | Cognitive estimate | | --- | ---: | ---: | ---: | | CLI `requestFailure` | 36 | 16 | 51 | | HTTP `ServeHTTP` | 143 | 22 | 31 | | HTTP `mapRunError` | 34 | 16 | 31 | | CLI `queueDiagnostics` | 18 | 7 | 17 | | Configuration `validateDocument` | 35 | 11 | 14 | Three opportunities warrant consideration: two within adapter packages and one across the HTTP/report package boundary. They are maintainability improvements, not release blockers or findings that the architecture needs replacement. No additional correctness bug was discovered. The three existing findings in [01-correctness.md](01-correctness.md) remain open and take priority over optional cleanup. ## Current Architecture Scriptorium remains a thin CLI/HTTP executable. ConfigKit resolves the shared application document; PromptKit owns definitions, preparation, and execution; CommandKit and its integrations own native CLI workflows and presentation. The HTTP service shares one engine and adds transport/deployment policy. ReleaseKit owns release mechanics. There is no application framework facade or durable execution workflow. See the [component overview](../../internal/overview.md) and [adapter internals](../../internal/adapters.md). ## 1. Separate The HTTP Handler's Request And Response Phases **Priority:** Medium. **Scope:** Within `internal/adapter/http`. **Evidence:** `Handler.ServeHTTP`, lines 43–185 of [handler.go](../../../internal/adapter/http/handler.go), combines routing, limited strict JSON decoding, trailing-token checks, request validation, PromptKit request construction, observer setup, execution, context-sensitive error classification, and success DTO construction. The response literal alone maps artifact, validation, metadata, usage, and optional report/output fields. Decode failures repeat the same size-versus-invalid-JSON response selection. **Why this matters:** Independent transport and projection changes all touch the orchestration method. A reader must distinguish pre-execution failures from execution failures while also reviewing field-by-field mapping. This mixes responsibilities beyond the necessary complexity of the HTTP contract. **Potential refactoring:** Extract a few cohesive private helpers for strict request decoding, validated DTO-to-RunRequest mapping, and RunResult-to-response projection. Keep `ServeHTTP` as the readable request lifecycle, including one execution and optional collector attachment. Move pure projection helpers out of the orchestration file if that improves navigation; avoid an interface or generic middleware pipeline for every phase. Preserve the existing wire format, numeric presence, native validation handoff, context/error precedence, report opt-in, and complete-response size handling. The earlier precision finding should be fixed explicitly rather than preserved as incidental decoding behavior. Existing HTTP behavioral tests remain the primary protection; extraction alone does not justify duplicate helper tests. ## 2. Consolidate CLI Configuration Diagnostics And Flatten Failure Selection **Priority:** Medium. **Scope:** Within `internal/adapter/cli`, at its ConfigKit handoff. **Evidence:** `runPrompt`, lines 77–89 of [native_run.go](../../../internal/adapter/cli/native_run.go), and `serveWithListener`, lines 23–35 of [server.go](../../../internal/adapter/cli/server.go), repeat the same evidence selection: read sources/findings from a successful result, prefer a wrapped `configkit.LoadError` when present, adapt diagnostics, then queue them. `frameworkFailure` in [outcomes.go](../../../internal/adapter/cli/outcomes.go) performs related native error adaptation. The same file's `requestFailure` nests configuration-error classification and a second sentinel switch inside the default of the initial timeout/cancellation switch. **Why this matters:** Several entry points independently implement the same configuration-evidence bridge. Maintaining safe diagnostics and precedence requires inspecting multiple command paths. The nested failure selection adds mental bookkeeping even though its intended priority is an ordered sequence. This is a drift risk, not evidence of a newly demonstrated behavior mismatch. **Potential refactoring:** Give the repeated result/error evidence selection and native adaptation one small CLI-local helper, then let callers queue its diagnostics and use its explanation. Reuse that extraction where appropriate for engine-construction errors while retaining their distinct heading and explanation composition. Flatten `requestFailure` into an ordered selection with configuration classification after timeout/cancellation and before the remaining PromptKit failure cases. Keep the actual ConfigKit result and typed errors, their causes, safe native writers, and current classification precedence. Leave resolution in `internal/config` and standard inspection in ckconfig/ckprompt. This does not call for another load, cache, reconstructed evidence model, acquisition framework, or combined CLI/HTTP error classifier. The adapters intentionally have different outcome policies. ## 3. Co-locate The HTTP-Only Execution Projection With Its Consumer **Priority:** Low; optional package-boundary simplification. **Scope:** Across `internal/report` and `internal/adapter/http`. **Evidence:** [report.go](../../../internal/report/report.go) is 104 lines and exposes `Collector`, `Execution`, `Usage`, and `TokenCount` plus their collection API. The package defines HTTP JSON field names, millisecond conversions, and bounded outcome/failure vocabulary. Its only production consumer is the HTTP adapter: [dto.go](../../../internal/adapter/http/dto.go) embeds the report type in success and error responses, and `ServeHTTP` creates and reads the collector. CLI delivery uses the native RunResult rather than this package. **Why this matters:** This is not a complex algorithm. It is an opportunity to reduce conceptual surface: one HTTP representation spans a general-sounding package, an exported cross-package API, and the adapter's DTOs. HTTP report changes require following that boundary even though there is no second production consumer. **Potential refactoring:** Move the collector, projection, and focused tests into a dedicated HTTP adapter file, keeping implementation types private where practical. Retain existing JSON shapes, terminal-only collection, unknown-value handling, detached snapshots, and per-request ownership. Update the component inventory if the package is removed. No public HTTP change or CLI reporting redesign is needed. Keeping the small separate package is also reasonable if its isolated responsibility is judged more valuable than reducing the boundary. Current usage does not justify adding a shared reporting interface or speculative multi-adapter framework. ## Candidates That Do Not Warrant Additional Refactoring Now - `mapRunError` is already a flat, ordered mapping of distinct public errors. Its branch count mostly represents necessary HTTP policy. Replacing it with a registry or universal classifier would obscure precedence without a clear maintenance benefit. `queueDiagnostics` similarly expresses four distinct native delivery choices directly. - Configuration validation contains short domain checks and resource loops; it does not need a validator framework or generalized visitor. - `handler_test.go` is large (1,948 lines), and lifecycle tests have high graph estimates. Source review shows much of that complexity comes from explicit assertions, cancellation coordination, and meaningful integration phases. Grouping HTTP tests into behavior-focused files is a reasonable navigation cleanup when those areas change, but size alone does not justify rewriting them or hiding synchronization in a fixture framework. - The remaining CLI composition/loading helpers, terminal projection logic, process entrypoint, and ReleaseKit launcher are small and direct. Preserve the existing native ownership and shared-server lifecycle rather than adding layers solely to reduce a metric. ## Validation And Limits This pass changes only this audit document. Source locations, package consumers, documentation links, and whitespace were checked. No application tests or benchmarks were run, and no refactor was implemented. The findings are scoped recommendations, not a guarantee that other maintainability or correctness issues do not exist.