From bd8e8a0627e7dfe0425e380212e82f00c79aa1d2 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 22:47:58 +0000 Subject: [PATCH] Record package boundary audit findings --- docs/roadmap/audit/11-boundaries.md | 327 ++++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) create mode 100644 docs/roadmap/audit/11-boundaries.md diff --git a/docs/roadmap/audit/11-boundaries.md b/docs/roadmap/audit/11-boundaries.md new file mode 100644 index 0000000..8f20af4 --- /dev/null +++ b/docs/roadmap/audit/11-boundaries.md @@ -0,0 +1,327 @@ +# Package Cohesion And Architectural Boundaries Audit + +Reviewed: 2026-11-30 + +Baseline: `28e54fb657e7915dd79f8b09bfde0636847ede1a` + +## Scope And Method + +The review covered the repository's 26 internal Go packages and the executable +entry point. It examined declared responsibilities, actual imports, public +contracts, and representative implementations and callers across configuration, +orchestration, stages, adapters, manifests, artifacts, workspace operations, +input preparation, readiness, publication, and restore. Third-party package +implementations and vendor code were outside scope. + +Codebase-memory-mcp supplied package exploration, symbol discovery, source +snippets, and call tracing. Its coarse package grouping and same-named receiver +method resolution were supplemented with source inspection and `go list`'s +actual production imports. Package size or a graph metric alone was not treated +as evidence of poor cohesion. + +The [architecture policy](../../policy/architecture.md) supplied the intended +ownership boundaries. Focused internal documents and existing tests supplied +additional implementation evidence. These checks passed on Linux with Go 1.27.4: + +- `go list -f '{{.ImportPath}}|{{join .Imports ","}}' ./...` +- `go test -count=1 ./...` +- `go vet ./...` +- `go test -count=1 ./internal/doccheck` after writing this report. + +No production code or tests were changed. No new tests, live provider calls, +external subprocess applications, or remote-storage experiments were needed. +This is an ownership audit, not proof that every runtime path is correct. + +## Current Architecture + +Narratio is a fixed-stage orchestrator: +`prepare → transcribe → merge → polish → normalize → trim → render → extract → analyze → publish → notify → cleanup`. +Notification currently uses the no-op mode. + +| Package area | Implemented responsibility | +| --- | --- | +| `cmd/narratio`, `internal/app` | Entry, native CommandKit composition, configuration acquisition, invocation/session lifecycle, planning, execution, operator commands, and restore. | +| `internal/config` | Typed ConfigKit handoff, Narratio validation, party/family/catalog derivation, and safe configuration materialization. | +| `internal/domaininput`, `internal/glossary` | Shared input-schema validation and Narratio's selected vocabulary projections/composition. | +| `internal/stage` | Fixed stage contracts, stage execution and resume semantics, sub-stage reconciliation, and stage-owned semantic fingerprints. | +| `internal/adapters/*` | Narratio-owned external contracts and HTTP, subprocess, notification, or object-store implementations. Shared subprocess supervision and credential handling have a dedicated owner. | +| `internal/manifest`, `internal/artifactmodel`, `internal/artifactpolicy` | Durable progress records/persistence, shared product models, and source/destination vocabulary and validation. | +| `internal/artifacts` | Canonical paths and local store/locking, runtime availability and evidence, artifact resolution, remote commit/current-state models, and remote locks. | +| `internal/audio`, `internal/previouscache` | Verified S3 audio materialization and selection of committed previous-session inputs. | +| `internal/preflight` | Downstream readiness assessment over supplied targets and adapter reports. Application code selects targets and coordinates probes. | +| `internal/pathsafe`, `internal/fileops` | Path confinement, ordinary workspace modes, bounded reads, replacement/deletion mechanics, and the diagnostic-view behavior discussed below. | +| `internal/contracts`, `internal/notariusref`, `internal/logging`, `internal/doccheck` | Focused bounds/selector contracts, reporting interfaces, and repository validation support. | + +The actual import graph respects the main direction: the executable imports +`app`; `app` composes stages and implementations; stages consume Narratio-owned +adapter contracts and support services. Stages do not import `app`. Locating +an interface in an adapter package does not itself leak an SDK or subprocess +protocol into its consumers. + +The five findings below concern responsibility allocation within that generally +sound structure. Several refine existing audit findings and should be addressed +as the same work rather than counted as additional runtime defects. + +## BN-01 — P3: Diagnostic-view layout policy is embedded in file-operation mechanics + +Status: Open + +**Relevant implementation.** +[fileops/attempt_views.go](../../../internal/fileops/attempt_views.go): +`BeginAttemptViews`, `attemptTarget`, `existingManagedView`, +`InspectManagedAttemptViews`, `RemoveManagedAttemptViews`, and `AttemptViews.Revert`. +[artifacts/paths.go](../../../internal/artifacts/paths.go): +`SessionInvocationProbeDir`, `SessionRunLogsDir`, `SessionRunDebugDir`, and the +latest-view path helpers. +[stage/run_local.go](../../../internal/stage/run_local.go): `resolveRunStageLayout`. + +**Basis.** Fileops knows Narratio's `runs///{logs,debug}` grammar, +the corresponding latest-attempt links, and reserved `.preflight`/`.validation` +identities. It constructs and recognizes those paths independently of the +canonical path owner. This is application workspace/navigation policy, beyond +writing, replacing, or removing a caller-selected file. Changing the attempt +layout or probe convention requires coordinated changes in fileops, artifacts, +and stage/application callers. + +The application correctly decides when to advance or revert a view in +`executeSelectedStage`; restore uses the same fileops operation, and cleanup +removes recognized views. The ownership issue is the location of the layout +grammar, not those callers' lifecycle decisions. + +**Remediation options.** Prefer moving the existing diagnostic-view operation +to the canonical layout owner, currently `internal/artifacts`, and making it +consume the same path model. Keep root-scoped directory creation, permissions, +and ordinary replacement/deletion mechanics in fileops. Move the operation +without introducing a generalized symlink-management framework. + +An alternative is a focused `internal/workspace` owner containing the canonical +local path model, session locking, and attempt views. That gives the broad +artifacts package a clearer boundary, but requires a larger interface/import +change. Establishing one owner for attempt layout is useful independently of +whether that broader extraction is worthwhile. + +**Supporting tests and tradeoffs.** +[Fileops view tests](../../../internal/fileops/attempt_views_test.go), including +`TestAttemptViewsAdvanceAndRestoreManagedTargets`, and +[application attempt tests](../../../internal/app/attempt_views_test.go), +`TestAttemptViewsTrackAttemptsFailureSkipAndReuse`, protect advancement, +failed-attempt visibility, self-skip reversion, and reuse without an empty run. +Keep those behaviors and root-confinement rules. The runner still decides +whether an attempt exists; cleanup still chooses authorized targets. A package +move should not add retention, locking, or filesystem guarantees. + +## BN-02 — P3: Notarius output-protocol translation partly lives in stage orchestration + +Status: Open + +**Relevant implementation.** +[stage/notarius_lanes.go](../../../internal/stage/notarius_lanes.go): +`notariusLanePath` (line 23) and `stageRequiredNotariusLanes`. +[stage/extract.go](../../../internal/stage/extract.go): `resolveExecutable` +(line 317) and its extraction caller. +[stage/extract_preflight.go](../../../internal/stage/extract_preflight.go): +`BuildNotariusReadiness`. +[adapters/notarius/runner.go](../../../internal/adapters/notarius/runner.go): +`RunRequest` and `RunResult`; +[subprocess.go](../../../internal/adapters/notarius/subprocess.go): +completion decoding and bundle discovery. + +**Basis.** The adapter owns CLI arguments, completion decoding, and bundle-root +discovery, but returns only the bundle root rather than locations of requested +native outputs. The stage therefore implements Notarius's lane-ID sanitization +and `lanes/.json` mapping itself. This mapping changes with the external +output protocol, not Narratio's stage policy. Executable discovery through +`exec.LookPath` also lives in the stage and is used by execution and readiness, +although process launch belongs to the adapter/shared subprocess boundary. + +The source mapping is directly protected by +[TestNotariusLanePath](../../../internal/stage/notarius_lanes_test.go), with +native filename expectations in the stage package. +[TestNativeExtractionRejectsMappedLaneCollisions](../../../internal/stage/extract_native_test.go) +also exercises the external sanitization collision. These tests demonstrate +where the external contract currently resides. + +**Remediation options.** Prefer making the existing Notarius adapter own the +lane-to-native-path translation, through a narrow resolver or requested-lane +result contract. The stage supplies required lane IDs and receives their +locations, then applies Narratio's staging, checksum, canonical-name, and +promotion policy. Pass executable selection through the adapter/shared process +runner or production composition, retaining the same operator override semantics. + +A smaller alternative moves only lane-path resolution into an exported helper +in the existing Notarius adapter package. That fixes the clearest misplaced +responsibility without redesigning `Runner`. A separate shared contract package +is warranted only if another actual consumer needs the same protocol. + +**Tradeoffs.** Keep Narratio's canonical filename selection and collision rules +outside the downstream protocol resolver. Confined paths, bounded valid JSON, +verification before replacement, and manifest evidence remain Narratio +responsibilities. Typed adapter results do not eliminate those checks. Move +native naming fixtures with their owner while retaining stage tests that prove +the correct configured lanes are promoted. This is distinct from decomposing +the large extraction function in CX-03 of the +[complexity audit](03-complexity.md). + +## BN-03 — P3: Machine-consumed publication metadata lacks a shared contract owner + +Status: Open + +**Relevant implementation.** +[stage/publish.go](../../../internal/stage/publish.go): `publishMetadata`. +[stage/publish_output_plan.go](../../../internal/stage/publish_output_plan.go): +`publishOutputStatus` and `publishOutputOutcomeMetadata` (line 245). +[stage/cleanup_plan.go](../../../internal/stage/cleanup_plan.go): +`validateCleanupPublishEvidence` (line 84). +[app/artifact_inspection.go](../../../internal/app/artifact_inspection.go): +`committedPublishOutputOutcomes` (line 41) and `isPublishOutputOutcome`. + +**Basis.** Publish serializes completion identity and per-source outcomes into +`StageRecord.Metadata`. Cleanup independently reconstructs completion fields and +checks their meaning. App inspection independently knows the outcome keys and +repeats the producer's five status strings. Its parser handles both +`[]map[string]any` and JSON-decoded `[]any`. A producer change can compile while +silently changing cleanup eligibility or operator reporting. + +These values are shared control/reporting evidence, even though they currently +share a map with arbitrary diagnostics. Manifest persistence supplies a common +container, but does not own the meaning of publication fields. Stage-private +types also cannot be the sole contract for independent app consumers. + +**Remediation options.** Prefer small typed publication completion/outcome +values and map encoding/decoding helpers under an existing shared owner, such +as `internal/artifacts` alongside its remote publication identities. Have the +producer and consumers use that contract while preserving the existing JSON +shape. Keep cleanup eligibility in cleanup and presentation decisions in app. + +An alternative is a focused publication package if remote commit, lock, and +publication evidence responsibilities are extracted together. That creates a +stronger domain boundary at the cost of a larger change. A generic metadata +framework or new manifest schema is unnecessary for the immediate issue. + +**Supporting tests and tradeoffs.** +[TestCommittedPublishOutputOutcomesRecognizesAllStates](../../../internal/app/restore_commit_test.go) +checks the app-side vocabulary. +[Cleanup plan tests](../../../internal/stage/cleanup_plan_test.go), notably +`TestBuildCleanupPlanRejectsInvalidPublishEvidenceWithoutExecutablePlan`, +exercise the safety gate. Retain direct and persisted-round-trip coverage. +Tolerant display parsing and authoritative cleanup checks have different +failure policies; a shared decoder should not silently make them equally +strict. Arbitrary diagnostic metadata can remain flexible. + +This is the publication part of CX-06 in the +[complexity audit](03-complexity.md), with a concrete ownership recommendation. +Typed evidence does not resolve FC-02's carried-output/manifest coherence issue. + +## BN-04 — P3: Audio discovery is owned independently by preparation and inspection + +Status: Open + +**Relevant implementation.** +[stage/prepare.go](../../../internal/stage/prepare.go): +`resolveLocalAudioFiles` (line 311), `resolveAudioInputs`, and +`localAudioDestinations`. +[app/operator_inspection.go](../../../internal/app/operator_inspection.go): +`inspectLocalAudioPresence`, `resolveLocalInspectionAudioPaths` (line 207), +and remote-audio inspection. +[audio/s3_audio.go](../../../internal/audio/s3_audio.go): +`MaterializeS3Audio`, the existing audio-focused domain helper. + +**Basis.** Both app and stage own explicit-list/directory selection, relative +resolution, FLAC filtering, duplicate handling, and deterministic ordering. +There is no shared read-only source-selection owner. Their policies have already +diverged: preparation rejects duplicate resolved source paths and supports +distinct same-basename recordings; inspection accepts repeated identical paths +and rejects distinct paths with the same basename. File eligibility checks also +differ: preparation's `requireFile` rejects directories, while inspection +requires a regular file. + +The same-basename reporting defect is already CX-01 in the +[complexity audit](03-complexity.md), including its dynamic evidence. This audit +does not recount it as a new defect; it identifies the missing ownership seam. + +**Remediation options.** Prefer a read-only audio-source discovery operation in +the existing `internal/audio` package. Supply explicit selection and source-base +values and return sources or remote identities. Preparation retains copying, +canonical destination naming, and manifest updates; app retains reporting. +Storage adapters continue to receive explicit bucket-relative prefixes. + +A narrow separate source-selection package is viable if it materially avoids +dependencies on audio materialization. The existing audio owner is the smaller +starting point. Share discovery and filters rather than turning operator +inspection into a preparation-stage invocation. + +**Supporting tests and tradeoffs.** +[Preparation tests](../../../internal/stage/prepare_test.go) cover explicit +lists, directory enumeration, and duplicate source rejection. +[TestLocalAudioDestinationsPreserveDistinctRecordings](../../../internal/stage/audio_destinations_test.go) +protects disambiguation and source preservation. Keep inspection read-only and +retain the separately selected S3 basename rules. Resolve current eligibility +differences explicitly against the existing contract rather than adopting the +strictest implementation merely to simplify sharing. CX-01's correctness fix +retains its original priority. + +## BN-05 — P3: Configured-artifact graph operations are fragmented across domain owners + +Status: Open + +**Relevant implementation.** +[config/artifact_dependencies.go](../../../internal/config/artifact_dependencies.go): +`resolveArtifactDependencies` derives the concrete edge union and origin data. +[config/validate_scriptorium.go](../../../internal/config/validate_scriptorium.go): +`ValidateScriptoriumArtifactDependencies` rebuilds adjacency and validates it. +[stage/analyze_fingerprint.go](../../../internal/stage/analyze_fingerprint.go): +`normalizedAnalyzeDependencyKeys` and `orderConfiguredAnalyzeArtifacts`. +[stage/analyze_plan.go](../../../internal/stage/analyze_plan.go): +`AnalyzeTargetClosure`. +[stage/analyze.go](../../../internal/stage/analyze.go): +`staleAnalyzeDependentClosure`. +[artifacts/previous_requirements.go](../../../internal/artifacts/previous_requirements.go): +`CollectPreviousArtifactRequirements` consumes the selected target set. + +**Basis.** Configuration owns the concrete graph, while stage code owns its +normalization, work ordering, prerequisite closure, and reverse-edge rebuilding. +Artifact services expose an effective selection that is targets-only; consumers +must know when to expand it. These are different views of one domain relation, +with no single query boundary for its mechanics. The earlier FC-01 missing +previous-input closure illustrates the resulting cross-package ambiguity. + +**Remediation options.** Prefer exposing dependency queries from the existing +derived `config.ArtifactCatalog` owner: validated adjacency, dependency-first +order, prerequisite closure, and dependent traversal. Make selected targets and +required work separate explicit results. Preparation and restore can then ask +for inputs of the work closure without depending on analyze-stage internals. +Stage code retains force, reuse, fingerprint payloads, and invalidation decisions. + +A lower-level artifact-graph package taking keys and edges is a viable +alternative if needed to keep dependencies acyclic. Preserve configuration's +source-origin diagnostics at its boundary. A generic workflow engine would +serve a different problem. + +**Supporting tests and tradeoffs.** Configuration dependency tests, +[fingerprint ordering tests](../../../internal/stage/analyze_fingerprint_test.go), +and [work-plan tests](../../../internal/stage/analyze_plan_test.go) protect +normalization, invalid-graph rejection, deterministic ordering, disabled +prerequisites, and target-only force. Preserve those distinctions. +`config.ArtifactCatalog` describes derived definitions; the runtime +`artifacts.ArtifactCatalog` additionally tracks manifest-backed availability. +Those responsibilities remain distinct even if their graph queries are shared. +The fixed stage-invalidation relation also remains separate. + +This refines CX-05 in the [complexity audit](03-complexity.md) and EQ-03 in the +[equivalence audit](10-equivalence.md); implement it as their shared remediation. + +## Proportionate Follow-Up + +Address BN-01 and BN-02 as focused ownership corrections. Fold BN-03 through +BN-05 into the cited existing work rather than parallel refactors. The +equivalence audit's transcript predicate and sibling-temp recommendations are +additional small shared-helper opportunities under existing owners. + +The review does not recommend splitting app or stage by file count, merging +configuration definitions with runtime availability, moving stage execution +policy into persistence, or creating an umbrella package for every contract. +Native configuration acquisition, input-schema validation, vocabulary +composition, process supervision, typed checkpoint persistence, and +pointer-selected remote-state verification already have useful boundaries. +Preserve these owners and the fixed pipeline while correcting the narrower +allocation problems above.