From d064d25db92c1336ef9264c666595c47c315c728 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Thu, 26 Nov 2026 13:52:17 +0000 Subject: [PATCH] Retire the completed audit remediation plans --- docs/roadmap/audit-remediation.md | 362 --------- docs/roadmap/audit/catalog.md | 4 +- docs/roadmap/audit/discussion.md | 10 +- docs/roadmap/core-integration-api.md | 16 +- docs/roadmap/future.md | 4 - docs/roadmap/implementation.md | 1041 -------------------------- docs/roadmap/remediation.md | 373 --------- 7 files changed, 15 insertions(+), 1795 deletions(-) delete mode 100644 docs/roadmap/audit-remediation.md delete mode 100644 docs/roadmap/implementation.md delete mode 100644 docs/roadmap/remediation.md diff --git a/docs/roadmap/audit-remediation.md b/docs/roadmap/audit-remediation.md deleted file mode 100644 index d41e5997..00000000 --- a/docs/roadmap/audit-remediation.md +++ /dev/null @@ -1,362 +0,0 @@ -# Audit Remediation Roadmap - -## Status, Purpose, And Ownership - -**Status:** Target design and scope accepted; the staged -[implementation plan](implementation.md) is prepared. Implementation is pending. - -This roadmap defines the end state and required work for the remaining -[audit catalog](audit/catalog.md) findings, incorporating the accepted decisions -in the [discussion record](audit/discussion.md). It is the feature/design handoff -to an implementation agent, not the worker's detailed execution plan. No application -changes are implemented by this document. - -The catalog owns finding inventory, evidence links, and implementation status. -The discussion preserves decision rationale. This roadmap owns the consolidated -target and scope; the implementation plan owns ordered worker stages, concrete -dependencies, verification, and progress. Original audit reports -describe their historical baseline and are not instructions to restore superseded -behavior, particularly diagnostic group caps. - -Planning baseline: `f1b62bdf532118ffc62d0e2bdaefc429bb495df2`. The -[core/integration API migration](core-integration-api.md) and its -[review remediation](remediation.md) are complete. CAT-007, CAT-015, CAT-016, and -CAT-034 are resolved. Of the 30 remaining catalog entries, 29 are in scope here; -CAT-033 is deliberately deferred. Recheck affected callers against current source -when planning, since the core migration partially addressed several findings. - -## Goals And Preserved Boundaries - -The resulting application has clear owners for composition, operation execution, -capture, run finalization, and reusable domain mechanics. Ordinary execution avoids -unnecessary source-scale work. Failure preserves completed-work diagnostics and -error causes without retaining obsolete intermediates. Tests protect meaningful -contracts while permitting legitimate changes to prose and private structure. - -Continue the fixed typed pipeline and native ConfigKit, PromptKit, and CommandKit -architecture. Core retains the implemented operation lifecycle; integrations own -domain interpretation, identity, prompts, correction assignments, and fallback -construction. Generic framework changes must remain usable by non-D&D integrations. -No upstream dependency upgrade is required by this roadmap. - -Preserve configured validation, strict/permissive disposition, cache identity and -reuse controls, generated-reference eligibility, domain schemas, durable identity -bytes, and artifact-first output. PromptKit continues to own native structural -validation/repair, continuation mechanics, and backend admission. Maintain the -bounded worker pool without adding another scheduler or retry mechanism. - -The selected behavior changes are diagnostic group-cap removal, whole-source -capture sharing, cooperative process signals, and correction of cataloged defects. -Refactoring elsewhere preserves established configuration, CLI, acceptance, -ordering, and output contracts. Debug layout remains private. No new result -envelope, durable report sidecar, configuration interpreter, resource-management -framework, or generalized normalization engine is selected. - -## Target Design And Required Work - -### 1. Correct Accepted Boundary Inputs - -**Findings:** CAT-001, CAT-002, CAT-011, CAT-012, CAT-013. - -Correct the documented edge cases at their existing owners without narrowing -accepted inputs to make the implementation easier: - -- Generic chunking handles extreme accepted sizes without overflowing allocation - arithmetic or endpoints; ordinary overlap behavior remains intact. -- Timestamp validation checks exact negativity even when float conversion - underflows. Preserve finiteness, precision, zero/negative-zero handling, and - ordering without a new magnitude limit. -- Reconciliation context expansion handles extreme nonnegative radii using - source-distance-aware arithmetic, retaining the existing material budget. -- Generated producer lookup uses distinct structured step/lane keys rather than - delimiter encodings that collide for accepted identifiers. Do not prohibit NUL - characters as a substitute for fixing lookup identity. -- Metadata copying distinguishes finite shared-prefix slice views from real - cycles. Preserve detached concrete containers, cycle rejection, and useful - error paths; do not ban shared backing arrays or use a JSON round trip. - -Reproduce static counterexamples at their actual boundaries and retain focused -regressions alongside ordinary cases. These fixes do not depend on the broader -composition/copying refactor. - -### 2. Source Work Proportional To What Is Needed - -**Findings:** CAT-004, CAT-005. - -Citation text resolution resolves, sorts, and coalesces selected source ranges, -then visits selected units rather than allocating a document-wide bitmap and -scanning the entire document per record. Preserve source order, errors, one -inclusion of overlapping evidence, and newline joining, including empty, sparse, -disjoint, invalid, and non-monotonic-ID cases. - -Prepare one immutable whole-source position index at the run/source lifetime for -sharing by applicable extraction jobs. Retain local construction for standalone -callers. Preserve whole-document resolution, current-source checks on cache hits, -and isolation between runs and sources. A chunk-only index or process-global cache -does not satisfy this target. Select the small passing/ownership API during -planning; do not introduce a generalized caching facility. - -### 3. A Reusable Native Capture Owner And Convenient Evidence - -**Findings:** CAT-003, CAT-024, CAT-032. - -Extract native request capture into a focused framework package. It owns prepared -request hooks/snapshots, native result and exchange evidence, and capture-error -retention, using PromptKit types and the existing `EvidenceWriter` directly. -Core operations and independently executing validators use the same implementation. -This is required ownership work, independent of any performance improvement. - -Pipeline retains operation identity and step/lane/chunk evidence paths. CLI and -recorder retain filesystem allocation, run-level capture lifecycle, and finalization. -Prefer a dedicated capture package over expanding storage-oriented debug; exact -names remain implementation choices. Preserve prepared-value ownership, -cancellation and capture causes, admission behavior, cache-hit evidence, and -existing observations without duplicate preparation or model calls. Do not add -a telemetry service, replacement execution interface, or synchronized writer wrapper. - -Finish guarding expensive debug-only construction at its owning boundaries when -capture is disabled, including deferred chunk outcomes and run-wide envelopes. -The core migration's lazy operation projections are a starting point, not proof -that all CAT-003 work is complete. Required artifact encoding still runs normally. - -For enabled capture, use the most convenient representation: - -- Record original input and complete parsed source once per run. Operation inputs - reference them using clear logical bundle paths through the same capture sink. - Explicit writer consumers receive shared and operation records alike, without - an assumed CLI filesystem root or records written to another destination. -- Keep particular chunks, operation selections, selected reference contents, and - incoming artifacts directly readable within operation evidence initially. -- Keep convenient native prepared messages, responses, and exchanges, including - useful duplication. Reading a prepared request needs no reconstruction tool. -- A complete bundle preserves whole-source context; an isolated operation directory - need not carry a whole transcript. Logical references require no symlink scheme. - -Keep requested capture required and its failures visible. Retain secret-aware -omissions and actual available evidence. No generalized deduplication, capture -modes, silent truncation, quotas, automatic deletion, or heuristic scrubbing is -included. Private filenames remain implementation choices. - -### 4. Completed Diagnostics And One Runner Finalization Boundary - -**Findings:** CAT-006, CAT-008, CAT-009, CAT-022; CLI coordination in CAT-023. - -Use private working state and one clear runner finalization boundary across -success, failure, and cancellation. The returned logical result does not retain -private execution accumulators, normalized working bytes, or reuse bookkeeping -after their last consumers. Extract cohesive source, chunk/map, and output phases -so stage ordering and failure boundaries are readable without a generic dispatcher. - -Collect completed-operation diagnostics independently of lane continuation or -publication eligibility, including after draining work on failure. Preserve -canonical lane/chunk ordering with sparse and out-of-order completions, without -double counting. Incomplete lanes produce no artifacts or generated handoffs. - -Diagnostic volume alone cannot fail an otherwise successful pipeline. Remove the -local producer group-count cap and final warning/non-warning group-count caps, -including collection-level truncation/omission machinery used solely by those -caps. Retain every distinct group, occurrence counts, and representative sampling -within each group, initially the existing three examples and omitted-sample counts. -Do not replace removed caps with configuration or an exhaustive diagnostic ledger. - -Genuine diagnostic-contract, arithmetic-overflow, reporting, and requested-capture -failures remain failures. Preserve the primary and relevant finalization causes -alongside available valid diagnostics, without repeating a failed aggregation. -Preserve cancellation precedence. Existing errors can describe incompleteness; -no new report schema is needed. Keep completion reporting and fallback disclosure. - -Release references to reorder maps, extraction values, and other intermediates -after their final consumers on success and failure, including while slower sibling -lanes continue. Do not clear shared backing storage or discard data needed for -handoff, capture, encoding, or completed-work diagnostics. - -### 5. Clear CLI Lifecycle And Cooperative Signals - -**Findings:** CAT-010, CAT-023. - -Keep the native command declaration small, with a cohesive private invocation and -finalization owner. Preserve one configuration/engine, supplied-value semantics, -capture allocation before preparation, cause retention, and distinct execution, -physical publication, and report-delivery outcomes. The runner returns logical -results; CLI publishes artifacts, completes capture, and presents native reports. -This is separate from runner phase control and introduces no new command framework. - -At the executable boundary, the first SIGINT or SIGTERM cancels the invocation -context so dispatch stops, native requests cancel, started jobs drain, and ordinary -failure/capture finalization runs. A subsequent signal permits ordinary process -termination and may interrupt finalization. Add no shutdown deadline/configuration -or SIGKILL guarantee. Embedded callers retain ownership of their contexts and -receive no process-wide signal handlers from application invocation. - -Cancellation initiates no fallback or model retry and makes no successful completion -claim. Retain existing cache entries, published artifacts, and available debug -evidence under the established lifecycle. Use a small standard-library adapter and -focused offline subprocess coverage with a local fake backend; do not promise -cooperation from collaborators that ignore cancellation. - -### 6. Pipeline Interpretation And Pure Copying At Their Owner - -**Findings:** CAT-014, CAT-017, CAT-018. - -Within the existing pipeline package, provide shared catalog-independent structural -layout and catalog-aware selected-target inventory. Layout establishes ordered -steps/lanes and identities; inventory selects modules/defaults/variants and reference -slots without requiring them to be populated. Complete resolution reuses these -operations. CLI discovers targets, supplies bindings, then checks completeness; -do not introduce a partial/allow-missing mode in the full resolver. - -ConfigKit and its application integration retain loading, imports, inheritance, -source presence, and provenance. CLI retains selector grammar and precedence. -Pipeline resolution/preparation retains complete binding, capabilities, exact type -compatibility, validator selection/order, and generated-dependency checks. - -Place pure copying beside pipeline-owned types. Preserve values and distinguish -copying from trimming, defaults, and normalization. Inventory supported mutable -option containers before consolidating copies; preserve omission, explicit empty, -explicit zero, and detached ownership. Remove redundant copies where ownership -permits, without imposing universal immutability or a reflection-based copier. -Source-metadata cycle handling remains a separate responsibility. - -Decompose resolution into cohesive same-package helpers and per-binding checks -while retaining useful error context. Demonstrate reuse through configuration, -resolver, and CLI callers and independent selection/isolation tests, rather than -moving duplicated logic into smaller files. - -### 7. Family-Owned Rules And Shared Deterministic Mechanics - -**Findings:** CAT-019, CAT-020, CAT-021. - -Put reusable scene checks with a small scene-family domain owner; tiny predicates -may live beside domain types. Normalizers and validators use it. Validator adapters -retain extraction-specific cardinality, assessment classification, and corrective -prose. Codec acceptance shares only identical primitives, preserving differences -such as trimmedness and the optional nature of selectable checks. - -Introduce a pure duplicate-grouping helper returning retained positions and groups. -Start with NPC occurrences, location occurrences, and combat turns. Families supply -eligibility and identity keys, and own sorting, cloning, original-input-index -mapping, and diagnostics. Include spells only if its nil/allocation behavior fits -cleanly. Leave item occurrences separate initially, preserving its bucket-plus- -exact-equality check. Do not collapse distinct evidence, combine evidence ranges, -or make domain eligibility rules uniform to simplify the helper. - -Calculate invariant sorting keys once per normalized record using the existing -combat approach. Preserve ties, invalid-reference ordering, and defensive comparison -for inputs whose canonical form is not established. Genuine evidence tie comparison -may still require linear work. This improvement is independent of duplicate sharing. -Use independent family expectations; no universal normalizer or sorting framework. - -### 8. Explicit Extension Contracts And Maintainable Tests - -**Findings:** CAT-025, CAT-026, CAT-027, CAT-028, CAT-029. - -Document sharing and lifetimes in module internals and interface comments: -prepared extractors, extraction validators, and shared codecs can receive overlapping -calls; per-operation mutable state stays local/operation-owned, intentionally shared -mutable state is synchronized, and shared source is read-only. Describe each stage's -actual call pattern rather than claiming every module method runs concurrently. -The runner waits for dispatched operations, not arbitrary extension goroutines; -extensions own their background work's lifetime relative to borrowed collaborators. - -Custom writers shared across concurrent operations must support concurrent calls; -point to the standard synchronized recorder. Defer a synchronized wrapper until -a concrete serial-only consumer needs one. Link native client/observer/callback -contracts upstream and explain where Notarius shares them. Add no automatic writer -serialization, per-job module construction, or blanket locking. - -Include these test improvements explicitly: - -- Replace incidental production-English assertions and message-location markers - with test-controlled content and behavioral preparation/binding checks. Preserve - schemas, input/default selection, required properties, cache hints, and follow-up - routing. Prompt quality remains a human review concern, not a prose snapshot. -- Replace sleep-induced overlap and unbounded handshakes with explicit start/release - gates, bounded cancellation-safe failure handling, and joining started work. - Preserve worker limits and ordering; test watchdogs create no runtime deadline. -- Separate maintained-example checks and independent resolved fixtures, retaining - useful integration coverage without shared-map execution-order dependence. -- Remove the private run-ID format regex while preserving uniqueness, safe paths, - collision/allocation behavior, and partial-write protection. Keep the separate - versioned session-ID contract and its exact-value protection. - -### 9. Remove Obsolete Metadata And Helpers - -**Findings:** CAT-030, CAT-031. - -Recheck and delete the audit's confirmed unused private policy labels and three -private helpers. Preserve live identity constants/bytes, keys, reason codes, -schemas, guidance, and similarly named live helpers. Do not resurrect policy -fingerprints or alter cache keys to give dead labels a purpose. - -Give the six exported internal `NormalizationPolicy` aliases a short intended-use -review. Remove those without a supported purpose; explicitly defer any whose -purpose remains unclear. Capitalization alone establishes no external API, and -this review requires no broad compatibility initiative. Existing behavioral tests -suffice for declaration deletion; add no count/absence tests. - -## Coverage And Disposition - -All catalog entries have the following disposition; section numbers identify the -target above, not mandatory worker stage numbers. - -| Catalog entries | Disposition / target | -| --- | --- | -| CAT-001, CAT-002, CAT-011, CAT-012, CAT-013 | Required: section 1 boundary correctness | -| CAT-004, CAT-005 | Required: section 2 source work | -| CAT-003, CAT-024, CAT-032 | Required: section 3 capture | -| CAT-006, CAT-008, CAT-009, CAT-022 | Required: section 4 finalization and lifetimes | -| CAT-010 | Required: section 5 signals | -| CAT-023 | Required: sections 4–5 CLI/runner separation | -| CAT-014, CAT-017, CAT-018 | Required: section 6 composition and copying | -| CAT-019, CAT-020, CAT-021 | Required: section 7 domain mechanics | -| CAT-025, CAT-026, CAT-027, CAT-028, CAT-029 | Required: section 8 contracts and tests | -| CAT-030, CAT-031 | Required: section 9 cleanup; aliases have the stated conditional disposition | -| CAT-007, CAT-015, CAT-016, CAT-034 | Already resolved; preserve established behavior | -| CAT-033 | Deferred; retain the matcher until representative workloads justify optimization | - -Deferral does not mean a defect was fixed. No token-matching algorithm replacement, -name-length cap, or new benchmark gate is part of acceptance. Future email/NWS -integrations, broader domain/package migration, release publication, and upstream -feature work are outside this remediation. - -## Implementation Handoff - -The [implementation plan](implementation.md) owns ordered worker stages, concrete -APIs, dependencies, checks, and progress. The completed core migration is the -baseline; its former detailed plan remains available in Git history. Accepted -decisions here qualify historical audit recommendations. A new conflict with the -target must be reported rather than silently changing inputs, acceptance, or scope. - -Implementation is one end-to-end sprint; intermediate buildability is not a -separate product requirement. Completion is judged against the target below, -not an intermediate compatibility surface or a closed-finding count. - -## Verification And Completion - -Use [testing policy](../policy/testing.md) to select focused, offline behavior tests. -Correctness regressions must demonstrate the defect at the relevant boundary. -Retain independent domain-output expectations for ordering, identity, and acceptance; -exercise cancellation, capture failure, and completed-diagnostic retention where -lifecycle changes affect them. Run relevant race checks for changed concurrent -paths and repository-wide `go test ./...`, `go vet ./...`, and -`go build ./cmd/notarius` at shared-contract milestones and final acceptance. -Reuse successful checks for unchanged content; default tests need no credentials -or paid model calls. Claim measured speedups only when measured, without a new -coverage, benchmark, complexity, or broad-audit gate. - -Update canonical internal, architecture, authoring, and operator documents when -their behavior lands. Reconcile diagnostic cap removal and whole-source sharing -with ADR-0015/ADR-0024 through successor decisions/status links as appropriate, -preserving accepted ADR bodies. Keep configuration/CLI references unchanged unless -an implemented selected behavior actually requires an update. - -Completion requires all required coverage rows to have implemented target behavior -and appropriate verification, including capture extraction, ordinary-run costs, -failure paths, source/option isolation, family output preservation, and explicit -test cleanup. Record alias-review dispositions. Catalog statuses must identify -what was actually resolved; CAT-033 remains deferred. Canonical documentation, -implementation status, and code must agree. A smaller file, green happy-path test, -or closed finding count alone is not evidence of completion. - -There are no unresolved product or scope decisions. The implementation plan -records selected APIs and stage decomposition within these boundaries. diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md index 3236d507..007f424a 100644 --- a/docs/roadmap/audit/catalog.md +++ b/docs/roadmap/audit/catalog.md @@ -14,8 +14,8 @@ another code audit or an implementation plan. The companion [remediation discussion](discussion.md) collects review recommendations and open choices in discussion order. Accepted decisions there qualify proposed remediation; finding statuses here track implementation. -The [Audit Remediation Roadmap](../audit-remediation.md) consolidates the accepted -target and required work for the remaining findings, with CAT-033 deferred. +The completed Audit Remediation Roadmap and implementation plan are retained in +Git history; they consolidated the accepted target with CAT-033 deferred. The [Core And Integration API Roadmap](../core-integration-api.md) established the core/integration boundary. The reassessment below distinguishes its completed work from the remaining audit remediation. diff --git a/docs/roadmap/audit/discussion.md b/docs/roadmap/audit/discussion.md index 111fee43..66303256 100644 --- a/docs/roadmap/audit/discussion.md +++ b/docs/roadmap/audit/discussion.md @@ -6,9 +6,9 @@ This document consolidates the review recommendations for the [audit catalog](catalog.md) into an ordered discussion for maintainers. The catalog owns the finding inventory and prioritization; its linked audit reports own detailed evidence and qualifications. This document preserves discussion -decisions and rationale. The [Audit Remediation Roadmap](../audit-remediation.md) -owns the consolidated target and scope; a subsequent implementation plan will own -detailed worker stages. +decisions and rationale. The completed Audit Remediation Roadmap and +implementation plan are retained in Git history, recording the consolidated +target and worker stages. Prepared on 2026-11-24 against catalog revision `5a0650250686353cf34fbbbf0e780b04f60e70c1`. All discussion decisions are now @@ -393,8 +393,8 @@ Recommended approach: Use one focused implementation plan linking worker stages to catalog findings and accepted scope, with dependencies, observable completion criteria, verification, and documentation updates. Keep finding status in the catalog and rationale here; -do not copy the audit reports into the plan. The -[formal roadmap](../audit-remediation.md) defines the end state for that handoff. +do not copy the audit reports into the plan. The retired formal roadmap, +available in Git history, defined the end state for that handoff. This is an ordering guide, not a serial dependency chain. Cheap independent fixes can proceed without waiting for broader discussion. Practical reachability and diff --git a/docs/roadmap/core-integration-api.md b/docs/roadmap/core-integration-api.md index 65d6c4cd..f200593c 100644 --- a/docs/roadmap/core-integration-api.md +++ b/docs/roadmap/core-integration-api.md @@ -3,19 +3,19 @@ ## Status And Purpose **Status:** Implemented and reviewed for the selected core/integration boundary. -See [final acceptance](implementation.md#stage-24--perform-final-sprint-acceptance) -and [review remediation](remediation.md). +Final acceptance and review remediation records are retained in Git history. -This roadmap records the completed prerequisite to the remaining -[audit remediation](audit-remediation.md). It develops +This roadmap records the completed prerequisite to the subsequent audit +remediation, whose completed planning documents are retained in Git history. It +develops [discussion Item 5](audit/discussion.md#5-producer-state-and-shared-reconciliation-lifecycle) into an integration-author API initiative, rather than a private-helper cleanup. The target design below is retained as the migration record; its baseline section describes the pre-migration state. -[Implementation Plan](implementation.md) owns the ordered implementation stages -and stage-specific validation. This document owns scope, target behavior, and -the accepted design decisions. +The retired implementation plan records ordered stages and stage-specific +validation in Git history. This document owns scope, target behavior, and the +accepted design decisions. The selected goals are: @@ -324,7 +324,7 @@ family tests. Simplify tests coupled to retired plumbing; do not derive expected domain outputs from the same helper under test. This is a coverage guide, not a new test for every row or an exhaustive cross-product requirement. -The [Implementation Plan](implementation.md) assigns focused and final checks +The retired implementation plan assigned focused and final checks under [Testing Policy](../policy/testing.md) and [Development](../development.md#validation). Completion evidence includes offline full tests, vet, build, and focused race checks for changed concurrency paths. diff --git a/docs/roadmap/future.md b/docs/roadmap/future.md index b2a04e40..2ff9d3ee 100644 --- a/docs/roadmap/future.md +++ b/docs/roadmap/future.md @@ -5,10 +5,6 @@ configuration, operations, internal, and integration docs. This backlog records proposed extensions to that implementation. Items below are ordered roughly by value and specificity, not as committed release dates. -The accepted [Audit Remediation Roadmap](audit-remediation.md) is the current -follow-on to the completed core/integration migration. It owns that remediation's -target and scope; the proposals below remain separate future work. - ## Near-Term D&D Pipeline ### Evaluate Spell Extraction And Normalization diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md deleted file mode 100644 index 3a24d7d6..00000000 --- a/docs/roadmap/implementation.md +++ /dev/null @@ -1,1041 +0,0 @@ -# Audit Remediation Implementation Plan - -## Purpose And Baseline - -Implement the accepted [Audit Remediation Roadmap](audit-remediation.md). -It owns target behavior and scope; the [catalog](audit/catalog.md) owns finding -status, and the [discussion](audit/discussion.md) owns accepted rationale. -Historical reports are evidence, not instructions to restore superseded proposals. - -Baseline: `57fce85c822cb0a8a7c057400a64cef2892b6f8f`. The completed 24-stage -core/integration migration and cancellation fix are the starting architecture. -Its former implementation plan remains in Git at this revision. CAT-007, CAT-015, -CAT-016, and CAT-034 are resolved; CAT-033 stays deferred. This plan covers the -other 29 catalog findings. No dependency upgrade is needed. - -## Worker Instructions - -Each numbered stage is one prompt for a Luna coding agent. Execute in order as -one end-to-end sprint. Prerequisites identify substantive dependencies. Intermediate -stages need not compile or leave a coherent repository. Do not add compatibility -APIs, duplicate implementations, or temporary supported behavior just to make them -green. Record deferred checks and finish them at the next applicable milestone; -all acceptance criteria must hold at sprint completion. - -Start with [Development](../development.md), [Agent Policy](../policy/agents.md), -and applicable policies. Confirm current callers through code discovery; paths -below are starting points, not closed inventories. Follow commit policy for -completed nonempty units, honestly describing intermediate migration conditions. -This plan authorizes no push or release. - -Path shorthand: `dnd` means `internal/modules/dnd`; bare runner/resolver filenames -are under `internal/framework/pipeline`, and contracts/capture/diagnostics/ -semanticreconcile are its sibling framework packages unless qualified otherwise. - -After each stage, record actual changes, checks, and follow-up here. Update catalog -status only after full scope is verified. Update canonical documentation alongside -changed behavior. Do not duplicate upstream kit feature documentation or carry -audit history into current internal guides. - -### Preserved Boundaries - -- Keep the fixed typed pipeline, core-owned lifecycle, native kits, worker/admission - separation, configured validators, strict/permissive disposition, and cancellation - precedence. Model validators remain one-shot per assessment. -- Preserve schemas, durable identity bytes, reference eligibility, current-source - cache checks, cache identity, source order, and artifact-first publication. -- Selected behavior changes are boundary repairs, diagnostic group-cap removal, - whole-source capture sharing, and cooperative executable signals. Other work - preserves established configuration, CLI, and acceptance behavior. -- Add no new input bound, identifier prohibition, scheduler, retry loop, shutdown - deadline, configuration interpreter, normalization engine, telemetry service, - exhaustive diagnostic ledger, or report sidecar. -- Keep requested capture required, cache I/O best effort, native secret omissions, - deployment-owned access policy, and output/debug retention. No scrubbing, quotas, - automatic deletion, or blanket locking is selected. - -## Cross-Stage Implementation Decisions - -### Source Lookup - -Add optional `SourceIndex *source.DocumentIndex` to `contracts.ExtractionInput`. -It borrows the complete `Source` index, read-only, not a chunk index. Construct one -after runner source validation and share across steps, extraction inputs, and -artifact cache decoders. Replace the private cache-only index supplier with this -value. Standalone cache construction can retain local lazy indexing. - -Add a small D&D source-order constructor accepting document plus optional index: -use `NewSourceRefOrderFromIndex` when supplied, otherwise construct locally. -Do not revalidate/reindex the document per job. Runner provenance establishes the -match; direct callers supply an index for their source or omit it. No process-global -cache or new rejection policy is needed. - -For `CitationResolver.CitedText`, resolve refs to position intervals, sort/coalesce, -then traverse only their union. Numeric IDs do not define chronology. Empty/sparse -citations need no document-sized bitmap or full-source scan. - -### Capture - -Create `internal/framework/capture` for native request hooks, prepared ownership/ -snapshots, events, result/exchange evidence, and retained capture errors. Move -`CaptureNativeRequest`/`NativeCapture` with minimal API change, using PromptKit -types and `contracts.EvidenceWriter` directly. Pipeline keeps operation identity, -path scoping, and application projections. CLI/debug keep allocation, observation -grouping, and terminalization. Validators and core use the same implementation. - -Select the effective sink once: explicit `RunInput.Execution.Capture`, otherwise -enabled `RunInput.Debug`, otherwise none. Send shared source and operation records -there. Use logical root paths `source/input.json` and `source/output.json` for -original input and parsed source. A private descriptor on runner targets carries -clearly labeled bundle-root references, not operation-relative filesystem paths. - -Keep chunks, selections, references, incoming artifacts, and native messages/ -responses/exchanges inline. Do not rewrite prepared messages as references. -If explicit capture and Debug differ, required shared records must not go only to -Debug or repeat full-source payloads there. Standalone native capture needs no -run descriptor. No symlink, assumed filesystem root, or reconstruction tool. - -### Working State And Finalization - -Use private `runState`/`laneOutput` for normalized bytes, reuse bookkeeping, -pending diagnostic groups, and fallback counts. `RunOutput` contains only final -logical diagnostics/files/fallback count. Physical publication remains in CLI. - -Coordinator-owned completed groups are independent of accepted values and lane -eligibility, including available groups accompanying errors. After drain, assemble -once in stable step/lane/chunk/stage order. Continuation must not append extraction -groups again. Reuse compact operation results, not an exhaustive event ledger. - -One runner finalizer aggregates once on success/failure/cancellation. On aggregation -failure, retain its valid prefix plus primary/finalization causes; do not repeat -the failed pass. Incomplete lanes still produce no artifacts/handoffs. Preserve -canonical error choice, cancellation precedence, and required-capture causes. - -### Composition And Copying - -Keep these concrete operations in `internal/framework/pipeline`: - -- Pure `ClonePipelineProfile`, `CloneModuleBinding`, and subordinate copies beside - their types. No trimming/defaults/validation. Preserve nil/empty/zero and copy - existing mutable options: `map[string]any`, `[]any`, `[]string`, `[]byte`, and - `json.RawMessage`. Retain supported scalars without new rejection. -- `LayoutPipeline(profile)` returns normalized identities, ordered steps/lanes, - and established flat/explicit structural checks without a catalog. Config owns - map-key matching and ConfigKit presence/provenance checks. -- `SelectPipelineTargets(layout, only, catalog)` returns selected chunk/lane stage - bindings/specs, artifact kinds, kind-specific variants, reference slots, and - configured-lane inventory. References need not be populated. Preserve defaults, - unselected-lane behavior, and explicit-step/`only` semantics. -- Complete resolution reuses selections, then owns full binding, capabilities, - validators, generated dependencies, effective controls, and digest. CLI discovers - slots, applies bindings, then resolves. Grammar/precedence remain CLI-owned; - no partial/allow-missing mode in full resolution. - -Names may follow nearby conventions, but preserve this data flow. Move trimming -explicitly into interpretation when replacing the old normalizing clone helper. -Do not introduce a second configuration model or independent selector. - -### Family Mechanics - -Use `internal/modules/dnd/scenedescriptions` for pure reusable scene checks; -the existing registry subpackage remains. Return facts/field locations, not -classification or corrective prose. Adapters retain extraction-only cardinality. -Codecs share only primitives with identical existing acceptance. - -Add a pure generic helper in `dnd/shared`: given a count and a callback returning -`(key, eligible)` for each index, return retained positions and groups of -representative/removed positions. Preserve first-representative group order, not -second-copy discovery order. Ineligible records stay independent. Families own keys, eligibility, sorting, -cloning, original-index mapping, and diagnostics. No evidence merging. - -Prepare invariant sort keys once per owned normalized record. Keep defensive -comparators for unproven inputs; canonical fast paths retain their existing premise. - -## Stage 1 — Fix Accepted Range Arithmetic - -**Completed.** Chunk planning uses overflow-safe capacity and remaining-length -arithmetic; reconciliation bounds expansion by source distance. Regressions -reproduced both failures before the fixes and cover maximum values, overlap, -cited flags, and the material budget. The specified package tests pass. No -follow-up remains for this stage. - -**Coverage:** CAT-001/CAT-011. **Prerequisites:** none. - -Inspect generic `chunk/units/chunker.go` and reconciliation `preparation.go` plus -audit counterexamples. Replace overflowing chunk capacity/endpoints with safe -division or remaining-length comparisons. Expand windows by source distance before -addition/subtraction. Keep overlap and the independent material byte budget. - -**Acceptance:** Failing-before/fixed-after regressions exercise real option -decoding/planning with `math.MaxInt` on three units and ordinary overlap with -literal expected ranges. Maximum nonnegative radius includes the small whole -source/cited flags, or the existing byte-limit disposition when material does not -fit. No panic, wraparound, or new limit. - -**Check:** `go test ./internal/modules/generic/chunk/units ./internal/framework/semanticreconcile`. -Existing public contracts need no rewrite. - -## Stage 2 — Check Exact Timestamp Negativity - -**Completed.** Timestamp validation checks the exact rational sign after the -existing finite-number check. Parser regressions cover tiny negative endpoints, -tiny positives, negative zero, ordinary values, exact ordering, and retained -numeric metadata. The specified package test passes. No follow-up remains. - -**Coverage:** CAT-002. **Prerequisites:** none. - -In Seriatim `adapter.go`/`validTimestamp`, check rational sign while retaining -float finiteness handling, exact ordering, and numeric metadata. - -**Acceptance:** Real `Parse` rejects `-1e-1000` at either endpoint. Tiny positives, -zero/negative zero, ordinary numbers, and precise start/end comparisons retain -behavior. Add the parser regression, not a magnitude/exponent bound or new parser. - -**Check:** `go test ./internal/modules/seriatim/input/transcript`. -No contract change is required. - -## Stage 3 — Use Structured Producer Lookup Keys - -**Completed.** Resolution uses the existing structured producer key for both -insertion and lookup. Real-resolution regressions reproduced the collision and -cover each producer with matching and mismatched kinds. The specified focused -pipeline tests pass. Later resolution decomposition must preserve this behavior. - -**Coverage:** CAT-012. **Prerequisites:** none. - -Replace generated-binding insertion/lookup concatenation with -`generatedOutputKey`/`generatedOutputKeyFor` from `pipeline/handoff.go`. - -**Acceptance:** Real resolution coverage uses pairs `("a\x00b", "c")` and -`("a", "b\x00c")` with different kinds. Valid earlier references check the right -producer; real kind mismatches fail. No new identifier restriction or handoff change. - -**Check:** `go test ./internal/framework/pipeline -run 'Generated|Handoff|ResolvePipeline'`. -No public grammar/documentation change. - -## Stage 4 — Distinguish Finite Slice Views From Cycles - -**Completed.** Metadata recursion tracks each nonempty slice's visible length -with its type and pointer, and skips cycle tracking for empty views. Regressions -reproduced the shared-prefix failure and cover detached sharing, nil/empty views, -and actual map and slice cycles; existing tests cover concrete containers. Both -specified package tests pass. No follow-up remains. - -**Coverage:** CAT-013. **Prerequisites:** none. - -In source `metadata.go`, include visible length in active slice identity with -type/pointer. Empty views have no children requiring tracking. Preserve map cycle -handling, concrete-container reflection copying, and useful error paths. - -**Acceptance:** The shorter shared-prefix counterexample clones and is detached. -Ordinary sharing succeeds; actual map/slice cycles fail. Protect nil/empty and -concrete containers. No shared-array ban, JSON round trip, or option-copier merger. - -**Check:** `go test ./internal/core/source ./internal/modules/seriatim/input/transcript`. - -## Stage 5 — Resolve Sparse Citations From Coalesced Intervals - -**Completed.** Citation resolution validates in input order, sorts and coalesces -position intervals, and visits only selected units. Literal tests cover sparse, -overlapping, disjoint, invalid, non-monotonic, and empty-text cases. The specified -shared and validator tests pass; no performance timing claim or follow-up remains. - -**Coverage:** CAT-004. **Prerequisites:** none. - -Rewrite `dnd/shared/citations.go` as selected. Validate refs in input order before -sorting positions. Avoid source-scale allocation/traversal per sparse record. - -**Acceptance:** Literal text cases cover empty/sparse, nested/overlapping, -disjoint, invalid/wrong-source/reversed refs, non-monotonic IDs, and empty unit -text. Include units once in source order with unchanged newline joining. Inspect -the algorithm to establish reduced work; no wall-clock gate. - -**Check:** `go test ./internal/modules/dnd/shared ./internal/modules/dnd/validate/...`. - -## Stage 6 — Supply One Run-Owned Source Index - -**Completed.** The runner builds one whole-source index after validation, shares -it with extraction jobs and cache decoders, and retains lazy local cache indexing -for standalone construction. The D&D ordering constructor accepts an optional -index. Tests cover jobs across steps, separate same-ID layouts, cache decoding -and omitted-index use. The specified package tests pass. Extractor migration and -the final CAT-005 disposition remain in the following stages. - -**Coverage:** CAT-005 framework. **Prerequisites:** none. - -Add `ExtractionInput.SourceIndex`, runner initialization, extraction passing, -and cache decoder reuse in contracts/preparation.go, pipeline/runner.go, -runner_concurrent.go, and runner_cache.go. Add the optional-index D&D constructor. -Keep mutable chunk/metadata isolation. - -**Acceptance:** A generic typed test receives a complete-source index shared -across jobs/steps. Separate runs with the same ID and changed layouts remain -isolated; cache checks use current source. Missing standalone index builds locally. -No mutable map exposure/process-global cache. - -**Check:** `go test ./internal/core/source ./internal/framework/contracts ./internal/framework/pipeline ./internal/modules/dnd/shared`. -Update borrowed-index comments and module internals alongside the API. - -## Stage 7 — Reuse The Index In Registry Extraction - -**Completed.** NPC, item, and location registry preparation borrows the optional -whole-source index for response ordering and endpoint repair, falling back locally -when absent. Existing literal output tests exercise both paths, including -non-monotonic source order. All three specified package tests pass. Other -extractors and the CAT-005 catalog disposition remain for the following stages. - -**Coverage:** CAT-005 registry callers. **Prerequisites:** Stage 6. - -Migrate NPC/item/location registry extractors, including interpretation and -endpoint repair. Remove repeated indexing, not no-model behavior, prompts, -schemas, or identity rules. - -**Acceptance:** Omitted-index standalone and representative supplied-index tests -preserve literal output and non-monotonic ordering. Preparation/interpretation do -not rebuild the index. No cache-key or entity-ID change. - -**Check:** `go test ./internal/modules/dnd/extract/npcregistry ./internal/modules/dnd/extract/itemregistry ./internal/modules/dnd/extract/locationregistry`. - -## Stage 8 — Reuse The Index In Occurrence Extraction - -**Completed.** NPC, item, and location occurrence extraction use the optional -whole-source index for ordering and endpoint repair. Location grounding shares -that index, including a single locally built fallback for standalone extraction. -Existing contextual-selector, identity, evidence, and invalid-reference tests -remain in place; representative supplied-index cases and all three specified -package suites pass, as does the location registry suite. Remaining extractor -paths and the CAT-005 catalog disposition follow next. - -**Coverage:** CAT-005 occurrence callers. **Prerequisites:** Stages 6–7. - -Migrate NPC/item/location occurrence extractors. Preserve registry resolution, -holder policy, references, interpretation, and fallback. - -**Acceptance:** Omitted/supplied-index tests retain contextual selections and -evidence. Whole-source checks still distinguish invalid refs from endpoint repair. -The optional index is not a new required caller argument. - -**Check:** `go test ./internal/modules/dnd/extract/npcoccurrences ./internal/modules/dnd/extract/itemoccurrences ./internal/modules/dnd/extract/locationoccurrences`. - -## Stage 9 — Complete Extraction Index Reuse - -**Completed.** Spells, combat turns, enemy events, and scene descriptions now -borrow the run index, with local construction when omitted. Combat eligibility -still returns before ordering construction. The six registry/occurrence paths -use the same optional ordering constructor; location grounding shares its index, -and scene reuse/fallback validates against the same whole-source index. Focused -extractor and pipeline tests, pipeline/shared race tests, and full tests, vet, -and build passed. Cross-run layout and cache checks are covered by the preceding -framework tests. No production speedup was measured or follow-up deferred. - -**Coverage:** CAT-005 completion. **Prerequisites:** Stages 6–8. - -Migrate spells, combat turns, enemy events, and scene-description extractors. -Preserve combat-gated early returns. Trace all ten paths to verify supplied-index -use; add only missing representative coverage, not duplicate constructor tests. - -**Acceptance:** Verify whole-source resolution, concurrent readers, cache hits, -standalone calls, steps, and source/run isolation. Record actual construction -paths, not unmeasured production speedups. - -**Check:** `go test ./internal/modules/dnd/extract/... ./internal/framework/pipeline`; -`go test -race ./internal/framework/pipeline ./internal/modules/dnd/shared`. -Update D&D internals/catalog; full tests/vet/build at this shared-contract milestone -if no recorded migration condition prevents it. - -## Stage 10 — Control Worker-Test Overlap And Bound Handshakes - -**Completed.** Continuation overlap is established by start/release gates; -reverse-completion handshakes enforce actual completion order, detect early runner -exit, and use bounded cancellation and joining. Both tests check no jobs remain -active. The prescribed ten-run focused check and affected race check pass. No -runtime timeout guarantee or follow-up was added. - -**Coverage:** CAT-027. **Prerequisites:** none; precedes lifecycle edits. - -Replace continuation sleep in runner_concurrency_test.go with start/release gates. -Bound reverse-completion receives, observe early runner failure, cancel/release on -test failure, and join started work. Use ready_jobs_test.go as a local example. - -**Acceptance:** Deterministically establish overlap at a controlled limit, stable -ordering, and no retained activity. Broken scheduling fails locally, not at the -suite timeout. No runtime deadline or throughput guarantee. - -**Check:** `go test ./internal/framework/pipeline -run 'Concurrent|Concurrency|ReverseCompletion|ReadyJobs|Cancellation' -count=10`; -run affected pipeline tests under `-race` once. - -## Stage 11 — Extract Native Capture Ownership - -**Completed.** Request hooks, snapshot ownership, events, results, and retained -capture errors moved to framework/capture; pipeline retains operation scoping and -the validator uses the shared owner. Direct capture tests cover hook composition, -snapshot ownership, and write errors; pipeline integration retains cache, -provider/cancellation, continuation, and evidence tests. The specified normal -and race suites pass, as do focused CLI capture tests. No representation change -or follow-up remains for this ownership move. - -**Coverage:** CAT-032. **Prerequisites:** Stage 10. - -Move request-level code/tests from pipeline/native_capture.go into framework/capture. -Keep operationExecution/scoped paths in pipeline. Core and the independently -executing combat-semantics validator import the shared implementation. Remove old -forwarding entry points. - -**Acceptance:** Preserve callbacks/observers, prepared ownership, I/O outside -admission, native results/exchanges, cache-hit availability, and joined capture/ -provider/cancellation causes. No extra preparation/model calls. Keep cancellation- -during-evaluation-capture regression. Capture imports no pipeline/domain. -Do not change representation in this stage. - -**Check:** `go test ./internal/framework/capture ./internal/framework/pipeline ./internal/modules/dnd/validate/scenedescriptions/combat_semantics`; -these packages under `-race`. Update overview/LLM/state package pointers. - -## Stage 12 — Avoid Disabled-Capture Construction - -**Completed.** Run-wide source, chunk, lane, artifact, output, and evidence-summary -projections are constructed only for enabled debug capture; deferred chunk -outcome projection is guarded by the operation's effective capture writer. -Existing operation-input, result, assessment, and evaluation projections were -inspected and already guard construction. Mandatory artifact serialization is -unchanged. Focused projection, pipeline, capture, and integration tests pass; -subsequent source-sharing and runner decomposition must retain these guards. - -**Coverage:** CAT-003. **Prerequisites:** Stage 11. - -Inspect debug.go, runner.go, runner_chunk_plan.go, runner_concurrent.go, -runner_typed.go, operation_capture.go, and existing lazy projections. Guard expensive -construction before argument evaluation, including deferred chunk outcomes and -run-wide payloads. Prefer direct checks; a lazy helper needs actual repeated use. -Mandatory artifact encoding remains outside guards. - -**Acceptance:** Disabled paths build no debug-only source/base64/chunk/artifact -envelopes. Enabled capture retains evidence/failures; deterministic, cache-hit, -and failure results remain. Establish by boundary inspection and focused projection -tests, not unstable allocation ceilings. - -**Check:** `go test ./internal/framework/pipeline ./internal/framework/capture ./internal/modules/integration`. -Comment subtle deferred ownership; record all inspected boundaries in catalog. - -## Stage 13 — Share Source Evidence At The Effective Sink - -**Completed.** The runner selects the explicit writer or enabled debug sink once, -records original input before parsing and validated source afterward, and passes -labeled bundle-root references through run, chunk, lane, and operation inputs. -Chunk and native request evidence remain inline. Tests cover multiple jobs, -cache hits, each sink selection, both shared-write failures, and parse failure; -the prescribed suites and targeted pipeline race checks pass. ADR-0027 records -the narrow source-representation decision. No follow-up remains for this work. - -**Coverage:** CAT-024. **Prerequisites:** Stages 11–12. - -Implement selected sink, shared source records, and descriptor passing through -runner targets. Update operation/run/chunk/lane inputs to reference full source, -preserving selections/chunks/references/incoming artifacts/native messages inline. -Record raw input before parsing and parsed source after validation; retain only -evidence actually available on failure. - -**Acceptance:** An explicit in-memory writer receives shared and operation records -with resolvable links. Cover multiple jobs, cache hits, Debug-only and distinct -explicit/Debug sinks, and shared-write failure. One original/parsed copy supports -bundle context; no symlinks/reconstruction/sanitization promise. Test content/link -integrity, not private layout snapshots. - -**Check:** `go test ./internal/framework/pipeline ./internal/framework/capture ./internal/cli`. -Add a narrow successor ADR/status link for ADR-0024 source representation; preserve -accepted bodies. Update state/LLM/operations and affected evidence tests. - -## Stage 14 — Remove Group Caps, Retain Sampling And Overflow Checks - -**Completed.** Local and final group-count caps and collection-only truncation -metadata are removed; origin-aware ordering, three samples, omitted-sample -counts, validation, and checked occurrence totals remain. Many-group collector, -aggregator, and runner regressions pass, as do overflow and the prescribed -contracts, diagnostics, pipeline, and CLI suites. ADR-0028 records the capacity -decision. CAT-009's single finalization and failure-cause work remains pending. - -**Coverage:** CAT-009 capacity policy. **Prerequisites:** none. - -In contracts/diagnostics, collector, aggregator, and CLI consumers, remove local/ -final group caps and solely cap-related collection truncation/unrepresented fields. -Keep intrinsic validation, count overflow checks, origin-aware grouping/order, -three samples, and per-group omitted counts. No replacement knob/occurrence ledger. - -**Acceptance:** Test-controlled many-group local/final collections retain all groups. -Repeated occurrences merge/sample; invalid contracts/overflow fail. A many-group -pipeline succeeds without capacity failure. Do not retain cap errors as the -finalization oracle. - -**Check:** `go test ./internal/framework/contracts ./internal/framework/diagnostics ./internal/framework/pipeline ./internal/cli`. -Add a group-cap successor ADR/narrow status links for ADR-0015/0024; update -architecture/pipeline/operator claims. No new durable reporting protocol. - -## Stage 15 — Separate Working State From Logical RunOutput - -**Completed.** Private run/lane state now owns normalized artifacts, reuse -eligibility, and pending diagnostic groups. Public results contain only final -diagnostics, logical output files, and fallback count. Existing focused tests -inspect private state where necessary; integration and CLI use the public result. -The prescribed suites and pipeline race checks pass. Completed-work diagnostic -retention, finalization failures, and earlier intermediate release remain for -their explicitly scheduled follow-up work. - -**Coverage:** CAT-006 structure; CAT-009/CAT-022 foundation. -**Prerequisites:** Stages 12–14. - -Move normalized bytes, reuse maps, and diagnostic accumulators from RunOutput -into private run/lane state. Update step, typed continuation, handoff, completion, -and output helpers. Retain necessary copies/domain construction; no new operation -API migration. - -**Acceptance:** Returned results retain no private accumulators. Preserve artifacts, -eligibility, fallback count, and owned final diagnostics. Record any deferred -failure-path repairs for following stages. - -**Check:** `go test ./internal/framework/pipeline ./internal/modules/integration ./internal/cli` -where buildable. Update internal terminology, not public contracts. - -## Stage 16 — Preserve Completed Diagnostics Independently Of Lanes - -**Completed.** The coordinator retains completed extraction groups independently -of lane eligibility and assembles them in lane/chunk order after draining work. -Available diagnostics from failed operations and completed merge/normalize work -are preserved without duplicate extraction publication. Regressions cover -same-lane failure, sparse reverse completion, cancellation, and normalize failure; -the focused and pipeline race checks pass. Finalization failures remain for the -following stage. - -**Coverage:** CAT-008. **Prerequisites:** Stages 10, 15. - -Retain operation groups separately from extraction values/completion eligibility. -After drain, assemble canonical order for sparse/out-of-order results. Remove -continuation's duplicate extraction-group publication. Preserve available groups -accompanying errors and completed merge/normalize work. - -**Acceptance:** One-worker successful warned chunk then same-lane failure retains -the warning without artifact/handoff. Controlled reverse/sparse completion counts -once in canonical order. Cover merge success then normalize failure, and drained -completed work on cancellation. Preserve canonical error selection. - -**Check:** `go test ./internal/framework/pipeline -run 'Diagnostic|Concurrent|Cancellation|OrderedStep|Handoff'`; -`go test -race ./internal/framework/pipeline`. Update diagnostics flow docs. - -## Stage 17 — Finalize Once, Retaining Primary And Finalization Causes - -**Completed.** One diagnostic finalization boundary retains the valid prefix and -joins aggregation errors with execution, cancellation, and capture causes. A -failed success-path aggregation prevents output encoding; work-only diagnostic -groups are retired. Genuine occurrence-overflow regressions and the specified -diagnostics, pipeline, and CLI checks pass. Runner decomposition follows later. - -**Coverage:** CAT-009 correctness; CAT-022 foundation. -**Prerequisites:** Stages 14–16. - -Replace failOutput's ignored aggregation and repeated passes with one runner -finalization boundary. Snapshot successfully aggregated groups on failure, join -causes, and retire work-only state. Use ordinary named returns/explicit finalization, -not another lifecycle framework. - -**Acceptance:** A genuine invalid-group or occurrence-overflow failure following -valid groups preserves the prefix and distinct execution cause. Success-path -aggregation failure also fails once, without success encoding. Caller cancellation -stays terminal; capture causes survive. Empty/parse-failure/success/fallback paths -retain established behavior. - -**Check:** `go test ./internal/framework/diagnostics ./internal/framework/pipeline ./internal/cli`. -Update finalization docs; errors convey incompleteness without new report fields. - -## Stage 18 — Release Intermediates After Their Last Consumer - -**Completed.** Ordered assembly releases reorder maps; the coordinator releases -extraction values when each continuation returns and drops undeliverable values -after failure drains. Diagnostics survive independently and normalized artifacts -remain through handoff, evidence, and encoding. A controlled blocked-sibling -test checks owner references and output retention; pipeline, integration, and -pipeline race suites pass. - -**Coverage:** CAT-006 completion. **Prerequisites:** Stages 15–17. - -Release reorder maps after successful ordered extraction assembly and extraction -values/artifacts after continuation. On failure, preserve diagnostics before dropping -undeliverable values after drain. Keep normalized bytes through output/handoff/ -evidence consumption. Clear owner references, not shared backing storage. - -**Acceptance:** Trace fast lanes while siblings block, failure/cancellation, -handoff, and encoding. Use controlled sibling plus narrow same-package state -checks if needed; no GC timing, finalizers, or heap thresholds. No diagnostic -loss, shared mutation, or premature retirement. - -**Check:** `go test ./internal/framework/pipeline ./internal/modules/integration`; -`go test -race ./internal/framework/pipeline`. Comment non-obvious last consumers. - -## Stage 19 — Expose Cohesive Runner Phases - -**Completed.** The runner now delegates source parsing/indexing, chunk planning -and map creation, and logical output/evidence encoding to private collaborators; -ordered steps, cancellation, and single finalization remain explicit. Existing -pipeline, integration, CLI, full test, vet, and build checks pass. Physical -publication remains CLI-owned. - -**Coverage:** CAT-022 completion. **Prerequisites:** Stages 12–18. - -Extract same-package source parse/validate, chunk/materialization/map, and logical -output/evidence/encoding phases. Keep ordered steps/cancellation/single finalizer -readable in Runner.Run. No generic dispatcher or core physical publication. - -**Acceptance:** Control flow reveals order and failure boundaries, not large -inline evidence maps. Preserve source/index lifetime, capture, fallback eligibility, -auxiliary output, output ownership, and completed diagnostics. - -**Check:** `go test ./internal/framework/pipeline ./internal/modules/integration ./internal/cli`; -full tests/vet/build at this milestone. Update pipeline/state internals. - -## Stage 20 — Give CLI Invocation A Private Lifecycle Owner - -**Completed.** The native declaration creates a private invocation owner for -configuration, execution, publication, capture finalization, and reporting; -mutable lifecycle state is no longer captured by the declaration. Regressions -cover combined causes and publication locations. CLI and integration suites and -affected CLI race tests pass; existing delivery and allocation coverage remains. - -**Coverage:** CAT-023. **Prerequisites:** Stages 13, 17–19. - -Reduce pipelineRunCommand in internal/cli/pipeline_run.go to native declaration -plus private invocation/finalization owner. Remove declaration-captured mutable -state; reuse capture/publication/reference/report helpers. - -**Acceptance:** Preserve one config/engine, supplied-value semantics, allocation -before preparation, independent invocations, and causes. Distinguish execution, -publication, capture finalization, and delivery. Retain published artifacts/ -locations after reporting failure; no model reruns or new command interface. - -**Check:** `go test ./internal/cli ./internal/modules/integration`; affected CLI -race tests. Update CLI/state internals, not CommandKit-owned syntax. - -## Stage 21 — Connect Executable Signals To Cancellation - -**Completed.** The executable routes the first SIGINT/SIGTERM into the existing -context and restores ordinary handling for a subsequent signal, joining its -signal helper before exit. Offline subprocess tests exercise in-flight provider -cancellation, terminal evidence, no fallback/retry, and a held-delivery second -signal. Repeated process tests and the prescribed executable/CLI checks pass. -No shutdown deadline or embedded process-wide handler was added. - -**Coverage:** CAT-010. **Prerequisites:** Stages 10, 17, 20. - -Pass a SIGINT/SIGTERM-cancelled context from cmd/notarius/main.go to app.Execute. -A small standard-library adapter restores ordinary handling promptly after the -first signal so another can terminate cleanup. Stop/join helpers before os.Exit, -e.g. return status from a small run function. No embedded process-wide handlers. - -**Acceptance:** Offline subprocess tests with local fake backend wait for a started -request before signaling. Verify request cancellation, non-success, no fallback/ -retry, started-work drain, and available terminal evidence. Hold cleanup to test -subsequent-signal termination without a complete-bundle guarantee. Bound waits/reap -children. Embedded contexts remain caller-owned. No new shutdown timeout/SIGKILL -promise or cooperation guarantee for collaborators ignoring cancellation. - -**Check:** `go test ./cmd/notarius ./internal/cli`; repeat affected process tests. -Update CLI/operations/subprocess guidance. - -## Stage 22 — Centralize Pure Pipeline Copies - -**Completed.** Pipeline-owned pure profile and binding copies are shared with -configuration; explicit decoding/resolution owns name trimming. Supported -option containers, nested references, validators, control pointers, whitespace, -and nil/empty values have mutation and preservation coverage, including effective -configuration isolation. Config, pipeline, and CLI checks pass. - -**Coverage:** CAT-017. **Prerequisites:** Stage 3 where files overlap. - -Inventory copy switches in config/config.go, pipeline/profile.go, and -validator_chain_registry.go. Implement selected pure pipeline copies; reuse at -config/framework boundaries. Move trimming explicitly into normalization. Remove -only copies proven redundant by ownership. - -**Acceptance:** Independent mutation tests cover step/lane/reference maps, -bindings/validator overrides, maps/lists/string/byte/RawMessage options, control -pointers, omission/empty/zero. Pure copies preserve untrimmed values; original/ -effective config stays detached. No reflective/JSON option copier, new restriction, -or universal immutability policy. - -**Check:** `go test ./internal/core/config ./internal/framework/pipeline ./internal/cli`. -Update configuration/pipeline ownership documentation/comments. - -## Stage 23 — Centralize Catalog-Independent Layout - -**Completed.** Configuration validation and complete resolution share a detached -catalog-independent layout for normalized identities, step ordering, and sorted -lanes. Missing profile IDs use the validated config map key without mutation; -empty composable steps remain accepted by config and rejected by resolution. -Independent shape/reference/ownership tests and the specified package checks pass. -Module and reference-slot selection remains for the following stages. - -**Coverage:** CAT-014 structure. **Prerequisites:** Stage 22. - -Implement LayoutPipeline, reusing it in config structural validation and complete -resolution. Preserve default flat step, explicit order, sorted lanes, identity -trimming/uniqueness, and current empty/mixed rules. Keep ConfigKit origin/presence, -map-key matching, and binding-source checks at their owner. - -For configuration maps whose profile ID is omitted, pass the already validated -map key as layout identity on a detached value; do not require a new `id` field -or mutate the ConfigKit result. - -**Acceptance:** Independent layouts cover flat/explicit, duplicates, empty/mixed -shapes, and references. Config validation needs no catalog; original settings stay -untouched. No second structural interpreter in resolution. - -**Check:** `go test ./internal/core/config ./internal/framework/pipeline`. -Update config/pipeline phase documentation. - -## Stage 24 — Centralize Module And Reference-Slot Selection - -**Completed.** A shared target inventory selects chunk and lane bindings, -artifact-kind variants, and declared slots without requiring reference values or -constructing modules. Resolution consumes the selected specs and preserves -configured-lane eligibility for reference defaults. Tests cover kind variants, -defaults, subsets, missing selections, explicit restrictions, and unselected -default targets; pipeline and preflight suites pass. CLI adoption follows next. - -**Coverage:** CAT-014 selection. **Prerequisites:** Stage 23. - -Implement target inventory with existing spec lookups, selecting defaults/kind -variants once and exposing configured lanes for final option checks. Resolution -consumes selections, not another independent interpreter. - -**Acceptance:** Inventory works before required references are populated; no files, -engine, or config load. Test kind-specific variants, controlled defaults, flat -subsets, and explicit restrictions. Preserve unknown selected-module errors, -unselected-lane behavior, and reference-default eligibility. Selection is not full -resolution. - -**Check:** `go test ./internal/framework/pipeline ./internal/preflight`. -Document the phase boundary, not a partial resolver. - -## Stage 25 — Reuse Inventory In CLI Reference Binding - -**Completed.** CLI selector expansion uses the shared layout and selected target -inventory; grammar, precedence, conflicts, unbinds, and binding remain CLI-owned. -A regression supplies required references only through CLI selectors, alongside -existing variant, generated-handoff, and invalid-before-read coverage. The -specified CLI, config, pipeline, and preflight suites pass. - -**Coverage:** CAT-014 completion; CAT-018 callers. **Prerequisites:** Stages 23–24. - -Replace reference_selectors.go's target/default/spec interpreter with inventory; -remove unused selection helpers. CLI keeps grammar, specificity/conflicts, -overrides/unbinds, and precedence. Discover slots, bind, then check completeness. - -**Acceptance:** Independent config/resolver/CLI expectations retain CLI-only -required references, pipeline/stage/lane precedence, ambiguity/unbind/generated -protection, and invalid-selector-before-read behavior. No syntax change, premature -full resolution, or allow-missing mode. - -**Check:** `go test ./internal/cli ./internal/core/config ./internal/framework/pipeline ./internal/preflight`. -Update links to shared owners in CLI/config/pipeline internals. - -## Stage 26 — Decompose Complete Resolution - -**Completed.** Value/wire handling, effective bindings, reference normalization -and overlays, and generated-dependency checks have cohesive same-package owners. -Generated bindings are checked individually through structured producer keys; -the shared layout, selection, and copies remain the composition inputs. Focused -composition and reference tests, full tests, vet, and build pass. - -**Coverage:** CAT-018 completion. **Prerequisites:** Stages 3, 22–25. - -Split cohesive value/wire, copy, reference, generated-dependency, and effective -selection responsibilities within pipeline. Extract per-binding checks from -nested loops with structured producer keys/useful scope. Separate source -normalization from overlays/precedence. File splitting alone is not completion. - -**Acceptance:** Full binding, exact types/codecs, capabilities, validator order, -generated restrictions, option checks, and digest semantics remain. All callers -reuse shared layout/selection/copies. No new config model/reloader, generalized -interpreter, or broad package migration. - -**Check:** `go test ./internal/framework/pipeline ./internal/core/config ./internal/cli ./internal/preflight`; -full tests/vet/build at this milestone. Update internal flow docs. - -## Stage 27 — Move Scene Checks To Their Family - -**Completed.** Family-owned checks return field facts for scene normalization -and sibling validators; the selectable adapter retains extraction cardinality -and corrective guidance. The codec shares only the common kind predicate and -keeps its distinct whitespace/range acceptance. Literal fact and codec tests and -the specified family, normalizer, codec, and validator suites pass. - -**Coverage:** CAT-020. **Prerequisites:** preceding stage order. - -Extract pure reusable scene checks from shape adapter; migrate normalizer/sibling -validators. Compare codec acceptance before sharing primitives. Adapter retains -exactly-one extraction checks, classification, and guidance. - -**Acceptance:** Literal nil/empty/kind/blank/untrimmed/source-ref/cardinality cases -protect actual owners. Codec/selectable differences remain; optional checks do -not become mandatory. Normalization builds no unused guidance and imports no -selectable validator adapter. - -**Check:** `go test ./internal/modules/dnd/scenedescriptions/... ./internal/modules/dnd/codec/scenedescriptions ./internal/modules/dnd/normalize/scenedescriptions ./internal/modules/dnd/validate/scenedescriptions/...`. -Update D&D family guidance. - -## Stage 28 — Share NPC And Location Duplicate Bookkeeping - -**Completed.** Shared grouping returns retained positions and duplicate groups -in representative order; NPC and location families retain eligibility, identity, -cloning, and original-index diagnostics. Independent tests cover interleaving, -invalid references, distinct evidence, permutations, and ownership. The shared -and both normalizer suites pass. Combat and spell review follow next. - -**Coverage:** CAT-021 first callers. **Prerequisites:** preceding stage order. - -Implement selected grouping helper and migrate NPC/location occurrences. Families -keep ref eligibility, exact identity, cloning, original-index mapping, diagnostics, -and nil/empty. Track representatives in encounter order; emit only duplicate groups. - -**Acceptance:** Independent outputs cover interleaved groups, invalid refs retained -independently, distinct evidence, and permutations. Preserve retained/removed -original indices/ownership. Helper tests protect behavior, not its map/keep mask. - -**Check:** `go test ./internal/modules/dnd/shared ./internal/modules/dnd/normalize/npcoccurrences ./internal/modules/dnd/normalize/locationoccurrences`. -Comment family-owned eligibility/mapping. - -## Stage 29 — Reuse Grouping For Combat And Review Spells - -**Completed.** Combat and spell duplicate grouping use the shared bookkeeping -with family-owned keys and eligibility. Spell empty/no-change cases retain the -original list; item occurrences deliberately keep bucket-plus-exact equality. -Combat evidence/index ownership and spell no-change storage have regressions; -the specified combat, spell, and item normalizer suites pass. - -**Coverage:** CAT-021 completion. **Prerequisites:** Stage 28. - -Migrate combat turns without identity/eligibility changes. Migrate spells only if -nil/allocation behavior remains cleanly local; otherwise record the concrete reason -to retain its implementation. Leave item bucket-plus-exact-equality separate. - -**Acceptance:** Combat/optional spell output, order, original-index diagnostics, -invalid evidence, and cloning match independent expectations. No flattened domain -rules/evidence merging. Record the conditional spell and deliberate item dispositions. - -**Check:** `go test ./internal/modules/dnd/normalize/combatturns ./internal/modules/dnd/normalize/spells ./internal/modules/dnd/normalize/itemoccurrences`. -Update relevant D&D internals/catalog. - -## Stage 30 — Prepare NPC And Location Sort Keys Once - -**Completed.** NPC and location normalization prepare earliest valid positions -once per owned record; location kind ranks are also prepared once. Defensive -comparators remain, and evidence ties retain their established comparison. Literal -long-tie, non-monotonic, invalid-reference, duplicate and existing permutation -coverage passes with the specified normalizer and validator suites. Item and -enemy sorting follow next. - -**Coverage:** CAT-019 first families. **Prerequisites:** Stages 28–29. - -Decorate owned records with earliest valid position/invariant scalars before sort, -following combat. Keep defensive comparators; no generic sorting framework. - -**Acceptance:** Literal ties/long/disjoint/invalid refs/non-monotonic IDs/duplicates/ -permutation cases retain stable order and original-index diagnostics. Inspection -proves invariant rescans removed; genuine evidence tie comparisons can stay linear. - -**Check:** `go test ./internal/modules/dnd/npcoccurrences ./internal/modules/dnd/normalize/npcoccurrences ./internal/modules/dnd/normalize/locationoccurrences ./internal/modules/dnd/validate/npcoccurrences/... ./internal/modules/dnd/validate/locationoccurrences/...`. -Comment canonical fast-path premises. - -## Stage 31 — Prepare Item And Enemy Sort Keys Once - -**Completed.** Item and enemy-event normalizers prepare chronology and scalar -comparison keys once per owned canonical record. Enemy invariant checks use the -canonical path only for evidence that passed order/uniqueness checks; defensive -comparators and item exact-equality buckets remain. Literal tie, invalid evidence, -identity/dedup, and existing nil/empty and kind-order tests pass with the -specified family, normalizer, and validator suites. - -**Coverage:** CAT-019 completion. **Prerequisites:** Stage 30. - -Apply local key preparation to item/enemy records. Remove enemy recanonicalization -only on proven canonical paths, including invariant checks after canonical-order -validation. Keep defensive comparison and existing item canonical/bucket equality. - -**Acceptance:** Equal scalar keys/distinct evidence, invalid refs, nil/empty, -kind/name order, identity, and dedup retain behavior. No call-count test or claim -of universally constant-time comparisons. - -**Check:** `go test ./internal/modules/dnd/itemoccurrences ./internal/modules/dnd/enemyevents ./internal/modules/dnd/normalize/itemoccurrences ./internal/modules/dnd/normalize/enemyevents ./internal/modules/dnd/validate/itemoccurrences/... ./internal/modules/dnd/validate/enemyevents/...`. -Update relevant canonical-input explanations. - -## Stage 32 — Replace Prompt-Prose Change Detectors - -**Completed.** - -**Coverage:** CAT-026. **Prerequisites:** prior operation/capture work settled. - -Inspect asset registry/scene/combat/package/composition, reconciliation, and spell -prompt tests listed by TEST-005. Remove authored-English and production message -markers. Use supplied transcript/reference/guidance sentinels, native role/schema -contracts, and declarations for binding/order. Compare a loaded shared asset rather -than copied prose/hash if needed; consolidate genuinely duplicate checks. - -**Acceptance:** Keep automatic preparation/discovery, required-schema compatibility, -enums/opaque-ID exclusions, selected public defaults, cache hints, and follow-up -routing without source regeneration. Keep distinct module tests. No snapshots, -prefix-length/live-quality gates, or production prompt rewrite. - -**Check:** `go test ./assets ./internal/framework/semanticreconcile ./internal/modules/dnd/extract/...`. - -## Stage 33 — Separate Example Tests And Unfreeze Run-ID Format - -**Completed.** - -**Coverage:** CAT-028/CAT-029. **Prerequisites:** Stages 20, 25–26. - -Refactor cli/example_contract_test.go into independent resolved fixtures and focused -load/composition/inheritance/list tests. Load parent directly, not via mutable -previous-iteration state. Remove private timestamp/hex-width regex from run_id_test.go; -do not change the production algorithm. - -**Acceptance:** Configs/input still load/parse/resolve/list; parent comparison is -order-independent. Retain generated-reference coverage, run uniqueness/path safety/ -collision/allocation/partial-write checks, and the exact versioned session-ID vector. -No assertion DSL or new defaults. - -**Check:** `go test ./internal/cli -run 'Example|RunID|Session|Allocat|Partial' -count=5`; -`go test ./internal/core/config ./internal/cli`. - -## Stage 34 — Document Actual Extension Sharing And Lifetimes - -**Completed.** - -**Coverage:** CAT-025. **Prerequisites:** final preceding interfaces. - -Update stage/preparation/codec/validator/EvidenceWriter comments and module/LLM/ -pipeline/state internals. Prepared extractors/extraction validators/codecs can -overlap; describe each stage's actual pattern, not universal concurrency. Source/ -index are read-only; mutable operation state is local. - -**Acceptance:** Explain callback/writer/borrowed/background ownership. Runner joins -dispatched operations, not arbitrary extension goroutines. Concurrent custom writers -support concurrent calls; point to the synchronized recorder without a new wrapper. -Link pinned upstream client/observer contracts, not stronger local guarantees. -Verify the generic authoring example against final APIs. No blanket locking or -per-job module construction. Earlier stages update their own comments alongside code. - -**Check:** `go test ./internal/framework/contracts ./internal/framework/pipeline ./internal/modules/integration`; -relevant race checks and manual call-site comparison. - -## Stage 35 — Remove Confirmed Dead Metadata And Helpers - -**Completed.** - -**Coverage:** CAT-030/CAT-031. **Prerequisites:** preceding moves complete. - -Recheck audit/12-deadcode.md against callers. Delete unused validator policy, -registry correctionPolicy, scene normalizerPolicy labels; config cloneStringMap; -pipeline laneReferencesReuseEligible and sortValidatorSpecs where still unused. -Clean unused imports only. Keep live spell helper, scoped eligibility, durable -identity bytes, keys, reasons, schemas, and guidance. - -Review all six internal exported NormalizationPolicy aliases: remove those without -supported use, defer uncertain ones with specific reasons. Capitalization alone -does not warrant a compatibility initiative. - -**Acceptance:** Record declaration/alias outcomes; historical counts are not quotas. -Behavior/IDs/cache identity stay unchanged. No count/absence test or revived policy -fingerprint to justify obsolete declarations. - -**Check:** `go test ./internal/core/config ./internal/framework/pipeline ./internal/modules/dnd/...`; -`go vet ./...`. Record disposition in catalog, not runtime docs. - -## Stage 36 — Verify Full Target And Documentation - -**Completed.** The coverage catalog and canonical documentation were reviewed; -all required findings are resolved, the selected prior resolutions remain closed, -and CAT-033 remains deferred. Final offline verification passed: `go test ./...`, -`go vet ./...`, `go build ./cmd/notarius`, the specified race suite, and -`git diff --check`. Changed documentation's relative link targets were checked. - -**Coverage:** all required scope. **Prerequisites:** Stages 1–35. - -Match every coverage row below to production paths, regressions, and canonical -docs. Finish deferred caller/build/test repairs. Check tests/docs have not -strengthened inputs, permissions, acceptance, or guarantees. Green happy paths or -smaller files alone are insufficient. - -**Check:** Run final checks; reuse unchanged successful checks where valid: - -```sh -go test ./... -go vet ./... -go build ./cmd/notarius -go test -race ./internal/framework/pipeline ./internal/framework/capture ./internal/framework/semanticreconcile ./internal/modules/dnd/shared ./internal/modules/dnd/validate/scenedescriptions/combat_semantics -git diff --check -``` - -Repeat affected process/concurrency checks after final edits. Default verification -is offline, with fake external boundaries and no credentials/paid inference. -Inspect changed Markdown links/code symbols. No new benchmark/complexity/coverage/ -production-run gate; claim measured speedups only when actually measured. - -**Acceptance:** Required findings have evidence and sufficient verification; -partial work is not resolved. Record permitted spell/alias dispositions. Keep -CAT-007/015/016/034 closed and CAT-033 deferred. Code/docs/catalog agree. Do not -incidentally delete/archive completed roadmaps. - -## Coverage And Documentation Checklist - -| Findings | Completion stages | -| --- | --- | -| CAT-001, CAT-011 | 1 | -| CAT-002 | 2 | -| CAT-012 | 3, preserved in 26 | -| CAT-013 | 4 | -| CAT-004 | 5 | -| CAT-005 | 6–9 | -| CAT-027 | 10 | -| CAT-032 | 11 | -| CAT-003 | 12, preserved in 13/19 | -| CAT-024 | 13 | -| CAT-009 | 14 and 17 | -| CAT-006 | 15 and 18 | -| CAT-008 | 16 | -| CAT-022 | 17 and 19 | -| CAT-023 | 20 | -| CAT-010 | 21 | -| CAT-017 | 22 | -| CAT-014 | 23–25 | -| CAT-018 | 26 | -| CAT-020 | 27 | -| CAT-021 | 28–29 | -| CAT-019 | 30–31 | -| CAT-026 | 32 | -| CAT-028, CAT-029 | 33 | -| CAT-025 | 34 and comments alongside earlier changes | -| CAT-030, CAT-031 | 35, including conditional alias review | -| All required scope | 36 | - -Reconcile these canonical owners as their behavior lands: - -- `docs/internal/overview.md`: actual capture/family package inventory. -- `docs/internal/pipeline.md`: shared layout/selection/resolution, working state, - diagnostics/finalization, source index, phases, and release boundaries. -- `docs/internal/configuration.md` and `docs/internal/cli.md`: shared copying/ - selection versus kit loading/CLI grammar and invocation lifecycle. -- `docs/internal/modules.md`, `docs/internal/dnd.md`, interface comments, and the - existing generic authoring example: actual borrowing/concurrency and mechanics. -- `docs/internal/llm.md`, `docs/internal/state.md`, `docs/operations.md`: capture - owner/source sharing/required failures/signals and removed cap/truncation claims. -- `docs/consumers/subprocess.md` and relevant CLI text: cooperative first signal, - subsequent termination, no deadline guarantee. -- Architecture policy and successor ADRs/status links: group-cap removal and source - sharing. Preserve accepted ADR bodies; select next unused numbers at each change. - -Keep public configuration, artifact contracts, examples, kit versions, release -procedure, and upstream-owned feature documentation unchanged unless a selected -change demonstrably affects current text. Link canonical owners instead of repeating -volatile definitions. - -## Open Questions - -None. Policy/scope is accepted; the plan selects remaining boundaries. Spell reuse -and alias cleanup have explicit conditional dispositions. Report newly discovered -conflicts instead of silently changing scope or acceptance. diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md deleted file mode 100644 index 16e3061b..00000000 --- a/docs/roadmap/remediation.md +++ /dev/null @@ -1,373 +0,0 @@ -# Audit Remediation Review - -## Scope And Result - -Reviewed all 36 stages of [the implementation plan](implementation.md) against -`c5d8697d9f645a7b3b9041769da02704bd495b7a`, including the changes since planning -commit `cecd68f`, their tests, the accepted -[feature roadmap](audit-remediation.md), and current canonical -architecture/internal documentation. The review below records that snapshot; -the remediation status records the subsequent correction. - -The targeted architecture is substantially in place. Core retains typed operation -execution; a separate capture package serves operations and one-shot validators. -The runner shares a whole-source index, separates working state from logical -results, retains completed diagnostics independently of lane eligibility, and -finalizes diagnostics once. Configuration, CLI, and resolution reuse pipeline-owned -layout, target selection, and pure copying. Families own scene rules, duplicate -eligibility/identity, and prepared ordering keys. The executable owns cooperative -signals; embedded callers retain context ownership. - -The one required failure-cause retention gap is now resolved. No other required -correctness, code-quality, architectural/documentation gap, or inadvertently -strengthened requirement was substantiated in the inspected changes. The previously -resolved standalone native-executor cancellation finding remains fixed; the issue -below is at the enclosing runner's error-selection boundary. - -## Finding 1 — Retain Drained Capture Failures Alongside Caller Cancellation - -**Status:** Resolved. The runner now joins caller cancellation with capture-bearing -errors from drained jobs, preserving their scope and typed causes in canonical -stage/lane/chunk order. Unrelated sibling errors remain suppressed, and ordinary -uncanceled error selection is unchanged. - -**Priority:** P2, error integrity; requires concurrent cancellation and a capture -failure, not an ordinary successful run. - -**Affected plan scope:** Stage 17's primary/capture/finalization cause retention, -with Stage 21's cancellation path. The aggregation finalizer itself works; the -loss occurs before that boundary receives the operation error. - -**Location:** [selectRunError](../../internal/framework/pipeline/runner_concurrent.go), -lines 402–405 at the reviewed revision; also inspect the extraction outcome -capture defer in the same file and the analogous continuation completion path. - -### Behavior And Evidence - -After started work drains, `selectRunError` immediately returns `parent.Err()` -when the caller context is canceled. This discards the recorded job errors, -including a `contracts.CaptureError` joined by operation outcome recording. -The runner's finalizer can preserve the error it receives, but cannot recover a -cause already removed by selection. - -A temporary offline Go test overlay exercised the real `Runner.Run` boundary: - -1. Prepare the existing small concurrent-pipeline fixture, use one worker, and - supply a cancelable caller context plus an explicit evidence writer. -2. When the writer receives an extraction operation's `outcome.json`, cancel - that caller context and return a distinct sentinel capture error. -3. Assert that the returned error retains `context.Canceled`, the capture - sentinel, and the typed `contracts.CaptureError`. - -The writer reached the boundary once. The diagnostic failed with: - -```text -capture cause present=false, want=true: execute pipeline step "default": context canceled (capture writes=1) -``` - -The expanded diagnostic repeated this at extraction, merge, and normalization -outcome recording. All three combined-failure cases failed; cancellation-only -and capture-only controls passed for each stage (six passing controls). -Cancellation remains observable, but `errors.Is(err, captureCause)` and -`errors.As(err, &captureError)` fail in the combined cases. No timing-dependent -sleep or provider call is needed. The diagnostic exists only in a temporary -overlay, not a committed production or test change. - -The selection branch predates this work set; this is an incomplete end-state -requirement, not a newly introduced regression. Existing tests cover capture -failure and caller cancellation separately, and cancellation plus aggregation -failure, but do not cover capture failure in a drained job alongside caller -cancellation. - -This finding does not establish successful publication after cancellation, loss -of available files, or that the standard CLI recorder forgets its own retained -write error. The confirmed issue is loss from the runner's returned error chain, -particularly relevant to explicit writer/direct framework consumers. - -### Required Remediation - -- Preserve caller cancellation as the primary terminal classification, while - retaining required capture-failure causes from drained operations. Joining the - relevant typed capture failures with that primary error is sufficient. -- Keep canonical operation-error selection and sibling-cancellation suppression - for ordinary execution errors. Do not indiscriminately expose every sibling - error, add a ledger/schema, change retry/fallback behavior, or introduce shutdown - deadlines. Required capture failures are not just harmless sibling cancellation. -- Add a focused permanent runner regression at the controlled writer boundary - above. Assert cancellation and capture cause/type, no deliverable files or - successful completion, and normal drain. Exercise extraction and continuation - capture boundaries using a small table. Retain the existing core cancellation, - aggregation-prefix, native-local timeout, and capture-error tests. - -**Acceptance:** `Runner.Run` preserves both cancellation and the supplied capture -cause/type after started work drains, without acceptance/fallback or another model -call. Ordinary cancellation still returns cancellation; uncanceled failures retain -their established canonical selection. Available diagnostics and capture remain -under the existing lifecycle. - -### Implemented Remediation - -`selectRunError` retains drained job errors containing `contracts.CaptureError` -when caller cancellation takes precedence. It returns the caller context error -first in the joined chain, keeping every capture cause from those jobs without -changing retry, fallback, finalization, or publication behavior. - -Permanent runner regressions cancel the caller and fail outcome capture at each -of extraction, merge, and normalization. They verify cancellation, capture cause -and type, one outcome write, no deliverables, and no fallback. Selection coverage -also checks multiple capture failures, canonical ordering, and suppression of an -unrelated ordinary sibling failure. - -Post-remediation checks passed: the focused cancellation/capture/finalization -and error-selection tests (ten consecutive runs), `go test ./...`, `go vet ./...`, -`go build ./cmd/notarius`, and the five-package race command below. - -## Stage-By-Stage Review Coverage - -| Stages | Evidence inspected / result | -| --- | --- | -| 1–4 | Safe chunk/window arithmetic, exact rational negativity, structured producer keys, slice-view cycle tracking, and boundary regressions are present. | -| 5–9 | Citation union traversal and all ten extraction index paths match the target; run/step sharing, standalone fallback, same-ID changed layouts, grounding, scene reuse, and cache checks have focused coverage. | -| 10 | Worker tests use controlled overlap, bounded cancellation-safe handshakes, and joining; repeated focused checks pass. | -| 11–13 | Native capture is a reusable framework owner; disabled projections are guarded; shared source and operation records reach the selected sink, including explicit writers and failure/cache paths. | -| 14 | Group caps and collection truncation are removed; samples, grouping, checked counts, and selected diagnostic classification remain. Successor ADR scope is narrow. | -| 15–19 | Private working state, completed diagnostics, one aggregation pass/prefix retention, last-consumer release, and runner phases are present. Finding 1 qualifies composed cancellation/capture error retention. | -| 20–21 | Invocation-local CLI state and executable signal handling are present. Subprocess tests exercise first-signal drain and subsequent-signal termination. Finding 1 concerns the runner error chain, not signal registration. | -| 22–26 | Pure copies preserve supported containers/absence distinctions; layout and inventory are reused by config, CLI, and complete resolution. Reference/type/capability/selection boundaries remain explicit. | -| 27–31 | Scene facts have family ownership with codec differences preserved; grouping is shared across selected families, including spells, with item equality kept separate; prepared sort keys retain family ordering premises. | -| 32–35 | Prose-based assertions and private run-ID regex are removed, useful prompt/session contracts remain, example tests are independent, concurrency/lifetimes are documented, and dead declarations/alias dispositions are recorded. | -| 36 | Canonical docs and narrow ADR status updates reflect the changes. Broad checks pass, but the completion claim needs the composed failure-path correction in Finding 1. CAT-033 remains deliberately deferred. | - -## Validation - -Passed on the reviewed state: - -```sh -go test ./... -go vet ./... -go build ./cmd/notarius -go test -race ./internal/framework/pipeline ./internal/framework/capture ./internal/framework/semanticreconcile ./internal/modules/dnd/shared ./internal/modules/dnd/validate/scenedescriptions/combat_semantics -go test ./internal/framework/pipeline -run 'Concurrent|Concurrency|ReverseCompletion|ReadyJobs|Cancellation|RetainsDiagnostic|Finalization' -count=10 -go test ./internal/cli -run '^TestExecutableSignalsCancelAndDrainProviderWork$' -count=3 -git diff --check -``` - -Go reused cached results where applicable; the repeated checks ran afresh. The -additional cancellation/capture overlay failed as described. No API credentials, -production inference, application fixes, or permanent test edits were used. -Local link checks found no missing targets among 199 distinct paths referenced -by the 15 changed canonical documentation files inspected. - -## Algorithmic Follow-Up Audit - -Reviewed the 36 stages of [implementation.md](implementation.md) at -`5ffe22f5ac9dfb096f80670645e54f547b9ffec9` on 2026-11-26. The earlier cancellation/ -capture finding above is resolved. This additional review identifies three -efficiency opportunities for consideration, not three newly introduced bugs or -three failures to implement the accepted plan. No further functional correctness -defect was confirmed. - -The fixed typed pipeline remains coherent. Core owns operation execution, -assessment, reuse, and ready-job coordination; capture has a shared owner; -families own semantic rules, evidence identity, and canonical ordering. One run -index serves extraction and cache decoding. Completed diagnostics survive lane -failure and aggregate once, while obsolete extraction intermediates are released. -The CLI owns invocation, publication, and reporting; the executable owns signals. - -This pass inspected production paths and relevant tests in stage order, using -graph discovery and current source. It excludes reconsideration of selected -algorithms: sorted/coalesced citation intervals, bounded lazy scheduling, complete -assessment, detached validator inputs, stable domain ordering, genuine evidence -tie comparisons, item duplicate buckets with exact equality, native conversation -capture, and accepted-result caching. CAT-033's deferred token matcher stays -deferred. Required data copies and emitted overlapping chunk content are not -treated as defects merely because they cost time or space. - -### ALG-001 — Validators Still Rebuild The Whole-Source Index - -**Status:** Completed. Validator requests now borrow the run-owned index across -chunking, extraction, merge, and normalization. All D&D citation/reference and -applicable invariant/semantic checks reuse it through shared optional-index -helpers; standalone calls still build locally. Detached validator views remain -isolated. Tests cover shared identity across jobs/steps/request forms, concurrent -readers, same-ID changed layouts, omitted indexes, and mutation isolation. -Full tests, vet, build, the pipeline/shared/all-D&D-validator race suite, and -three repeated focused race runs passed. Internal ownership guidance is updated. - -**Priority:** Medium efficiency opportunity; adjacent follow-up to Stages 5–9, -not a regression or reopening of their completed extraction/cache scope. - -**Evidence:** [NewDocumentIndex](../../internal/core/source/validation.go#L17) -allocates and fills a map over every source unit. Although extraction now borrows -the runner's index, [TypedValidationRequest](../../internal/framework/contracts/typed_pipeline.go#L59) -has no corresponding borrowed index. Validators construct it again for each -assessment, for example [spell citations](../../internal/modules/dnd/validate/spells/source_refs/validator.go#L38), -[NPC citations](../../internal/modules/dnd/validate/npcregistry/source_refs/validator.go#L39), -and [scene citations](../../internal/modules/dnd/validate/scenedescriptions/source_refs/validator.go#L40). -All ten source-relatedness adapters also construct a -[CitationResolver](../../internal/modules/dnd/shared/citations.go#L19), whose -constructor builds another whole-source index. These validators appear in the -[production chains](../../internal/modules/dnd/register/chains.go). - -**Complexity:** Let `D` be source units and `A` the total applicable validator -invocations across delivered candidates. Index construction alone still costs -`Theta(A * D)` time and cumulative map allocation. With fixed-size chunks, -fixed lane/validator counts, no cache hits, and one candidate per job, -`A = Theta(D)`, making this indexing component quadratic in transcript length. -Concurrent assessments can also hold multiple equivalent `O(D)` maps. - -**Potential refactoring:** Carry the existing run-owned immutable index through -the validation target and typed request, with an optional-index citation resolver -constructor. Reuse it in source-reference and relatedness validators, and other -applicable validation consumers. Keep local construction when a standalone caller -omits it. This reduces the indexing component to `O(D + A)` work and one shared -`O(D)` map, excluding the actual citation checks and returned text. - -The index is valid for detached source copies with unchanged IDs/order; preserve -the selected per-validator source, artifact, reference, and metadata isolation. -In particular, [isolatedValidationTarget](../../internal/framework/pipeline/candidate_assessment.go#L132) -still intentionally clones source units per validator. That copying remains -source-scale, so sharing indexes does **not** make the whole validation pipeline -linear. This is a narrower allocation/work reduction, not permission to remove -isolation, assessment, or source checks. Add no process-global cache or mandatory -new argument for standalone callers. - -**Verification:** Retain literal valid/invalid/containment/relatedness cases; -exercise supplied and omitted indexes, concurrent readers, and separate runs -with the same source ID but changed layouts. Inspect the construction paths to -establish the cost reduction. Do not use elapsed-time or allocation ceilings as -new public contracts. - -### ALG-002 — Reference Collision Checks Compare Every Pair Of Keys - -**Status:** Completed. The predicate indexes trimmed slot/source-kind pairs and -probes for the opposite kind in expected `O(P + Q)` time, preserving mixed-kind -raw keys that trim to the same slot. Literal cases pass in both argument orders; -a temporary offline oracle matched the old predicate on all 6,561 pairs of maps -over four raw keys and absent/external/generated states. Pipeline, config, -preflight, CLI reference/example tests, package vet, and whitespace checks passed. - -**Priority:** Low; configuration-resolution cost, not per-model-call work. - -**Evidence:** [referenceSourceMapsConflict](../../internal/framework/pipeline/reference_resolution.go#L34) -scans every override key for every base key, trimming override keys repeatedly. -The resolver calls it for pipeline/step defaults and lane/extractor references. -It is unchanged logic relocated during Stage 26, not a newly introduced defect; -the plan selected responsibility separation, not this all-pairs algorithm. - -**Complexity:** For `P` base entries and `Q` override entries, a nonconflicting -case performs `P * Q` pair comparisons, including repeated string trimming. -For comparable map sizes this is quadratic even though the operation is an -exact, whitespace-normalized key lookup. Extra storage is currently constant. - -**Potential refactoring:** Index trimmed keys and their generated/external source -kind from one side, then probe from the other: expected `O(P + Q)` map work, -plus processing key bytes once, using `O(P)` or `O(Q)` temporary entries. Preserve -the existing predicate, including raw keys that trim to the same name. If the -helper continues accepting unnormalized maps, retain both observed source kinds -per trimmed key rather than overwriting one arbitrarily. Leave duplicate-name -validation and error context with their existing owners; add no new key restriction. - -**Verification:** Compare same-kind, opposite-kind, disjoint, whitespace-equivalent, -and repeated-trimmed-key cases against the current simple pairwise predicate. -Retain resolver collision and generated-binding regressions. A temporary reference -oracle is sufficient; no benchmark or framework is needed. - -### ALG-003 — Chunk Range Capacity Can Scale With Source Size For One Range - -**Status:** Completed. Range capacity now uses the first window plus quotient/ -remainder arithmetic for uncovered units, so reservation follows emitted ranges -without overflowing addition. Literal high-overlap, exact/partial remaining-step, -ordinary overlap, and maximum-integer tests pass. The temporary diagnostic now -reserves one slot for each one-range case (4 and 40 source units); no permanent -capacity assertion was added. Final repository tests, vet, build, pipeline/chunker -race tests, and whitespace checks passed with all three remediations in place. - -**Priority:** Low; avoidable space/zeroing cost for valid high-overlap settings. -Stage 1's overflow defect is fixed; this concerns the retained upper-bound capacity. - -**Evidence:** [PrepareChunk](../../internal/modules/generic/chunk/units/chunker.go#L65) -reserves `ceil(D / step)` range entries, where `step = max_units - overlap_units`, -but stops as soon as a range reaches the end. With `max_units = D` and -`overlap_units = D - 1`, it reserves `D` entries while returning one range. -A temporary offline Go overlay reproduced capacities 4 and 40 for sources of -4 and 40 units respectively; both produced exactly one range. No production -measurement or large-memory experiment was needed. - -**Complexity:** The range slice uses `Theta(D)` extra reserved storage in that -case, although its output has size one. More generally, for `C` emitted ranges, -the desired range-storage cost is `O(C)`, not an arbitrarily loose `O(D / step)` -bound. Source validation remains `O(D)` regardless; this is not an end-to-end -linear-time-to-constant-time claim. - -**Potential refactoring:** Reserve the actual range count using remaining-length -arithmetic: one when `D <= max_units`, otherwise -`1 + ceil((D - max_units) / step)`. Compute the ceiling by quotient/remainder, -not overflowing addition. Alternatively omit the optional capacity estimate and -let append grow with the actual output. Both retain the accepted option domain, -range endpoints, overlap, early exit, and Stage 1's overflow safety. - -**Verification:** Preserve literal ordinary overlap and maximum-integer option -tests; include the one-range/high-overlap case. Inspect the resulting allocation -formula rather than freezing an exact slice capacity or production allocation -ceiling in permanent tests. The temporary capacity diagnostic is not a proposed -durable behavior contract. - -### Stage-By-Stage Algorithmic Coverage - -| Stage | Inspected result | -| --- | --- | -| 1 | Range endpoint/loop arithmetic and reconciliation window bounds are safe; range capacity has ALG-003. | -| 2 | Exact rational sign rejects underflowed negatives; finite-number and precision behavior remain. | -| 3 | Producer insertion/lookup uses structured keys; no separator ambiguity or repeated producer search. | -| 4 | Active slice identity includes visible length; finite views remain distinct from genuine cycles. Required recursive copying remains output-proportional, with deterministic map-key sorting. | -| 5 | Citation text validates in input order, sorts/coalesces intervals, and visits only their union: `O(R log R + U + B)` after index setup. Constructor repetition is covered by ALG-001. | -| 6 | Runner constructs and passes one read-only index; standalone cache decoding retains lazy construction. Validation is the additional scope in ALG-001. | -| 7 | All three registry extraction paths use the supplied index, retaining local fallback. | -| 8 | Occurrence extraction reuses the index, including location grounding; no additional index hidden in that grounding path. | -| 9 | Spell, combat, enemy, and scene paths reuse it; combat gating still precedes unnecessary work; scene cache/fallback shares the same snapshot. | -| 10 | Worker tests establish overlap/order with controlled handshakes rather than performance assumptions. | -| 11 | Shared capture does work proportional to requested evidence, retains prepared ownership, and keeps writing outside native admission. | -| 12 | Debug-only envelopes are constructed behind effective-sink guards, including deferred chunk outcomes. | -| 13 | Source capture has one effective sink and shared original/parsed records; operation references are constant-size. Inline chunk/native evidence remains selected behavior. | -| 14 | Diagnostic maps group by identity, with constant bounded sample scans and checked occurrence arithmetic; no growing all-group search. | -| 15 | Public output excludes private working accumulators; intermediate copies have explicit stage boundaries. | -| 16 | Completed diagnostic collection/assembly is linear in jobs plus emitted groups, independent of lane acceptance. | -| 17 | One aggregation pass retains the valid prefix and joined causes; the composed cancellation/capture fix above remains present. | -| 18 | Reorder maps and completed extraction values are released after consumers; diagnostics and required normalized bytes survive. | -| 19 | Source/chunk/output phases retain explicit boundaries; their required encoding/copying work tracks selected data. | -| 20 | Invocation-local lifecycle avoids declaration-shared mutable run state; finalization retains causes and published locations. | -| 21 | Standard-library signal context stops dispatch and drains work; subsequent-signal restoration adds no per-job scheduling layer. | -| 22 | Pure copies traverse supported container trees and preserve omission/ownership; no serialization round trip. | -| 23 | Layout traverses steps/lanes once plus selected deterministic sorting; duplicate identities use maps. | -| 24 | Inventory traverses configured targets/slots with keyed catalog selection; nested loops reflect distinct input dimensions. | -| 25 | CLI reuses inventory; broad selectors enumerate their actual target matches. No second module interpreter remains. | -| 26 | Generated producer/slot checks are indexed; reference-source collision checking retains the all-pairs scan in ALG-002. | -| 27 | Family scene checks are linear in scenes/field text; adapters retain their separate acceptance responsibilities. | -| 28 | Shared NPC/location grouping is expected linear in records and complete identity bytes; removed-index output is linear in removed records. | -| 29 | Combat/spell grouping shares that mechanism while retaining no-change behavior; selected item exact-equality buckets remain untouched. | -| 30 | NPC/location earliest-position keys are prepared once; actual evidence ties retain their selected linear comparisons. | -| 31 | Item/enemy scalar/evidence keys are prepared once; enemy validation uses the fast path only after canonical evidence checks. | -| 32 | Prompt test changes affect test resilience, not production algorithms or prompt content. | -| 33 | Example fixtures are independent; private run-ID formatting is no longer frozen. No production algorithm changed. | -| 34 | Comments describe actual sharing/lifetimes, without blanket locking or per-job construction. | -| 35 | Confirmed dead metadata/helpers are removed; live identity and cache behavior remain. | -| 36 | Existing completion checks and canonical docs agree with the selected architecture; this pass adds efficiency follow-ups only. | - -### Validation And Limits - -The focused offline package check passed (Go reused cached results where valid): - -```sh -go test ./internal/modules/generic/chunk/units ./internal/modules/seriatim/input/transcript ./internal/core/source ./internal/modules/dnd/shared ./internal/framework/diagnostics ./internal/framework/pipeline ./internal/modules/dnd/normalize/... ./internal/modules/dnd/validate/... -``` - -The temporary overlay ran the real chunker's preparation on small synthetic -sources and inspected its output length/capacity. It changed no tracked test or -production file. The repository-wide tests, vet, build, targeted race suite, -and repeated cancellation checks from the immediately preceding remediation -remain applicable to this unchanged production revision. This pass gathered no -real-world performance data, used no provider credentials, and changes only this -report. Complexity claims concern the named components, not measured application -speedups. None of these opportunities authorizes removing chosen ownership or -validation boundaries, changing accepted inputs, or introducing a new runtime cap.