diff --git a/docs/roadmap/audit/11-boundaries.md b/docs/roadmap/audit/11-boundaries.md new file mode 100644 index 00000000..d101a639 --- /dev/null +++ b/docs/roadmap/audit/11-boundaries.md @@ -0,0 +1,357 @@ +# Package Cohesion And Architectural Boundaries Audit + +## Baseline And Method + +Reviewed revision `7a14a43677626e7faa7bc60f5d8d4cfbdd835d45` on 2026-11-24. +Production code and tests are unchanged from the preceding audits. This pass adds +only this report, without changing production code or tests. + +The review followed the [architecture](../../policy/architecture.md), +[agent](../../policy/agents.md), and [testing](../../policy/testing.md) policies +and compared actual responsibilities with the +[implemented component map](../../internal/overview.md). Code-graph searches and +caller tracing located likely ownership seams; Go's package/import inventory and +source inspection established the actual dependency directions. Name-based call +graph associations were not treated as proof of Go imports. + +The default-build inventory contains 125 repository packages, including 123 under +`internal/` and packages containing only tests. Review scope was repository-owned +packages only. Third-party implementations were not audited; their imported types +were considered only to distinguish intentional native integration from local +ownership decisions. The import inventory reflects the current Linux build; +the existing import-boundary test additionally scans repository Go files rather +than only the files selected for that build. + +The review covered composition/configuration, framework contracts and execution, +preflight, source and auxiliary artifacts, cache/debug/file placement, domain +models, registries, codecs, stage implementations, validators, shared helpers, +and registrars. It is a responsibility-directed review, not a proof of every +supported configuration or hypothetical extension. + +## Architecture Assessment + +The central architecture remains coherent: + +```text +input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output +``` + +- The CLI composes native kits and family registrars, selects run inputs/state, + publishes logical output, and submits reports. +- Configuration owns application fields and runtime conversion; the pipeline + framework owns typed resolution/preparation, assessment, producer coordination, + ready-job execution, generated handoffs, and reuse eligibility. +- Artifact families own domain identity, interpretation, transformations, codecs, + contextual projections, validator policy, and prompts. Registrars compose their + implementations without owning process execution. +- Source, filesystem helpers, accepted-result storage, and debug recording have + focused responsibilities. Embedded assets remain a content-only leaf. + +The actual production imports show no core/framework dependency on concrete +module implementations, no production extension dependency on the CLI, and no +CLI dependency on concrete stage implementations instead of family registrars. +Generic production modules do not import D&D or Seriatim implementations. +`core/source` remains independent of the framework, and `assets` imports no +internal package. The existing production import-boundary tests pass. + +The `core/config -> framework/pipeline` dependency is intentional: configuration +uses pipeline-owned values and domain resolution. It is not a cycle or a policy +violation merely because the broad directory names suggest layers. Likewise, +native PromptKit types at the execution boundary are an accepted architectural +choice, not leakage that needs another adapter. + +The findings concern more local ownership overlap and cohesion. None establishes +a new runtime correctness defect or a breach of the checked import-direction +rules. Package size and fan-in alone were not used to justify package splitting. + +## Findings Summary + +Priority is relative refactoring value, not a runtime severity classification. + +| ID | Priority | Category | Responsibility needing a clearer owner | +| --- | --- | --- | --- | +| BND-001 | High | Overlapping/fragmented | Pipeline layout and selected-module/reference inventory across configuration, CLI, and resolver. | +| BND-002 | Medium | Overlapping | Pure copying of pipeline-owned values across configuration and framework code. | +| BND-003 | Medium | Misplaced/mixed | Reusable scene shape rules housed in a selectable validator adapter. | +| BND-004 | Low | Mixed cohesion | Native request capture housed with pipeline-specific operation scoping. | +| BND-005 | Medium | Overlapping | Reconciliation operation lifecycle repeated by three registry normalizers. | + +BND-001, BND-002, and BND-005 reinforce EQ-004, EQ-003, and EQ-001 in the +[equivalence audit](10-equivalence.md), respectively, and their related complexity +findings. They are not additional independent remediation projects. BND-003 and +BND-004 identify narrower package-placement concerns. + +## BND-001 — Pipeline Composition Meaning Has Three Partial Owners + +**Relevant implementation:** +[`config.validatePipelineProfiles`](../../../internal/core/config/validation.go#L30), +[`pipeline.ResolvePipeline`](../../../internal/framework/pipeline/profile.go#L337), +[`selectedArtifactLanes`](../../../internal/framework/pipeline/profile.go#L1478), +and [`cli.selectedReferenceTargets`](../../../internal/cli/reference_selectors.go#L288). + +**Basis:** Configuration independently interprets flat artifacts versus ordered +steps, constructs implicit steps, and checks normalized step/lane identities. +The runtime resolver repeats that structural interpretation, then selects +modules/defaults and artifact-kind-specific variants. CLI reference expansion +again flattens/selects lanes and resolves the same module/default/variant choices +to discover reference slots. + +Loading, CLI mapping, and runtime resolution are valid separate boundaries. +However, application composition choices shared by those boundaries lack one +reusable representation/owner. A module default or layout change needs coordinated +edits to three traversals. The existing +[CLI reference tests](../../../internal/cli/reference_contract_test.go#L321), +[typed resolution tests](../../../internal/framework/pipeline/typed_resolution_test.go#L143), +and [configuration structural tests](../../../internal/core/config/validation_contract_test.go#L40) +substantiate the overlapping responsibility. + +**Potential remediation:** Let `pipeline`, which already owns the profile and +resolved types, own two small operations: catalog-independent runtime-value +layout interpretation, and catalog-aware selected-target inventory. Reuse their +results in configuration validation, reference expansion, and full resolution. +Keep configuration source/presence diagnostics and CLI selector grammar, +specificity, bind/unbind conversion, and invocation-path handling with their +current owners. Keep capabilities, complete type compatibility, required +reference satisfaction, validator selection, and generated dependencies in full +resolution/preparation. + +The CLI needs selected targets before its overrides satisfy required references; +calling the full resolver there is not a substitute for the smaller inventory. +Configuration-only structural checks also need not construct a production +catalog. Raw-document presence cannot always be reconstructed from decoded Go +values, so its existing ConfigKit-backed checks remain separate. This is a +consolidation of application meaning, not an application replacement for ConfigKit +loading/composition. Preserve phase-specific error context and existing accepted +identifiers rather than introducing stricter validation to simplify the sharing. + +## BND-002 — Pipeline Value Ownership Is Implemented Outside Its Type Owner + +**Relevant implementation:** +[configuration clone tree](../../../internal/core/config/config.go#L44), +[framework binding/reference copies](../../../internal/framework/pipeline/validator_chain_registry.go#L84), +and [framework option copies](../../../internal/framework/pipeline/profile.go#L1445). + +**Basis:** `core/config` maintains its own pipeline/step/lane/binding/reference/ +validator copying functions even though the copied types belong to `pipeline`. +Framework construction, registry, and prepared-value paths maintain another +copying subtree for bindings, controls, references, overrides, and options. The +ownership requirement is shared, as demonstrated by +[effective-config mutation tests](../../../internal/core/config/effective_config_contract_test.go#L268) +and [framework defensive-copy tests](../../../internal/framework/pipeline/validator_chain_registry_test.go#L55). +Adding a mutable field requires auditing several traversals instead of its type +owner providing the copying operation. + +The helpers also mix responsibilities inconsistently: framework +`cloneModuleBinding` trims module/profile identifiers, while the configuration +copy preserves them. The option switches support different concrete containers. +Those differences mean the functions should not simply be substituted for one +another under their current names. + +**Potential remediation:** Provide small pure clone functions/methods for +pipeline-owned values in `pipeline`; keep root configuration copying in `config`. +Make trimming/defaulting explicit at resolution sites rather than a side effect +of copying. Share common binding/reference/options subtrees; source profiles and +resolved pipelines remain different types. + +Inventory supported option representations before unifying the switches. The +existing nested-map ownership tests do not by themselves establish a universal +contract for every mutable Go value. Preserve omission versus explicit controls +and source/frozen inspection. Avoid a generic reflection copier, JSON round trips, +or combining this with source-metadata validation, which has different accepted +representations and error behavior. Existing mutation-based tests should continue +to cover both conversion and framework boundaries independently. + +## BND-003 — Scene Domain Rules Live Inside A Selectable Validator Package + +**Relevant implementation:** +[`validate/scenedescriptions/shape`](../../../internal/modules/dnd/validate/scenedescriptions/shape/validator.go#L45), +[`normalize/scenedescriptions.normalizeList`](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer.go#L66), +other scene validator packages, and +[the scene codec](../../../internal/modules/dnd/codec/scenedescriptions/codec.go#L82). + +**Basis:** The shape package combines three responsibilities: reusable field/kind +checks (`Validate`, `ValidateForStage`, `ValidKind`), extraction cardinality and +validator adaptation, and model-facing corrective prose. The normalizer imports +this selectable validator package to call `shape.Validate` after trimming prose. +Sibling validators import it for shape preconditions. This works and is permitted +by the current same-family import rules, but a reusable family-domain rule is +owned by one stage-adapter implementation. + +The coupling is more than naming: `Validate` invokes `assess`, which constructs +correction guidance that non-validator callers discard. Changing the adapter's +assessment/guidance implementation therefore also affects an ordinary domain +validity call. The codec separately owns its intrinsic checks, including another +supported-kind predicate. + +The [normalizer's invalid/conflict tests](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer_test.go#L77) +and [shape validator tests](../../../internal/modules/dnd/validate/scenedescriptions/shape/validator_test.go#L13) +show the distinct consumers. The latter deliberately requires exactly one record +only for extraction; the [normalizer tests](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer_test.go#L16) +accept, trim, order, and combine a multi-scene list. + +**Potential remediation:** Move the genuinely reusable scene predicates/checks +into a small family-domain owner, following the existing pure `itemoccurrences`, +`npcoccurrences`, and `enemyevents` pattern. A scene-family helper package is a +reasonable home; tiny predicates can remain with the domain model if that is +clearer. Have the normalizer and validators depend on that owner. Keep native +registration, extraction-only cardinality, assessment classification, and +model-guidance rendering in the validator adapter. + +Start with scenes, where there is an actual cross-stage consumer. Other shape +packages expose similar helpers to sibling validators, but that alone does not +justify moving every check or generating a universal validation package. Extract +additional rules only where they have the same concrete ownership problem. + +Keep intrinsic codec acceptance separate from selectable validation. The codec +and shape validator currently differ, including trimmedness requirements; reusing +the entire strict checklist in the codec would strengthen its contract. Share +identical primitives, such as supported scene kinds, while retaining those +intentional boundary differences. Preserve early shape preconditions used by +other validators and all current validator-override behavior. This is a placement +and cohesion improvement, not a proposal to make optional validators mandatory. + +## BND-004 — Native Capture And Pipeline Scoping Share One Implementation Home + +**Relevant implementation:** +[`pipeline.NativeCapture` and `CaptureNativeRequest`](../../../internal/framework/pipeline/native_capture.go#L19), +[`operationExecution`](../../../internal/framework/pipeline/native_capture.go#L180), +[the producer](../../../internal/framework/pipeline/producer.go), +[the combat semantic validator](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go), +and [the debug recorder](../../../internal/framework/debug/recorder.go#L17). + +**Basis:** Most of `native_capture.go` implements one request's native evidence +lifecycle: hook composition, prepared snapshot ownership, event writes, +result/exchange rendering, and retained capture errors. It requires a native +request and an `EvidenceWriter`, not a runner, lane, or artifact type. Both the +shared producer and an independently executed LLM validator use that API. + +The same file also implements `operationExecution`, which does know `RunInput`, +diagnostic origins, step/lane/chunk identifiers, and the pipeline's evidence path +layout. Request-level capture and pipeline-level operation placement are therefore +mixed inside the orchestration package. The separate `framework/debug` package +owns recording/storage lifecycle, so contributors must find model evidence +behavior under `pipeline` rather than beside its recording concerns. + +**Potential remediation:** Consider extracting the sink-neutral native-capture +component into a focused framework package, retaining pipeline-specific scope +construction in `pipeline`. Alternatively, extend the existing debug package if +native capture can remain cleanly separated from its filesystem recorder and +bundle allocator. Prefer one coherent owner over creating parallel capture APIs. + +This is a low-priority package-cohesion opportunity, not a forbidden import or a +demonstrated runtime failure. Merely moving code into another file in `pipeline` +would clarify the internal seam but not its reusable package ownership. The +extraction is worthwhile only if the resulting API is small and direct; do not +introduce a replacement execution interface or generic telemetry service. + +Keep `contracts.EvidenceWriter` as the supplied sink, physical allocation and run +finalization with the CLI/recorder, and step/lane paths with the pipeline. Preserve +no-I/O-under-admission handling, prepared-value ownership, cause retention, +cancellation, cache-hit evidence, and no duplicate preparation/model calls. Existing +[capture tests](../../../internal/framework/pipeline/native_capture_test.go) and +[validator execution tests](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go) +protect these behaviors. Do not merge capture with invocation accounting or turn +private evidence layout into a durable consumer contract during the move. + +## BND-005 — Registry Reconciliation Lifecycle Ownership Is Repeated By Family Adapters + +**Relevant implementation:** The `Normalize` methods for +[NPC registries](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go#L57), +[item registries](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go#L58), +and [location registries](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go#L58), +together with `framework/semanticreconcile` and `pipeline.RunProducer`. + +**Basis:** The domain-neutral core owns candidate preparation, request-local +mapping, proposal safety, and typed application. The producer owns native +execution and acceptance. Each family normalizer nevertheless independently +implements the same intermediate lifecycle: fixed originals, preparation +dispositions, evidence envelopes, proposal decoding/assessment, current-proposal +bookkeeping, correction construction, and terminal fallback plumbing. + +Domain-specific adapters are appropriate, but this repeated lifecycle has no +single implementation owner. Its genuinely shared responsibilities are mixed +with each family's preprocessing, identity rules, typed consolidation, and +diagnostics. The [equivalence audit's EQ-001](10-equivalence.md#eq-001--registry-normalizers-repeat-one-reconciliation-lifecycle) +provides the supporting family tests and detailed implementation comparison. + +**Potential remediation:** Assign the shared reconciliation lifecycle to a small +typed helper at the existing reconciliation/producer boundary. Continue delegating +native execution and terminal mode handling to the existing producer helpers. +Keep family preprocessing/application/cloning, fallback validity, prompt selection, +and diagnostic policy in the adapters. A neutral result can carry proposal issue +and omission information for family-owned presentation. + +Avoid transferring currency compatibility, NPC canonical-name decisions, +same-name location distinctions, or D&D diagnostic types into the generic core. +Keep every response applied afresh to fixed originals, not accumulated plans. +Choose a dependency direction that keeps the core free of concrete family +imports; a new orchestration framework or record reflection layer is unnecessary. +Retain independent family output tests rather than treating shared lifecycle +coverage as proof that all typed adapters are correct. + +## Boundaries Worth Retaining + +- **Typed contracts versus orchestration:** The contracts package is a useful + shared vocabulary. Framework erasure and registries belong with execution/ + construction, while pure source types remain independent. Do not move all + behavior into `contracts` simply because many packages import it. +- **ConfigKit result versus application semantics:** Native loading, presence, + composition, provenance, and inspection retain their selected owner. Application + normalization and pipeline compatibility are legitimate local responsibilities. +- **Domain family versus stage adapters:** Family-specific packages already share + identities, immutable registry resolution, and occurrence/event helpers across + stages. The stage-oriented directory layout does not itself violate family + ownership or justify wholesale moves to another tree. +- **Shared D&D versus generic framework:** Family-only support may remain under + D&D even if a function looks mechanically generic. Its current consumers and + policy determine a useful boundary, not hypothetical reuse by another domain. +- **Source auxiliaries versus output publication:** `chunkmap` and + `evidencecontext` own logical domain-neutral artifacts; the runner assembles + values, output encoders return logical files, and the CLI publishes them. +- **Storage versus lifetime policy:** `fileio`, `debugbundle`, the debug recorder, + and `artifactcache` have different cohesive roles. Shared atomic writes do not + justify merging cache, output, and requested debug lifecycles or permissions. +- **Native integration versus pure domain logic:** The selected execution APIs + remain native. No private transport, scheduler, configuration parser, or kit + compatibility layer is indicated by these findings. + +The existing `shared` and registrar packages have demonstrated consumers and +bounded roles. This review does not recommend flattening all small packages, +splitting `pipeline` by file count, or reorganizing the entire repository. The +highest-value work is clearer ownership of composition meaning and reusable +family rules, coordinated with the earlier consolidation findings. + +## Validation And Limits + +The production package inventory was obtained offline with: + +```sh +GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go list -mod=readonly -json ./... +``` + +Repository-owned import edges were selected from `Imports`, separately from +`TestImports`/`XTestImports`, and checked against the boundaries summarized above. +Generated inventory data remained outside the repository. The inventory and +successful compilation do not by themselves establish conceptual cohesion. + +The following fresh offline tests passed: + +```sh +GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ + ./internal/modules ./internal/core/config ./internal/framework/pipeline \ + ./internal/framework/debug ./internal/core/debugbundle ./internal/preflight \ + ./internal/modules/dnd/normalize/scenedescriptions \ + ./internal/modules/dnd/validate/... ./internal/modules/integration +``` + +These include the production AST import guard and its rule fixtures, typed +resolution/preparation, scene shape/normalization, native capture, configurable +validators, debug lifetime, preflight, and assembled handoffs. Successful tests +show that the inspected baseline respects its checked contracts; the ownership +findings do not depend on inventing a test failure. The preceding equivalence +audit also records registry-normalizer tests at unchanged code. + +No third-party source audit, live provider calls, credentials, new tests, production +changes, or architecture-policy changes were required. Broader build-tag/platform +matrices and every possible extension remain outside the claim. Local report links +and the final documentation diff are checked before committing.