diff --git a/docs/roadmap/audit/03-complexity.md b/docs/roadmap/audit/03-complexity.md new file mode 100644 index 0000000..b4b24d7 --- /dev/null +++ b/docs/roadmap/audit/03-complexity.md @@ -0,0 +1,355 @@ +# Complexity And Maintainability Audit + +Reviewed on 2026-11-30 against commit +`3c00167912a47e566a1622097dcea2904fe50094`. + +## Scope And Method + +The review covered repository-owned configuration/domain derivation, +application orchestration, stages, manifests, artifact resolution, restore, +publication, file operations, and external adapters. It considered both local +control-flow complexity and duplicated responsibilities across package +boundaries. Production code and repository tests were left unchanged. + +Codebase-memory-mcp supplied symbol discovery, call relationships, and +cyclomatic/cognitive metrics. Its Go index merges some same-named receiver +methods, including stage `Run` methods, so those rankings are incomplete. A +temporary standard-library Go AST scanner supplemented the graph with +receiver-qualified metrics across non-test Go files. `gocyclo`, `gocognit`, and +`staticcheck` were not installed. + +The scanner's **decision score** is one plus the count of `if`, `for`, `range`, +non-default case/communication clauses, and `&&`/`||` expressions inside a +function, including nested closures. **Span** includes comments and blank +lines from the function declaration through its closing brace. These are +screening signals, not formal quality thresholds or active-LOC measurements. +Representative results were: + +| Function | File | Decision score | Span | +| --- | --- | ---: | ---: | +| `extractStage.Run` | `internal/stage/extract.go` | 56 | 200 | +| `trimStage.Run` | `internal/stage/trim.go` | 55 | 326 | +| `prepareStage.Run` | `internal/stage/prepare.go` | 44 | 238 | +| `publishStage.Run` | `internal/stage/publish.go` | 39 | 208 | +| `assessSessionReadiness` | `internal/app/session_readiness.go` | 35 | 116 | +| `inspectSessionState` | `internal/app/session_state_command.go` | 33 | 129 | +| `executeSelectedStage` | `internal/app/runner_stage_execution.go` | 31 | 125 | + +The graph additionally reported cognitive scores of 81 for +`inspectSessionState`, 78 for `assessSessionReadiness`, and 51 for +`preflight.Check`. Source inspection determined which scores corresponded to +useful refactoring seams. Guard clauses and explicit failure ordering account +for substantial scores in otherwise readable functions. + +No benchmarks, production measurements, or live-provider tests were used. Two +temporary offline diagnostics, supplied through Go's `-overlay` facility, +confirmed the reporting defect in CX-01. The metric scanner and diagnostics +ran with the maintained Go 1.27.4 toolchain and were not added to the repository. + +## CX-01 — P2: Audio discovery is duplicated and inspection rejects valid inputs + +Status: Open + +**Code.** [Preparation](../../../internal/stage/prepare.go): +`resolveLocalAudioFiles` (line 311), `localAudioDestinations` (line 381), and +`listS3AudioObjects` (line 487). +[Operator inspection](../../../internal/app/operator_inspection.go): +`resolveLocalInspectionAudioPaths` (line 207) and +`inspectRemoteAudioPresence` (line 101). + +**Complexity.** Preparation and inspection independently implement relative-path +resolution, explicit-file versus directory discovery, FLAC filtering, file +checks, duplicate handling, and deterministic ordering. The local discovery +functions occupy 56 and 54 lines respectively and both have graph cognitive +scores of 25. Remote discovery repeats prefix/list/filter/basename logic with +different return shapes. Maintaining these implementations requires tracing +both call paths to know which rules actually govern accepted audio. + +**Confirmed correctness issue.** Given `first/speaker.flac` and +`second/speaker.flac` in `inputs.audio_files`, preparation accepts both and +assigns distinct managed destination names. Inspection instead rejects the +second file with `duplicate audio basename`. Consequently `session status` +can report valid local audio as unavailable and return an error even though +preparation can succeed. Configuration validation does not prohibit this +selection. The existing +[distinct-recording test](../../../internal/stage/audio_destinations_test.go) +also protects preparation's preservation of these recordings. + +One temporary diagnostic executed the real preparation stage and confirmed two +distinct recorded audio destinations. A second exercised +`inspectLocalAudioPresence` over the same input shape; its expected-available +assertion failed with the duplicate-basename error. This is a local +inspection defect, separate from the S3 planning defect in FC-03. + +**Refactoring opportunity.** Give read-only audio discovery one owner, naturally +the existing `internal/audio` area or a small adjacent domain helper. Return +normalized local sources or remote object identities and let preparation own +copying/checkpoints while inspection owns reporting. Keep session-prefix +construction at the Narratio boundary and pass explicit prefixes to storage. +Share the remote object filter and duplicate rules as well as local discovery. + +Fix inspection to accept distinct same-basename local recordings. Retain +preparation's rejection of duplicate resolved local sources, destination +disambiguation, and the separately selected S3 basename rule. A shared helper +must express these real differences rather than impose a new global basename +restriction. A durable regression should exercise accepted local inputs +through preparation and operator inspection. + +## CX-02 — P3: Prepared stable inputs have parallel materialization and resume definitions + +Status: Open + +**Code.** [prepare.go](../../../internal/stage/prepare.go): `prepareStage.Run`; +[prepare_resume.go](../../../internal/stage/prepare_resume.go): +`currentPrepareSourceInputs`, `currentPreparePartySourceInputs`, and +`prepareSourceInputsMatch`; +[prepare_party.go](../../../internal/stage/prepare_party.go): +`materializeCanonicalPartyInputs`; +[semantic_contracts_initial.go](../../../internal/stage/semantic_contracts_initial.go): +`prepareStableInputSemantics`. + +**Complexity.** Execution builds input records through several local closures, +individual render/write/register blocks, a glossary list, and a separate party +writer. Resume reconstructs much of the same rendering and glossary dependency +information in a different representation, then maintains another explicit +managed-kind set. Semantic selection has its own stable-input enumeration. +Adding a prepared source requires finding all the relevant definitions and +keeping their kind, content, dependencies, and presence semantics aligned. + +The existing +[prepared-source descriptors](../../../internal/artifactpolicy/policy.go) +already centralize source IDs, manifest kinds, and filenames. The opportunity +is to reuse that investment, not introduce a competing registry. + +**Refactoring opportunity.** Build a small stage-owned stable-input description +from the resolved domain data, reused by materialization and current-source +identity calculation. Share the glossary name/descriptor/dependency mapping and +party/player rendering. Derive managed-kind membership from those descriptions +where appropriate. Keep audio and previous-session hydration as explicit phases +with their distinct acquisition rules. This also shortens `prepareStage.Run` +without replacing it with a configurable preparation engine. + +Preserve the distinction between raw materialized checksums and the intentional +semantic normalization of campaign/session snapshots. Semantic fingerprint +projection should continue to select result-affecting evidence, not hash all +configuration or perform materialization. Keep the ConfigKit result immutable +and use only post-handoff Narratio domain data. Focused regression coverage +should compare fresh preparation with reuse after unchanged and changed +inputs, including combined-glossary dependencies and source relocation. + +## CX-03 — P3: Trim and extraction mix invocation mechanics with product acceptance + +Status: Open + +**Code.** [trim.go](../../../internal/stage/trim.go): `trimStage.Run` (line 23); +[extract.go](../../../internal/stage/extract.go): `extractStage.Run` (line 38); +[extract_preflight.go](../../../internal/stage/extract_preflight.go): +`BuildNotariusReadiness`. + +**Complexity.** Trim's 326-line entry point interleaves input/layout discovery, +disabled-copy behavior, optional Scriptorium debug rendering, bounds generation +and validation, selector interpretation, Seriatim execution, output promotion, +and extensive diagnostic-map assembly. The disabled and enabled branches both +perform trimmed-transcript validation and promotion. A change to bounds +execution requires reading through several unrelated phases. + +Extraction's 200-line entry point similarly combines resolved options, +reference snapshots, invocation paths, subprocess execution, completion and +bundle checks, staged lane selection, canonical promotion, and evidence +construction. Execution and `BuildNotariusReadiness` independently resolve the +binary, configuration/working paths, timeout, and force-to-cache-refresh option. +Those copies must remain aligned even though probe and execution destinations +legitimately differ. + +**Refactoring opportunity.** Extract cohesive operations with typed inputs and +results: obtain validated bounds, optionally render diagnostics, produce the +trimmed transcript, and promote accepted products. Keep a small explicit +disabled branch and share the final transcript acceptance path. For extraction, +share the resolved Notarius invocation options with readiness, then isolate +native-completion acceptance and staged-lane promotion from request setup. +Return diagnostic information from those operations instead of using one +long-lived mutable map as their communication channel. + +The benefit should be fewer duplicated rules and smaller reasoning scopes, +not a helper for each statement. Keep orchestration visible in `Run`, CLI +translation in adapters, validation before canonical promotion, reference +verification after invocation, and failed-attempt diagnostics available. +Existing phase separation in +[analysis execution](../../../internal/stage/analyze_artifact_execution.go) +and shared request construction for polish offer local examples. No generic +subprocess-stage or workflow framework is warranted. + +## CX-04 — P3: Inspection and readiness combine collection, policy, and presentation + +Status: Open + +**Code.** [session_state_command.go](../../../internal/app/session_state_command.go): +`inspectSessionState` (line 109); +[session_readiness.go](../../../internal/app/session_readiness.go): +`assessSessionReadiness` (line 93); +[downstream_readiness.go](../../../internal/app/downstream_readiness.go): +`checkDownstreamReadiness` (line 27); +[preflight/check.go](../../../internal/preflight/check.go): `Check`. + +**Complexity.** Inspection loads ledger/catalog evidence, discovers a remote +commit, reads locks and publication state, inspects stable inputs/audio/previous +requirements, mutates a public report, and accumulates failures in one function. +Readiness combines preparation outcome interpretation, transcript projection, +tool checks, severity/category formatting, storage initialization, and lock +reporting. Deep per-tool initialization/build/check branches further obscure +which work is blocked, canceled, or independently eligible. + +`preflight.Check` has a related smaller seam: its target loop handles transport +failures and cancellation while also interpreting required/conditional inputs, +variables, incomplete reports, and duplicate missing-variable findings. +These rules are easier to understand separately from iteration and I/O. + +**Refactoring opportunity.** Keep explicit top-level sequencing, but collect +cohesive local-state, remote-publication, and input-readiness results before +projecting them into reports. Extract tool-specific readiness operations that +retain the initialized adapters on the invocation. Existing result types and +the current `record` helper provide a starting point; a broad check registry is +unnecessary. Isolate Scriptorium report interpretation as a pure operation +over one target/report, leaving inspection calls and cancellation in the loop. + +Preserve partial findings, independent checks after ordinary failures, blocked +checks when preparation is unavailable, cancellation, and the distinction +between preparation and readiness. Keep inspection read-only and standalone +preflight's preparation/provider effects explicit. Reuse current report shapes; +there is no need for new commands, stricter readiness rules, or exact diagnostic +wording guarantees. The nested-error performance issue is already EF-05 and is +not a new finding here. + +## CX-05 — P3: Artifact dependency semantics span several representations and owners + +Status: Open + +**Code.** [validate_scriptorium.go](../../../internal/config/validate_scriptorium.go): +`ValidateScriptoriumArtifactDependencies` (line 265); +[analyze_fingerprint.go](../../../internal/stage/analyze_fingerprint.go): +`normalizedAnalyzeDependencyKeys` and `orderConfiguredAnalyzeArtifacts`; +[analyze_plan.go](../../../internal/stage/analyze_plan.go): +`planAnalyzeWork` and `AnalyzeTargetClosure`; +[analyze.go](../../../internal/stage/analyze.go): `staleAnalyzeDependentClosure`; +[effective_set.go](../../../internal/artifacts/effective_set.go): +`EffectiveArtifactSet`; +[previous_requirements.go](../../../internal/artifacts/previous_requirements.go): +`CollectPreviousArtifactRequirements`. + +**Complexity.** Configuration builds normalized dependency adjacency and a DFS +for validation. Stage code separately normalizes edges, builds topological +ordering, expands prerequisite closure, and constructs reverse adjacency for +invalidation. Other consumers receive `EffectiveArtifactSet`, whose keys are +explicit/enabled targets rather than the prerequisite-inclusive work set. Its +comment describes artifacts an invocation will execute, which obscures that +distinction. Several consumers must reconstruct enough graph semantics to ask +what inputs or capabilities the invocation needs. + +The omission in FC-01 demonstrates the maintenance risk of these interfaces: +preparation collects previous inputs from targets while analysis separately +expands prerequisites. EF-02 records the repeated reverse-index construction +cost; neither defect is duplicated as a new correctness/performance finding. + +**Refactoring opportunity.** Centralize normalized configured-artifact graph +mechanics under a small domain owner, potentially alongside the separately +derived `config.ArtifactCatalog`. Reuse its dependency view for validation, +deterministic ordering, prerequisite queries, and dependent traversal. Expose +target selection and required work closure distinctly to preparation, +preflight/planning, analysis, and restore. Narrow domain helpers are sufficient; +a general graph library or workflow engine is unnecessary. + +Keep execution flat and canonical. Artifact force/publication targets remain +distinct from prerequisites, and invalidation eligibility remains caller policy. +Preserve family-origin diagnostics and semantic dependency fingerprints. Do not +merge this graph with the fixed stage invalidation relation: they represent +different domains. The outcome should be one definition of dependency +mechanics and clearer caller contracts, not another effective configuration. + +## CX-06 — P3: Unstructured metadata carries cross-package control evidence + +Status: Open + +**Code.** [publish.go](../../../internal/stage/publish.go): `publishMetadata` +(line 316); +[publish_output_plan.go](../../../internal/stage/publish_output_plan.go): +`publishOutputOutcomeMetadata`; +[cleanup_plan.go](../../../internal/stage/cleanup_plan.go): +`validateCleanupPublishEvidence` (line 84); +[artifact_inspection.go](../../../internal/app/artifact_inspection.go): +`committedPublishOutputOutcomes` (line 41); +[extraction_evidence.go](../../../internal/artifacts/extraction_evidence.go): +`InspectExtractionEvidence`. + +**Complexity.** `StageRecord.Metadata` serves both free-form diagnostics and +machine-consumed evidence. Publication writes string-keyed completion and +outcome maps; cleanup reconstructs required types/keys and identity evidence; +application inspection manually decodes outcomes. Extraction similarly writes +metadata in stage code and reads it in artifact resolution. A producer/consumer +change can compile while silently changing what another package recognizes. +Publication outcomes also require separate handling of freshly built +`[]map[string]any` and JSON-decoded `[]any`. + +**Refactoring opportunity.** Start with the publication completion/outcome +payload: provide narrowly typed construction and decoding under an existing +shared contract owner. Let consumers use named fields while retaining +stage-specific decisions, such as cleanup eligibility, at the stage boundary. +Apply the same treatment to extraction control evidence if it removes repeated +producer/consumer knowledge. Keep arbitrary diagnostic metadata flexible. + +This can preserve the existing JSON shape; a new manifest schema or generic +metadata framework is not needed just to centralize conversion. Fresh versus +decoded collection shapes are normal JSON behavior, not a legacy migration +surface. Preserve missing/malformed evidence handling and test a persistence +round trip as well as direct in-memory use. Typed decoding does not replace +identity checks or make successful publication imply that every local output +matches a carried remote object; FC-02 remains a separate correctness issue. + +## Deliberately Retained Complexity + +The audit does not recommend a package split merely because `internal/stage` +and `internal/app` are large. They already contain 51 and 54 non-test Go files +respectively. Moving unchanged branches between files would not address the +duplicated models or mixed responsibilities above. + +Several complex areas have useful existing boundaries: + +- Publication exposes immutable uploads, commit creation, lock revalidation, + and pointer selection in an understandable ordered sequence. Restore + separates discovery, planning, conflict classification, and installation. + Keep those protocol boundaries visible rather than hiding them in a generic + transaction abstraction. +- The runner's explicit stage lifecycle and manifest save ordering coordinate + real failure transitions. Shared invocation handling and checkpoint helpers + already consolidate behavior. A lower decision count alone would not justify + rewriting them. +- Artifact-family expansion and manifest/evidence validation contain many + genuine domain rules. Prefer the shared dependency/source models identified + above to mechanically fragmenting every validator. +- File-operation helpers already have narrow owners. The inspected path + walkers have different read/create/install responsibilities; this audit did + not establish that replacing them with one configurable FileOps framework + would simplify their contracts. +- ConfigKit, CommandKit, external tool semantics, streaming transport, and + adapter isolation remain appropriate upstream/boundary responsibilities. + +## Review Outcome + +Six findings warrant consideration: one confirmed P2 reporting defect with a +cross-package consolidation opportunity, and five P3 maintainability +opportunities. Fix CX-01 first. The highest-leverage structural work is sharing +prepared-input definitions and artifact dependency semantics; phase extraction +can then reduce the reasoning scope of stage and operator entry points. +Publication metadata typing is a narrower follow-up. These are opportunities, +not a requirement to implement all refactors together. + +Earlier open findings remain in [01-correctness.md](01-correctness.md) and +[02-efficiency.md](02-efficiency.md). Apart from CX-01, this pass established no +additional ordinary correctness defect. It does not establish the absence of +other defects or guarantee a net LOC reduction. The main expected gain is fewer +independent definitions and clearer ownership; helpers that only relocate +complexity should be avoided. + +Validation: `GOTOOLCHAIN=go1.27.4 go test ./...`, the focused documentation-link +check, and `git diff --check` passed. The temporary expected-available inspection +diagnostic failed as described in CX-01; the corresponding preparation +diagnostic passed. No bug fixes or refactors were implemented in this pass.