# Complexity And Maintainability Audit ## Baseline, Method, And Scope Reviewed revision `83352f78aea1e2dea23621688e83c7c0cf5ede7d` on 2026-11-24. Production code is unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; the subsequent commits contain the [correctness](01-correctness.md) and [efficiency](02-efficiency.md) reports. This pass changes only this report. A fresh full codebase-memory-mcp index, `notarius-complexity-audit`, provided function length, branching, cognitive-complexity, call-site, and package-boundary data. All indexed function/method pages were collected and their numeric metrics ranked locally; 2,070 non-test Go symbols were available for production triage. High-ranking test functions were examined separately. Source inspection and call traces then distinguished actionable maintenance costs from necessary complexity. The executable, excluded by the index, was inspected directly and remains a thin native application entry point. No standalone `gocyclo`, `gocognit`, `golangci-lint`, or `staticcheck` executable was found on PATH. No tool dependencies were installed. The graph's metrics are heuristics, including nested callback bodies, not independent standardized scores or proposed quality gates. Size and a high score alone do not justify refactoring. No application tests, benchmarks, production runs, or empirical performance measurements were conducted for this static audit. The review covered pipeline resolution/preparation/execution, native producer and capture integration, CLI/configuration boundaries, D&D normalization and validation, typed codecs, source metadata, semantic reconciliation, output/state helpers, registrars, and representative high-complexity tests. It is risk-directed rather than an exhaustive proof of every function. ## Current Architecture Notarius retains the fixed typed pipeline: ```text input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output ``` The composition root assembles native ConfigKit, PromptKit, and CommandKit integration, registries, physical state, and reporting. The pipeline framework owns typed preparation, complete candidate assessment, native producer coordination, one bounded ready-job pool, ordered generated-reference handoffs, and accepted-result reuse. Artifact families own domain interpretation, identity, normalization, validators, codecs, and contextual projections. Assets remain content-only; ReleaseKit owns release mechanics. The main maintenance pressure is concentrated in orchestration and repeated adaptation code, not a need to replace these boundaries. The recommendations retain native kit ownership, typed artifacts, domain-specific policies, fixed stages, existing configuration choices, and current failure/ownership semantics. They do not propose a new workflow engine, a general-purpose reflection layer, new restrictions, or stronger release/security guarantees. ## Measured Hotspots These are graph-reported source metrics at the reviewed revision. They guided inspection; they are not acceptance thresholds. | Function | Source lines | Branch complexity | Cognitive estimate | Assessment | | --- | ---: | ---: | ---: | --- | | `pipeline.RunProducer` | 269 | 64 | 118 | Several stateful lifecycles in one function; CPLX-001. | | `pipeline.validateGeneratedBindings` | 68 | 20 | 79 | Deeply nested orchestration plus per-binding rules; CPLX-002 and BUG-001. | | `config.validatePipelineProfiles` | 89 | 26 | 74 | Repeated structural interpretation across packages; CPLX-003. | | `cli.resolveCLIReferenceTargets` | 70 | 23 | 68 | Repeated scope-specific filtering and diagnostics; CPLX-003. | | `source.cloneMetadataValue` | 82 | 25 | 67 | Mostly justified type-specific handling; a slice-identity defect is BUG-002. | | `pipeline.ResolvePipeline` | 188 | 42 | 60 | Resolution orchestration mixed with structural checks; CPLX-002/003. | | `pipeline.Run` | 252 | 43 | 51 | Stage execution mixed with debug/output envelopes; CPLX-005. | | `pipeline.resolveReferenceTargetBindings` | 120 | 31 | 48 | Binding normalization, precedence, conflicts, and completeness together; CPLX-002. | | `cli.selectedReferenceTargets` | 127 | 25 | 46 | Independently reconstructs selected composition; CPLX-003. | | `cli.pipelineRunCommand` | 156 | 34 | 38 | Declaration, invocation lifecycle, and terminal presentation together; CPLX-006. | | Registry `Normalize` methods | 127–133 each | 24–25 each | 27–28 each | Similar stateful lifecycle repeated in three packages; CPLX-004. | `pipeline/profile.go` is 1,635 lines and contains configuration/resolved types, JSON handling, composition resolution, reference rules, validator selection, copying, capability logic, and digest construction. `cli/reference_selectors.go` is 588 lines. Their responsibilities, rather than those lengths alone, make them useful consolidation/decomposition targets. ## Findings Summary Priority below means relative value within a refactoring backlog, not a claim that ordinary runs are failing. | ID | Priority | Scope | Opportunity | | --- | --- | --- | --- | | CPLX-001 | High | Within `framework/pipeline` | Make producer attempt state and execution phases explicit. | | CPLX-002 | Medium | Within `framework/pipeline` | Separate resolution responsibilities and per-binding checks. | | CPLX-003 | High | `core/config`, `framework/pipeline`, `cli` | Share structural pipeline interpretation and selected-target inventory. | | CPLX-004 | High | Three D&D normalizer packages and shared helpers | Consolidate the common semantic-registry lifecycle. | | CPLX-005 | Medium | Within `framework/pipeline` | Give runner stages cohesive private helpers. | | CPLX-006 | Medium | Within `cli` | Separate native command declaration from invocation/capture lifecycle. | | CPLX-007 | Medium | `core/config` and `framework/pipeline` | Give pipeline values one pure copying implementation, separate from normalization. | | CPLX-008 | Low | CLI tests | Separate maintained-example checks by responsibility. | Two additional correctness defects are recorded after the refactoring findings. ## Refactoring Findings ### CPLX-001 — Producer Execution Has Too Much Coupled Mutable State **Evidence:** [RunProducer](../../../internal/framework/pipeline/producer.go#L17) contains native initial preparation/execution, accepted-result lookup, capture composition, interpretation, assessment, continuation callbacks, terminal disposition, and cache storage. Its local `evaluate` and native `Next` callbacks mutate `candidate`, `guidance`, `failure`, `assessmentError`, and `accepted`; continuation adds pending capture and recording-error state. Fourteen production callers across scene planning, extraction, and normalization depend on this helper. **Maintenance cost:** Understanding one exit requires remembering which variables were cleared by a previous callback, whether the response was delivered, whether an error is fatal or permits fallback, and which capture remains unfinished. Cache and capture branches obscure the central candidate lifecycle. Existing comments protect important decisions, but the whole state must still be held in the reader's head. **Potential refactoring:** Keep the public helper as the composition point and introduce small private result/state values for a delivered candidate's interpretation/assessment and an in-flight native attempt. Extract cohesive initial/cache execution, candidate evaluation, and correction-request construction functions or methods. Reuse the existing cache, capture, and terminal-disposition helpers. A reader should be able to follow the top-level lifecycle without tracing mutations across two large closures. Keep `Engine.Run`/`RunPrepared`/`Coordinate` native; do not introduce a replacement completion interface or application retry/history engine. Preserve final-turn assessment, candidate invalidation when another attempt begins, undelivered-result handling, cancellation precedence, capture failures, cache-hit behavior, and strict/permissive disposition. A private typed state object is useful only if it makes these transitions clearer, not as a new extensibility framework. **Behavioral protection to inspect:** [producer tests](../../../internal/framework/pipeline/producer_test.go), [cache tests](../../../internal/framework/pipeline/producer_cache_test.go), [native capture tests](../../../internal/framework/pipeline/native_capture_test.go), and runner operation tests. Existing public behavior should survive internal decomposition without tests of new private call sequences. ### CPLX-002 — Pipeline Resolution Mixes Too Many Responsibilities In One File **Evidence:** [profile.go](../../../internal/framework/pipeline/profile.go) combines public value types and wire handling with resolution, reference precedence, generated dependency validation, validator selection, profile application, cloning, capabilities, and digesting. In [validateGeneratedBindings](../../../internal/framework/pipeline/profile.go#L703), five nested loops mix collection traversal with individual producer/slot/kind/media checks. `resolveReferenceTargetBindings` contains a sizable captured `addBinding` function as well as source normalization, overlay precedence, unbind handling, and required-slot checks. **Maintenance cost:** Editing one concern requires navigating unrelated policy and representation code. Deeply nested checks repeat scope formatting and hide which facts have already been resolved. The delimiter-based producer-key defect below is one concrete example of a local representation decision being easy to miss. **Potential refactoring:** Split cohesive types/copying, composition resolution, reference resolution, and generated-binding validation into focused files in the same package. Then extract per-binding validation from the traversal, passing a small scope and already-indexed producers/slots. Separate pure reference-source normalization from merging selected bindings. Keep the top-level resolver readable as input/chunk selection, ordered lane resolution, dependency validation, effective controls, and final digest construction. File splitting alone does not resolve the nested logic. Conversely, there is no demonstrated need to split the package, add a generic stage interpreter, or replace typed lookups with `any`. Preserve capability flow, exact Go-type compatibility, configured validator order, generated-reference restrictions, required bindings, and useful error context. Coordinate this work with CPLX-003 so it does not merely create cleaner copies of duplicated structural logic. **Behavioral protection to inspect:** [profile tests](../../../internal/framework/pipeline/profile_test.go), [typed resolution tests](../../../internal/framework/pipeline/typed_resolution_test.go), reference materialization and generated-handoff tests. ### CPLX-003 — Three Packages Independently Interpret Pipeline Structure **Evidence:** [config.validatePipelineProfiles](../../../internal/core/config/validation.go#L30), [pipeline.ResolvePipeline](../../../internal/framework/pipeline/profile.go#L337), and [cli.selectedReferenceTargets](../../../internal/cli/reference_selectors.go#L288) each interpret flat artifacts versus explicit steps, trim/check identifiers, walk lanes, and check selection constraints. The CLI additionally selects default chunk/merge/normalize modules and performs kind-specific spec lookup independently of framework resolution. Its scope matcher then repeats filtering for pipeline, chunk, lane, and stage-qualified selectors. **Maintenance cost:** A change to pipeline structure, module defaults, or target eligibility needs coordinated edits in loading validation, framework resolution, and CLI reference expansion. These are legitimate callers with different jobs, but maintaining separate interpretations makes drift more likely and explains several of the highest complexity scores. **Potential refactoring:** Let the pipeline package own a small structural-layout operation and a selected-target inventory built from that layout and the supplied catalog. Reuse common identifier/step/lane rules in runtime-config validation and resolution; let CLI selectors operate on the inventory rather than reconstructing module selection. Keep CLI grammar, specificity/conflict presentation, and exact override/unbind conversion in `cli`. The inventory must be usable before references are bound: CLI overrides can supply otherwise-required slots. Calling full resolution first, or adding an `allow_invalid_configuration` mode to bypass it, would recreate the dependency problem. Keep separate source-aware ConfigKit presence/provenance validation and catalog-dependent compatibility checks where they belong; do not force all validation into one pass. ConfigKit still owns configuration mechanics. **Behavioral protection to inspect:** Runtime config validation/effective-config tests, profile/typed-resolution tests, and CLI reference/override tests. Preserve unselected-lane behavior, ordered-step restrictions, generated-binding protection, pipeline-to-local precedence, and validation before reference-file reads. ### CPLX-004 — Semantic Registry Normalizers Repeat A Stateful Lifecycle **Evidence:** The `Normalize` methods for [NPCs](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go#L57), [items](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go#L58), and [locations](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go#L58) repeat roughly 127–133 lines of similar control flow. Each retains merged input, prepares fixed originals, records preparation/proposals, selects no-model or bounded-model handling, runs the shared producer, replaces per-proposal findings, constructs supported fallback, and attaches final diagnostics. Each also captures mutable findings, omission details, and discarded-group state in nested callbacks. **Maintenance cost:** Fixes to final-candidate/fallback bookkeeping or evidence recording need to be replicated in three packages. Domain differences are small within this lifecycle but significant elsewhere: items guard currency and produce advisories, while location identity includes evidence. A copy-and-edit pattern makes it harder to see those actual differences. **Potential refactoring:** Add a small typed lifecycle helper in the D&D shared layer, reusing `semanticreconcile` preparation/application and `pipeline.RunProducer`. Pass domain-owned preparation/application/result functions and return explicit per-proposal value, findings, guidance, and omission information instead of updating unrelated captured variables. Centralize only the demonstrated common execution/fallback/evidence bookkeeping. Keep domain preprocessing, identities, compatibility guards, warning reason codes, and postconditions with the families. Do not build another reconciliation service, add another model loop, merge the artifact types, or expose a universal JSON normalizer. If a proposed helper needs many optional hooks for individual lines, extract smaller common phases instead. Retain application of each proposal afresh to fixed originals and the separation between a final safe proposal and the incoming merged-artifact fallback. **Behavioral protection to inspect:** The three normalizer packages' native execution/fallback tests, typed reconciliation application tests, currency compatibility cases, and final-proposal-only behavior. This complements CPLX-001; it should call the producer helper rather than duplicate its state machine. ### CPLX-005 — Runner Stages Are Obscured By Debug And Output Assembly **Evidence:** [Runner.Run](../../../internal/framework/pipeline/runner.go#L90) spans 252 lines. It validates input, wraps capture, parses and validates source, records source and chunk envelopes, executes chunk production, builds the accepted chunk-map artifact, runs steps, aggregates diagnostics, builds evidence context, invokes output, and validates returned files. Stage operations alternate with large envelope literals, cancellation checks, and failure wrapping. **Maintenance cost:** Readers must inspect the entire function to establish stage ordering and what state can reach output. A change to capture representation or auxiliary assembly takes place alongside core run-control decisions. **Potential refactoring:** Extract cohesive private parse-source, chunk/accepted-map, and encode-output phases, with small typed phase results where helpful. Keep `Run` as the ordered coordinator around those operations and the existing `runPreparedSteps`. Let each helper own its applicable evidence envelopes and error context. Avoid a generic string-named stage dispatcher or moving physical file publication into the runner. Preserve cancellation boundaries, accepted/fallback eligibility, diagnostic aggregation, no output after terminal stage failure, input/output ownership, and requested-capture failure semantics. This is a local readability refactor, not a change to the fixed pipeline or the ready-job algorithm. **Behavioral protection to inspect:** Runner operation, handoff, cache, concurrency, metadata-isolation, evidence-output, and capture-failure tests. ### CPLX-006 — The Run Command Owns Declaration And The Whole Invocation Lifecycle **Evidence:** [pipelineRunCommand](../../../internal/cli/pipeline_run.go#L20) embeds a 156-line native command construction/execution flow. It loads configuration, reports load diagnostics, selects overrides, allocates identity/capture, constructs registries and engine, preflights/materializes/prepares, reads input, selects session/cache, runs the pipeline, publishes files, finalizes capture, and reports results. Its `finish` closure reads and updates surrounding capture/publication/output state. **Maintenance cost:** Command wiring and lifecycle policy are difficult to review independently. Every early return must use the right terminal path; understanding that path requires inspecting several mutable variables captured from the handler. **Potential refactoring:** Keep the CommandKit declaration small and delegate to an application-specific invocation function. Use a small private run-session value for the actual shared terminal state—capture, optional observation group, useful locations, publication state, and result summary—and an explicit finish operation. Separate selection/preparation from execution/publication when it improves clarity. Existing native loaders and upstream suites remain the configuration/CLI owners. Do not build a new command framework or universal result envelope. Preserve supplied-value semantics, one selected configuration/engine, capture allocation before native preparation, finalization before success reporting, retained causes, and distinct execution/publication/report-delivery outcomes. This complements CPLX-005 but remains a different owner: CLI placement/reporting is not runner work. **Behavioral protection to inspect:** [native process tests](../../../internal/cli/native_process_test.go), run-command, debug-capture, provider-accounting, and maintained-example tests. Keep assertions about observable outcomes rather than private session helper calls. ### CPLX-007 — Copying Pipeline Values Has Multiple Owners And Mixed Semantics **Evidence:** [core/config/config.go](../../../internal/core/config/config.go#L44) independently copies pipeline profiles, steps, lanes, module bindings, reference sources, validator overrides, and options. The pipeline package owns those types but has its own [binding/reference/override copies](../../../internal/framework/pipeline/validator_chain_registry.go#L84) and [option copying](../../../internal/framework/pipeline/profile.go#L1445). The pipeline helper called `cloneModuleBinding` also trims module/profile strings; the configuration copy does not. Option-copy switches already differ: only the pipeline version explicitly copies `[]string`, `[]byte`, and `json.RawMessage`. **Maintenance cost:** Adding a mutable field or supported option container requires auditing multiple copying trees. Similar names conceal different copy-versus- normalization behavior. This makes ownership reasoning harder even where current loaded configurations behave correctly; the option differences alone are not claimed here as a demonstrated production regression. **Potential refactoring:** Give pipeline-owned value types one pure copying implementation usable by configuration conversion and framework callers, through small clone functions or methods as appropriate. Keep trimming/default resolution explicit and separate. Reuse only the copying operation across that boundary; calling the current normalizing helper from configuration would change semantics. Preserve absence versus explicit empty controls/chains, independent mutable containers, original configuration inspection, and supported option types. Do not replace these copies with JSON round trips or merge them with source-metadata validation, native evidence copying, or arbitrary deep reflection merely because all of those operations copy data. They serve different contracts. **Behavioral protection to inspect:** [effective-config ownership tests](../../../internal/core/config/effective_config_contract_test.go), inheritance/inspection tests, validator-chain registry tests, and prepared-request isolation tests. Verify the established option-container contract before unifying the two switches rather than inventing a broader one. ### CPLX-008 — Maintained-Example Testing Combines Several Independent Concerns **Evidence:** [TestMaintainedExamplesLoadResolveAndList](../../../internal/cli/example_contract_test.go#L29) has 117 lines and a graph cognitive estimate of 110. Nested example/pipeline loops combine transcript parsing, configuration loading/materialization, complete lane composition, generated references, development inheritance, and native list output. A mutable `completePipelines` map makes the development comparison depend on the parent having been processed earlier. **Maintenance cost:** Updating one example contract requires navigating checks for several others. The fixture-processing order is mixed into assertion flow, which adds context needed to understand failures. A high test score is not itself a problem; this finding concerns these mixed responsibilities and shared setup state. **Potential refactoring:** Build clearly named resolved-example fixtures, then separate loading/materialization, complete composition, development-vs-parent, and listing checks into focused tests/subtests or short `t.Helper` assertions. Obtain the explicit parent fixture for inheritance checks rather than depending on a previous assertion loop iteration. Keep the example-specific expectations local. Retain the useful maintained-example integration coverage. Do not introduce a general assertion DSL, duplicate every module's unit tests, or add snapshots and new exact-default requirements to make this reorganization possible. ## Additional Correctness Findings ### BUG-001 — Generated-Producer Keys Can Collide **Priority:** P3 — unusual identifiers can select the wrong validation record. [validateGeneratedBindings](../../../internal/framework/pipeline/profile.go#L703) indexes producer lanes by `step.ID + "\x00" + lane.ID`, then constructs the same string for reference lookup. The mapping is not injective: ```text (step="a\x00b", lane="c") -> "a\x00b\x00c" (step="a", lane="b\x00c") -> "a\x00b\x00c" ``` The step and lane identifiers remain individually distinct. Current structural checks trim whitespace and enforce nonblank/unique identities; they do not reject this embedded separator. Programmatic pipeline profiles can therefore reach this case. JSON can represent the character as `\u0000` as well. The later producer overwrites the earlier one in the index. A reference to the earlier producer then checks kind/media compatibility against the later producer. For example, distinct artifact kinds can cause a valid earlier binding to be rejected. This is a static counterexample derived from the actual key construction; no runtime reproduction was performed. It is not a claim that runtime handoff delivers the wrong artifact: that boundary already uses a struct key. **Potential correction:** Use the existing [generatedOutputKey](../../../internal/framework/pipeline/handoff.go#L16) and `generatedOutputKeyFor` for this resolver index too. Add a focused binding-validation case with the two distinct pairs above and different producer kinds. No new identifier-character prohibition is needed. This small correction can precede CPLX-002/003. ### BUG-002 — Cycle Detection Confuses A Slice View With A Cycle **Priority:** P3 — valid programmatically supplied metadata can be rejected. [CloneMetadata](../../../internal/core/source/metadata.go#L13) promises an owned copy of JSON-shaped metadata while preserving concrete containers. Its recursion tracker identifies maps/slices using only type and backing pointer in [enterMetadataValue](../../../internal/core/source/metadata.go#L112). For slices, the pointer is the first element's address, not the identity of the visible slice view. Consider: ```go values := []any{"one", nil} values[1] = values[:1] metadata := map[string]any{"values": values} ``` The finite JSON value is `{"values":["one",["one"]]}`. During cloning, the two-element outer slice is active when the one-element inner view is reached. They have the same type and first-element pointer, so the tracker reports a cycle even though the inner view cannot reach the outer slice's second element. This follows directly from the recursion/key construction and the local standard library documentation for `reflect.Value.Pointer`; it was not empirically tested. **Potential correction:** Make slice tracking distinguish the traversed view, including its visible length, and handle empty views without treating backing storage sharing as a cycle. Retain real cycle rejection, concrete types, detached output, and path-specific errors. Add narrow source-package coverage for this acyclic shared-prefix view, ordinary shared values, and actual map/slice cycles. No ban on shared backing arrays or JSON round-trip replacement is needed. The ordinary JSON transcript decoder does not itself construct this aliased view; the affected boundary is programmatic metadata supplied by callers/extensions. ## Areas Where A Rewrite Is Not Recommended - **Typed stage/validator registries:** Exact-type checks and stage-specific variants serve real boundaries. Similar adapter signatures are not sufficient reason to replace them with an untyped registry or reflection-driven dispatch. - **Shape validators versus durable codecs:** Candidate diagnostics/correction and intrinsic durable validity have different jobs. Share truly identical predicates where helpful; do not merge the boundaries or make optional validation mandatory. - **Metadata reflection:** Apart from BUG-002, the type switch has a cohesive purpose and preserves representations that JSON round trips would lose. Small comments explaining active-recursion tracking and slice-view identity after the fix are more valuable than a generic visitor framework. - **Default-chain/registration declarations:** Long declarative lists often have little control flow. Splitting or generating them solely to reduce line counts would add machinery without a demonstrated maintenance benefit. - **Ready-job coordination, proposal safety, and catalog composition:** These own genuine ordering, identity, and compatibility rules. Existing small state/helper boundaries are useful; the audit found no basis for a wholesale replacement. ## Suggested Order And Verification The two correctness corrections are small independent starting points. For a refactoring work set, prioritize CPLX-001, CPLX-003, and CPLX-004: they reduce shared state reasoning and cross-package drift. Coordinate CPLX-002/007 with structural consolidation. Runner/CLI phase cleanup and example-test organization can follow as separate focused work rather than one repository-wide rewrite. Each future change should preserve the existing observable contracts and use the focused behavioral suites named above. Those are recommendations for implementation, not tests run during this audit. There is no proposed complexity threshold, benchmark gate, new interface requirement, or obligation to refactor every measured hotspot. The findings do not retire or resolve issues in the earlier audit reports. Only report formatting, local link targets, and the final diff are checked for this documentation-only deliverable. No code or policy changes are included.