From cecd68f1610933ed33a5071119828af268cc4910 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Thu, 26 Nov 2026 01:24:00 +0000 Subject: [PATCH] Plan the remaining audit remediation work --- docs/roadmap/audit-remediation.md | 48 +- docs/roadmap/implementation.md | 1561 +++++++++++++---------------- 2 files changed, 721 insertions(+), 888 deletions(-) diff --git a/docs/roadmap/audit-remediation.md b/docs/roadmap/audit-remediation.md index be680f56..d41e5997 100644 --- a/docs/roadmap/audit-remediation.md +++ b/docs/roadmap/audit-remediation.md @@ -2,19 +2,19 @@ ## Status, Purpose, And Ownership -**Status:** Target design and scope accepted; detailed implementation planning -and implementation pending. +**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 a planning agent, not the worker's detailed execution plan. No application +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; a subsequent implementation plan will own ordered worker -stages, concrete dependencies, verification, and progress. Original audit reports +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. @@ -319,33 +319,17 @@ 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. -## Planning Handoff And Sequencing +## Implementation Handoff -Prepare one detailed implementation plan for a worker to execute in order. Keep -the completed core migration's plan/history intact. Use this roadmap as the target; -the planner selects concrete Go signatures, files, and independently reviewable -stages, without reopening accepted policy choices or treating historical audit -recommendations as stronger authority than the decisions here. +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. -Recommended ordering is narrow correctness fixes, ordinary-run source efficiency, -capture ownership/representation, finalization and shutdown, composition/domain -helpers, and remaining cleanup/final acceptance. This is dependency guidance, not -an artificial serial dependency between independent fixes. Improve fragile tests -before relying on them, and update interface documentation with affected changes. -Keep package extraction distinguishable from evidence behavior changes and narrow -bug fixes distinguishable from readability refactors. - -For each worker stage, identify the catalog coverage, scope, prerequisites, -observable completion criteria, relevant validation, and documentation updates. -Verify current callers and partial fixes before prescribing changes. Ensure no -required finding disappears inside a broad refactor and no resolved finding becomes -a second migration. Report any newly discovered conflict rather than silently -strengthening inputs, acceptance, or compatibility requirements. - -The planner should specify a usable intermediate state and focused commits. Detailed -test commands and exact stage boundaries belong in that plan; no new framework or -mandatory test matrix is needed to express them. Handing off or executing that plan -is subsequent work, not part of creating this roadmap. +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 @@ -374,5 +358,5 @@ 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. Remaining API details and -stage decomposition are implementation planning choices within these boundaries. +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/implementation.md b/docs/roadmap/implementation.md index 06a6dd41..cd368efc 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -1,972 +1,821 @@ -# Core And Integration API Implementation Plan +# Audit Remediation Implementation Plan ## Purpose And Baseline -All work below is complete. Individual completion notes record conditions at the -time of each unit; deferred interface and test repairs were resolved in the -cutover and verified during final acceptance. - -Implement the accepted [Core And Integration API Roadmap](core-integration-api.md). -That document owns scope and policy; this plan owns the implementation sequence. -The outcome is a core-driven authoring API, not just a smaller `RunProducer`. - -Planning baseline: `a051f34bf6db92bef65871f7602f0d15ea12b27c`. -Application code is unchanged from -`3887d89b763b7040efc866d4a57eb910d8778730`. Go 1.27.0 and the dependencies in -[go.mod](../../go.mod) are sufficient starting points. No dependency update, -configuration migration, durable schema change, or production inference is planned. - -Each numbered stage is one implementation prompt for a Luna coding agent. Follow -the stages in order as one end-to-end sprint. Intermediate stages may leave -unmigrated callers or tests uncompilable. Do not build compatibility interfaces, -duplicate executors, or temporary supported authoring recipes merely to make -each stage green. Keep a short record of deferred compile/test repairs so later -stages can finish them. All acceptance criteria must hold at sprint completion. - -Begin each stage with [Development](../development.md), -[Agent Policy](../policy/agents.md), and the policies applicable to its changes. -Use code discovery to confirm current callers; the paths below are starting -points, not a closed inventory. Preserve unrelated changes. Follow local commit -policy for completed units; an intermediate commit must accurately describe any -known incomplete migration. This plan does not authorize pushing or releasing. - -Source-path shorthand below uses `contracts`, `pipeline`, and `semanticreconcile` -for their directories under `internal/framework`, and `dnd` for -`internal/modules/dnd`. Test files remain beside their owning packages. - -## Selected Implementation Decisions - -These decisions make the work executable without another design approval round. -Exact Go names and file splits can follow the representative callers; preserve -the responsibilities and data flow below. - -### Contracts And Dependency Direction - -- Put author-facing operation/preparation/evaluation contracts beside the existing - typed stage contracts in `internal/framework/contracts`. Keep core execution - in `internal/framework/pipeline`. The reconciliation facility remains in - `internal/framework/semanticreconcile` and returns operation definitions for - that same executor; it does not execute a second producer loop or import D&D. -- A stage implementation prepares a typed operation. Core invokes preparation - and executes its result. Remove the module request's assessor, cache binding, - controls, and reuse-eligibility plumbing. Domain requests retain source/chunk, - incoming values, references, profile/session selection, metadata, and any narrow - optional domain-evidence facility actually needed. -- Distinguish deterministic candidate, native model operation, and the existing - preparation-limit disposition with small typed variants/constructors. Ordinary - preparation failure is a Go error, not the limit variant. Avoid a workflow DSL - or one struct containing unrelated optional branches. -- Keep engine, resolved controls, assessment, cache codecs/store, observation, - and terminal state in core's execution context. Registered calls bind this - context privately. A direct caller can supply the needed core execution - context and preparation function to the same executor; domain preparation - does not select or replace those collaborators. -- Remove engine storage and constructor arguments from producers that only used - the engine to run the retired helper. Validators that execute native one-shot - assessment still receive the shared engine. Do not remove native request and - result types from model-owning integrations. - -### Evaluation And Correction - -- One evaluation owns the optional typed candidate, ordered interpretation - guidance, candidate-associated diagnostics, and any evaluation-scoped domain - evidence/presentation. Core adds configured assessment separately and stores - the current evaluation as a unit. A candidate is not an acceptance claim. -- Reconciliation uses a typed evaluation record containing its proposal issues, - application information, omission counts/details, and family findings. Expose - the small common evaluation view to core, using composition or a small typed - interface. Keep reconciliation-only information out of ordinary extraction. - Evaluation-scoped projection functions may capture those fixed typed details; - a mutable `lastProposal`/`lastFindings` closure shared across turns is not the - replacement design. No untyped universal metadata payload is needed. -- Core invalidates the entire previous evaluation before constructing a selected - correction. Construction failure, unusable native output, and undelivered work - cannot leave its candidate or findings available as current output. Historical - evidence may retain earlier evaluations. -- The common correction form selects a native prompt and provides an explicit - guidance-to-native-input binding. Implement it by constructing the same native - request builder used by the custom form. Do not require a global `guidance` - variable name or D&D response schema. Carry explicit initial profile/session - selection and resolved native execution options through both forms. -- Core owns when fallback is selected. An integration constructs and intrinsically - checks supported output from the final eligible evaluation, or its existing - fixed fallback inputs when no evaluation remains. Family diagnostic projection - uses that same evaluation and terminal disposition, not an earlier turn. - -### Preparation And Terminal Behavior - -| Prepared/executed outcome | Core behavior | -| --- | --- | -| Ordinary preparation error or deterministic production error | Propagate; do not turn arbitrary errors into permissive recovery. | -| Deterministic candidate, including a no-model branch of a model role | Assess once; apply existing terminal policy after nonacceptance. No native request, correction loop, or synthetic cache key. | -| Existing explicit preparation-limit disposition | Apply existing strict/permissive handling and supported fallback. Do not assess a nonexistent candidate or broaden eligibility. | -| Usable model candidate | Run the complete configured assessment; collect ordered actionable guidance; continue through native coordination when permitted. | -| Correctable interpretation without a candidate | Use its domain guidance for native correction; do not claim approval or run candidate validators without a value. | -| Native failure or unusable result | Preserve classification/details and existing terminal policy. Do not convert it into semantic guidance or extend native repair budgets. | -| Model interpretation/application error | Preserve its cause and existing disposition; do not invent corrective guidance from an operational error. Capture and assessment-contract failures remain fatal. | -| Caller cancellation, undelivered response, framework/assessment-contract failure, or required-capture failure | Preserve existing fatal handling; no acceptance or fallback. | -| Accepted cache hit | Decode/check against current source; return accepted output without semantic reassessment or fictitious native execution. | - -Preserve the distinction between caller cancellation and a native operation -timeout. Preserve final-only safe-partial reconciliation, whole-chain assessment -of the final allowed usable response, and exactly one fallback count at its -emitting operation. These are existing contracts, not additional guarantees. - -### Scope Control - -Preserve native-kit ownership, module keys/default chains, fixed stage boundaries, -artifact types/identity rules, source semantics, CLI/configuration behavior, native -budgets, output/report contracts, and cache identity. Optional configured checks -remain optional; codec acceptance must not silently become ordinary validator -acceptance. An unsupported fallback still fails. - -Use the existing generic source model. Email and NWS Forecast Discussion -walkthroughs exercise text, domain metadata, chunk selection, and interpretation; -they do not implement new processors, ingestion, formats, or mandatory topology. -Do not introduce a public SDK/version guarantee, dynamic plugins, a new scheduler, -resource limits, security hardening, or universal collaborator thread safety. - -The remaining [audit catalog](audit/catalog.md) is not this sprint's task list. -CAT-015/CAT-016 and CAT-007 are in scope. Other entries are affected only to the -extent demonstrated by this migration. In particular, runner-wide diagnostic -retention/group-cap changes, process signals, full-source capture deduplication, -pipeline-layout consolidation, and unrelated efficiency fixes remain separate. -If this work must change whole-source capture representation, follow the accepted -[discussion Item 2](audit/discussion.md#2-convenient-debug-evidence-and-repeated-full-source-capture) -and record the added scope; do not invent a conflicting representation. - -## Validation Approach - -Use real internal collaborators and native kits with offline provider fakes. -Move/adapt existing behavioral tests as their entry points change; retain their -independent domain expectations. New common lifecycle coverage belongs in core, -not a full duplicate matrix in every family. Test observable outputs, assessment, -native history/selections, fallback, cancellation, reuse, and capture failure. -Do not pin callback order, type layout, error prose, prompt English, or hashes as -change detectors. Test-controlled prompt markers may verify request binding. - -Each stage lists focused commands. Run them when the affected packages can build; -if an earlier interface cutover prevents execution, record that fact and rerun the -checks after migration rather than claiming they passed. The last stage requires -the full suite. No paid API, benchmark threshold, coverage target, new CI gate, -or release process is needed. Adjust focused test-name filters when tests move -or are renamed; a filter matching no tests does not verify the stage. - -## Stage 1 — Define The Typed Preparation And Evaluation API - -**Status:** Complete. - -**Goal:** Establish the authoring contract using representative integrations. - -### Migration checklist - -- Native producer callers: D&D scene planning; spell, combat-turn, enemy-event, - scene-description, registry, and occurrence extractors; and NPC, item, and - location registry normalizers. Combat-turn and enemy-event extraction also - have deterministic no-model branches. -- Registry normalizers additionally call the deterministic assessment helper - for insufficient candidates and the terminal-failure helper for preparation - limits. Pipeline completion also calls the assessment helper. -- Migrate chunker registration and typed extractor, merger, and normalizer - registries, including generic unit chunking, append-order merge, and noop - normalization, plus deterministic D&D normalizers. -- Adapt direct producer, cache, capture, cancellation, operation, typed-registry, - CLI, integration, and module tests as their entry points move. Combat semantic - validation remains a separate one-shot native caller. - -The inventory is a migration aid; confirm additional callers as interfaces move. - -**Inspect:** `contracts/{contracts,typed_pipeline,producer}.go`, -`pipeline/{typed_execution,construction}.go`, spell extraction, scene planning, -the three registry normalizers, and current source types. - -**Work:** - -- Inventory producer/outcome-helper callers, typed registrations, direct tests, - generic deterministic modules, and preparation-limit/no-model paths. Keep the - inventory as a compact migration checklist in this plan, without freezing counts. -- Define the operation variants and common evaluation view selected above. - Give the core a preparation function to invoke; do not inject an executor for - the module to call. Separate domain requests from framework execution context. -- Sketch spell extraction, scene-plan interpretation with no candidate, a - deterministic branch, and registry application through those types. Add small - synthetic email/NWS-shaped source and operation sketches. Use domain metadata - without transcript speakers, scene tags, or registry requirements. -- Specify ownership of returned operation inputs, evaluation values, mutable maps/ - slices, and optional evidence hooks in local comments. Existing prepared module - instances may serve concurrent operations; new per-operation state belongs to - that preparation, not shared module fields. Preserve current detached boundaries - rather than imposing a new blanket clone/immutability system. - -**Acceptance:** Representative cases fit one core-driven contract; no domain type -enters core; ordinary preparation cannot access assessor/cache replacement or -terminal helper selection. Exact names are selected here, not deferred to each -module migration. Keep the design sketches small and reusable as later fixtures. - -**Check:** `go test ./internal/framework/contracts ./internal/core/source`. -This stage is one prompt for contracts and sketches, not executor implementation. - -## Stage 2 — Correct And Share Native Result Usability Handling - -**Status:** Complete. - -**Goal:** Resolve CAT-007 independently of the broader lifecycle rewrite. - -**Inspect:** `pipeline/producer.go`, combat semantic `validator.go` and tests, -`semanticreconcile/engine_test.go`, and pinned native result/error types. - -**Work:** - -- Add one small framework-owned check distinguishing absent result, completed - failed/invalid native validation, and an actual native Go error. Keep useful - native validation details in the returned cause. Do not manufacture - `promptkit.ErrValidation` for a completed content-check failure. -- Use it in the current producer and one-shot combat validator. The producer - retains its terminal handling; the validator retains unavailable judgment. - Preserve actual upstream causes for `errors.Is`/`errors.As`, cancellation, - capture failure, and ordinary valid-result interpretation. -- Correct the validator's wrong-sentinel assertion. At both caller boundaries, - check retained validation detail and refusal to interpret unusable content. -- Repair the native reconciliation fixture to select its real schema context, - request zero repair attempts, and require nil Go error plus a present failed - validation result with useful details and one provider call. An arbitrary setup - or schema-path error must not satisfy that test. - -**Acceptance:** A completed failed check is not mislabeled as an upstream -operational error; real upstream errors retain their identity. No extra loop or -budget is added. The later executor reuses this check. - -**Checks:** `go test ./internal/framework/pipeline ./internal/framework/semanticreconcile` -and `go test ./internal/modules/dnd/validate/scenedescriptions/combat_semantics`. - -## Stage 3 — Execute Preparation And Deterministic Outcomes In Core - -**Status:** Complete. +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 -**Goal:** Implement the core entry point and terminal policy before native work. +Keep these concrete operations in `internal/framework/pipeline`: -**Inspect:** `pipeline/{producer_outcome,runner_operation,candidate_assessment}.go` -and their existing tests; Stage 1's types and migration checklist. - -**Work:** - -- Implement the typed executor that calls preparation once and consumes its - operation variant. Registered and direct use will share this implementation. -- Handle deterministic candidate, explicit preparation limit, and ordinary error - distinctly. Reuse assessment/terminal helpers privately where useful. -- Return core-owned value, current evaluation/assessment information needed for - diagnostics, and terminal disposition. Integrations do not construct acceptance. -- Apply core terminal mode once. A supported fallback is constructed once, - intrinsically checked by its owner, not ordinarily reassessed, and reuse-ineligible. - Honor caller cancellation and framework/assessment-contract failure precedence. -- Port existing no-model and terminal-policy tests to the new core boundary; - cover a preparation error that must not invoke fallback. - -**Acceptance:** Core invokes preparation and assessment; deterministic work has -no engine/request requirement, no synthetic key, and no production retry. Existing -permissive behavior is neither widened nor removed. - -**Check:** `go test ./internal/framework/pipeline -run 'Producer|Operation'`. - -## Stage 4 — Move Native Evaluation And Continuation Into The Executor - -**Status:** Complete. Existing integrations still use the previous producer -entry point until their scheduled migrations. - -**Goal:** Own model production and replace coupled outer candidate variables. - -**Inspect:** `pipeline/producer.go`, native continuation/cancellation tests, and -the initial/correction request pairs in the pilot modules. - -**Work:** +- 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. -- Run native initial requests through the shared engine and Stage 2's usability - check. Interpret into a complete evaluation; assess each usable candidate once. -- Use explicit current-evaluation and terminal state, separate from pending - capture state. Replace findings with the candidate and clear the evaluation - before building a selected correction. No stale candidate survives a failed - builder, result-less execution, or unusable correction. -- Implement the common correction prompt plus guidance-input binder as a native - builder convenience. Exercise a different test-controlled input binding and a - specialized builder. Both use one path with native `Coordinate`, growing - exchange history, initial selections, and resolved execution overrides. -- Carry interpretation-only guidance without a candidate. Native errors and - validator unavailability do not become invented corrective instructions. -- If a candidate exists, interpretation guidance does not short-circuit its - configured validator chain. Keep native admission released before assessment - so nested validators can use the same limited backend. -- Preserve complete assessment of unchanged revisions and the final allowed - response, native turn limits, caller-cancellation precedence, operation-timeout - classification, and undelivered-response handling. - -**Acceptance:** The executor owns acceptance and continuation; the integration -has no turn loop. Candidate and associated findings are replaced atomically as a -logical evaluation. Existing producer tests protect behavior, not old closures. +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. -**Check:** `go test ./internal/framework/pipeline -run 'NativeProducer|Producer.*Cancellation'`. +### Family Mechanics -## Stage 5 — Bind Accepted-Result Reuse Inside Core Execution +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. -**Status:** Complete. +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. -**Goal:** Preserve cache semantics without author-controlled lifecycle plumbing. +Prepare invariant sort keys once per owned normalized record. Keep defensive +comparators for unproven inputs; canonical fast paths retain their existing premise. -**Inspect:** `pipeline/{producer_cache,runner_cache}.go`, producer/runner cache -tests, chunk-plan cache tests, and [ADR-0023](../adr/0023-unify-accepted-artifact-and-plan-caching.md). +## Stage 1 — Fix Accepted Range Arithmetic -**Work:** - -- Bind existing store, exact codec, current-source checks, and reuse eligibility - to the executor through framework-owned context, not domain preparation requests. -- Prepare the initial native request once; use its opaque message-content hash - and execute its retained prepared handle after a miss. Discard handles on every - terminal path. Do not rerender between keying and execution. -- Cache final accepted artifacts/plans, including corrected output, under the - original key. Hits decode/check current source without ordinary reassessment. -- Preserve bypass/refresh and previous entries on failed refresh. Fallback or - fallback-derived work skips lookup/write; deterministic/no-model work has no - manufactured key. Keep cache I/O diagnostic and encoding/capture errors distinct. - -**Acceptance:** Existing reuse tests can use the new executor without changing -the selected cache contract, adding dimensions, or persisting evaluation metadata. +**Coverage:** CAT-001/CAT-011. **Prerequisites:** none. -**Check:** `go test ./internal/framework/pipeline -run 'ProducerCache|ProducerCaches|ProducerExecutes|RunnerCache|ChunkPlanCache'`. +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. -## Stage 6 — Attach Evidence And Observation To Core-Owned Operations +**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. -**Status:** Complete. +**Check:** `go test ./internal/modules/generic/chunk/units ./internal/framework/semanticreconcile`. +Existing public contracts need no rewrite. -**Goal:** Keep standard evidence out of integration lifecycle code. +## Stage 2 — Check Exact Timestamp Negativity -**Inspect:** `pipeline/{native_capture,operation_capture,producer}.go`, -operation evidence helpers, native capture tests, and run-state internals. +**Coverage:** CAT-002. **Prerequisites:** none. -**Work:** +In Seriatim `adapter.go`/`validTimestamp`, check rational sign while retaining +float finiteness handling, exact ordering, and numeric metadata. -- Attach existing native capture/preparation/consumer observation hooks at the - executor boundary. Preserve supplied native hooks and the invocation context. -- Record standard preparation, candidate assessment, correction, cache decision, - and terminal evidence from actual execution. Retain earlier evaluations as - history without attributing their findings to the final artifact. -- Keep pending native capture finalization separate from candidate evaluation. - Finish each actual request on success, native failure, cancellation, or - undelivered continuation; preserve requested-capture failure and primary causes. -- Allow narrow optional domain evidence, including typed reconciliation detail, - without making the integration finalize capture. Guard expensive debug-only - construction before building its payload; use evaluation-scoped lazy projection - where needed. Required artifact encoding is not debug-only work. -- Cache hits may retain prepared/cache evidence but emit no native execution or - fabricated observation. Do not add invocation accounting or a capture package - migration. Leave untouched legacy capture inventory for the later audit work. - -**Acceptance:** Disabled evidence avoids new expensive debug-only work; enabled -evidence and independent observers retain their actual lifecycle. Physical sinks, -allocation, report delivery, and invocation finalization remain at existing owners. - -**Check:** `go test ./internal/framework/pipeline -run 'Capture|Evidence|Producer'`. +**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. -## Stage 7 — Wire Typed Extraction And Migrate The Spell Pilot +**Check:** `go test ./internal/modules/seriatim/input/transcript`. +No contract change is required. -**Status:** Complete. The spell and pipeline checks pass. The broader modules -check is deferred: the other D&D extractors and integration fixtures still use -the previous extraction interface. Migrate the extractors in their assigned -work and repair the remaining assembled fixtures by the cutover completion. +## Stage 3 — Use Structured Producer Lookup Keys -**Goal:** Prove registered extraction reaches the core executor end to end. - -**Inspect:** `pipeline/{extractor_registry,typed_execution,prepare,runner_concurrent}.go`, -spell `extractor.go`, shared extraction input helpers, and typed registration tests. +**Coverage:** CAT-012. **Prerequisites:** none. -**Work:** - -- Change extraction's typed interface/request to preparation under the selected - API. Registry erasure binds exact type and core context, invokes preparation - through the executor, and returns only core-completed results to the runner. -- Adapt `runExtractJob` without adding a second worker acquisition, outer - assessment, or new scheduler. Preserve source/reference isolation, provenance, - diagnostic origin, fallback count, serialization, and scoped errors. -- Migrate spells: prepare fixed catalog/registry/chunk inputs, return native - initial request and interpretation plus convenient correction and fallback. - Remove the producer engine field and domain `RunProducer` invocation. -- Update spell direct-call tests to use the same core entry point with explicit - test-controlled core context; retain independent expected spell output. -- Exercise exact-type registration and a core-selected correction/cache hit - through a registered pilot, not only a helper test. +Replace generated-binding insertion/lookup concatenation with +`generatedOutputKey`/`generatedOutputKeyFor` from `pipeline/handoff.go`. -**Acceptance:** Spell domain code describes preparation and policy, not execution -or terminal composition. Registration uses core; no external outcome can bypass -its assessment. Other extractors may await their migration stages. +**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. -**Checks:** `go test ./internal/modules/dnd/extract/spells` and focused typed -extraction/operation tests in `./internal/framework/pipeline`. +**Check:** `go test ./internal/framework/pipeline -run 'Generated|Handoff|ResolvePipeline'`. +No public grammar/documentation change. -## Stage 8 — Wire Merge And Normalize Preparation +## Stage 4 — Distinguish Finite Slice Views From Cycles -**Status:** Complete. Generic modules and pipeline fixtures use the new -boundary. D&D normalizers and assembled fixtures still using the former -normalizer interface are deferred to their scheduled migrations and cutover. +**Coverage:** CAT-013. **Prerequisites:** none. -**Goal:** Apply the same boundary to the remaining typed lane stages. +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. -**Inspect:** `pipeline/{merger_registry,normalizer_registry,typed_execution,runner_typed}.go`, -generic `merge/appendorder/typed.go`, generic `normalize/noop/typed.go`, and prepared lanes. +**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. -**Work:** +**Check:** `go test ./internal/core/source ./internal/modules/seriatim/input/transcript`. -- Adapt typed merger/normalizer registration and private exact-type erasure to - bind and invoke the same executor. Retain type/codec/projector compatibility - failures as errors, not panics or looser `any` acceptance. -- Change runner merge/normalize completion to consume core outcomes rather than - trust module-owned disposition and then choose another completion recipe. -- Migrate generic append-order and noop implementations to deterministic prepared - candidates. Keep ordering, domain combine errors, empty representation, and - ownership behavior. No synthetic prompts are required. -- Keep merge/normalize in the existing ready lane continuation. Preserve generated - handoff/reuse propagation and count emitted fallback once, not again in consumers. -- Adapt local generic and framework fixtures used by these paths. Domain D&D - normalizers can remain pending until their assigned migration stages. +## Stage 5 — Resolve Sparse Citations From Coalesced Intervals -**Acceptance:** All typed stage adapters have the core-owned route; deterministic -generic modules produce once, and no configured assessment is duplicated outside it. +**Coverage:** CAT-004. **Prerequisites:** none. -**Checks:** `go test ./internal/modules/generic/merge/appendorder ./internal/modules/generic/normalize/noop` -and focused runner operation/typed resolution tests. +Rewrite `dnd/shared/citations.go` as selected. Validate refs in input order before +sorting positions. Avoid source-scale allocation/traversal per sparse record. -## Stage 9 — Wire Chunk Planning And Migrate D&D Scenes +**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. -**Status:** Complete. Chunk-plan, generic unit, scene, and pilot checks pass. -Unmigrated D&D extractors, normalizers, and assembled fixtures remain deferred -to their assigned work and cutover. +**Check:** `go test ./internal/modules/dnd/shared ./internal/modules/dnd/validate/...`. -**Goal:** Include plan production without making scenes a core concept. - -**Inspect:** `contracts/contracts.go`, `pipeline/{chunker_registry,runner_chunk_plan}.go`, -generic unit chunking, D&D scene chunking, plan materialization, and plan cache tests. - -**Work:** - -- Move chunker invocation to preparation consumed by the same core executor. - The framework still materializes/validates generic plans before assessing chunks. -- Migrate generic unit chunking as deterministic preparation and D&D scene planning - as native preparation. Preserve plan annotations, source order/coverage checks, - identity, and the existing supported whole-source fallback. -- Return actionable interpretation guidance when a scene response cannot yet - produce a materializable candidate; do not assess nonexistent chunks. -- Keep plan cache decoding/rematerialization current-source-aware and native-only; - preserve no semantic reassessment on hits and accepted correction writes. -- Adapt chunker/direct-call fixtures and remove their integration-owned acceptance - assembly. Do not add scene metadata to generic source contracts. +## Stage 6 — Supply One Run-Owned Source Index -**Acceptance:** Deterministic and model-assisted planning share core disposition -while preserving their distinct production paths. Invalid generic plans still fail -at the appropriate boundary; no new chunk topology is promised. +**Coverage:** CAT-005 framework. **Prerequisites:** none. -**Checks:** `go test ./internal/modules/generic/chunk/units ./internal/modules/dnd/chunk/scenes` -and chunk-plan/materialization/cache tests in `./internal/framework/pipeline`. +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. -## Stage 10 — Migrate Combat-Gated Extraction And Its No-Model Paths +**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. -**Status:** Complete. Both focused extractor suites pass, including configured -assessment and cache-free no-model branches. Other extractors and normalizers -remain assigned to their respective migrations. +**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. -**Goal:** Prove no-model completion is a prepared operation, not a helper choice. +## Stage 7 — Reuse The Index In Registry Extraction -**Inspect:** `dnd/extract/combatturns` and `dnd/extract/enemyevents`, their -operation-registry input handling, and default registration/capability tests. +**Coverage:** CAT-005 registry callers. **Prerequisites:** Stage 6. -**Work:** +Migrate NPC/item/location registry extractors, including interpretation and +endpoint repair. Remove repeated indexing, not no-model behavior, prompts, +schemas, or identity rules. -- Migrate both extractors to native preparation for applicable chunks and a - deterministic candidate for their existing non-combat branches. -- Remove calls to direct assessment/outcome helpers, stored producer engines, - and manually assembled producer outcomes. Core performs configured assessment - once even when no model call is needed. -- Retain combat gating, contextual registry resolution, identities, endpoint - canonicalization, correction guidance, family fallback, and explicit selections. -- Exercise both branches through core with a native provider fake. A no-model - branch consumes no provider call and adds no synthetic cache entry. - -**Acceptance:** Empty non-combat output is still subject to the configured chain; -the migration does not invent combat classifications or silently skip assessment. - -**Check:** `go test ./internal/modules/dnd/extract/combatturns ./internal/modules/dnd/extract/enemyevents`. - -## Stage 11 — Migrate The Three Registry Extractors - -**Status:** Complete. All three focused extractor suites pass. Occurrence and -scene extractors, D&D normalizers, and assembled fixtures remain scheduled. - -**Goal:** Move canonical noun extraction to domain-only preparation. - -**Inspect:** `dnd/extract/{npcregistry,itemregistry,locationregistry}`, their typed -response interpretation/identity helpers, tests, and D&D registration. - -**Work:** - -- Return prepared native requests/evaluations with the convenient correction - binding and existing fallback algorithms. Remove module-owned execution and - terminal result composition and unused engine constructor dependencies. -- Preserve each registry's extraction scope, exact naming/identity behavior, - source resolution, nil/empty output, and external/generated reference handling. -- Retain native prompt IDs/static dependencies and schema selection. This is not - a prompt rewrite or domain scope expansion. -- Adapt direct-call tests to core and keep independent family output expectations. - -**Acceptance:** All registry extractors use the pilot's lifecycle without forcing -their domain preparation into one configurable D&D extractor engine. +**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 12 — Migrate The Three Occurrence Extractors +## Stage 8 — Reuse The Index In Occurrence Extraction -**Status:** Complete. Focused occurrence suites pass, including generated -registry handoff through registered typed execution. Remaining unmigrated -integrations and fixtures are addressed in subsequent stages. +**Coverage:** CAT-005 occurrence callers. **Prerequisites:** Stages 6–7. -**Goal:** Preserve contextual selections and domain feedback at the new boundary. +Migrate NPC/item/location occurrence extractors. Preserve registry resolution, +holder policy, references, interpretation, and fallback. -**Inspect:** `dnd/extract/{npcoccurrences,itemoccurrences,locationoccurrences}`, -their registry projections/resolvers, and current fallback/correction tests. - -**Work:** - -- Migrate preparation, native interpretation, correction, and fallback for all - three. Keep request-local/domain contextual selection and deterministic durable - ID attachment; do not expose opaque application IDs to the model. -- Replace returned candidate/guidance tuples with explicit evaluations. Preserve - the meaning of correctable selection errors versus ordinary preparation errors. -- Retain item holder/kind compatibility, location disambiguation, source ranges, - registry lookup precedence, and family-specific diagnostics. -- Exercise occurrence preparation with generated references via the typed route; - direct tests use the shared core entry point, not a module executor wrapper. - -**Acceptance:** Occurrence modules contain domain interpretation rather than -acceptance state, and no registry-specific concepts leak into ordinary core. +**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 13 — Migrate Scene Extraction And Two Deterministic Normalizers +## Stage 9 — Complete Extraction Index Reuse -**Status:** Complete. The focused suites and core pipeline tests pass, including -scene cache reuse against the current chunk and one-shot combat validation. -Other legacy callers remain deferred to the cutover. +**Coverage:** CAT-005 completion. **Prerequisites:** Stages 6–8. -**Goal:** Finish model extraction and cover non-registry normalization examples. +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. -**Inspect:** `dnd/extract/scenedescriptions`, `dnd/normalize/scenedescriptions`, -`dnd/normalize/spells`, and scene/combat semantic validator registration. +**Acceptance:** Verify whole-source resolution, concurrent readers, cache hits, +standalone calls, steps, and source/run isolation. Record actual construction +paths, not unmeasured production speedups. -**Work:** +**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. -- Migrate scene description extraction to prepared model work and explicit - evaluations. Preserve deterministic scene identity/range attachment, actual - fallback support, and both configured deterministic and one-shot model checks. -- Adapt scene-description and spell normalization to deterministic preparation, - retaining the existing transformation, diagnostic, cloning, and intrinsic checks. -- Do not promote optional shape validation into stricter codec acceptance or - redesign scene-domain rule ownership as an incidental part of this migration. -- Keep the combat semantic validator a one-shot native assessor using Stage 2's - check; it does not invoke the producer executor or semantic correction loop. +## Stage 10 — Control Worker-Test Overlap And Bound Handshakes -**Acceptance:** All ten baseline extractors have migrated; these deterministic -normalizers receive one core assessment and retain existing output semantics. +**Coverage:** CAT-027. **Prerequisites:** none; precedes lifecycle edits. -**Check:** `go test ./internal/modules/dnd/extract/scenedescriptions ./internal/modules/dnd/normalize/scenedescriptions ./internal/modules/dnd/normalize/spells ./internal/modules/dnd/validate/scenedescriptions/combat_semantics`. +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. -## Stage 14 — Adapt The Remaining Deterministic D&D Normalizers +**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. -**Status:** Complete. All five focused normalizer suites pass through core -operation execution; semantic registry normalizers remain scheduled below. +**Check:** `go test ./internal/framework/pipeline -run 'Concurrent|Concurrency|ReverseCompletion|ReadyJobs|Cancellation' -count=10`; +run affected pipeline tests under `-race` once. -**Goal:** Finish the mechanical deterministic contract migration. +## Stage 11 — Extract Native Capture Ownership -**Inspect:** `dnd/normalize/{combatturns,enemyevents,npcoccurrences,itemoccurrences,locationoccurrences}` -and their typed registration and regression fixtures. +**Coverage:** CAT-032. **Prerequisites:** Stage 10. -**Work:** +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. -- Return deterministic prepared candidates plus domain diagnostics and existing - supported fallback behavior where applicable. Core owns assessment/disposition. -- Keep domain transformation bodies intact unless the new boundary requires a - small adjustment. Preserve exact duplicate rules, ordering/ties, references, - identity resolution, unknown values, and nil/present-empty storage behavior. -- Adapt constructor/registration and direct test entry points, not expected - domain output. Do not fold the audit's sort/dedup/shape refactors into this step. +**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. -**Acceptance:** Every deterministic lane module now fits core preparation without -model machinery. Registry semantic normalization remains for Stages 15–19. +**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. -**Check:** Run the five focused `dnd/normalize` packages above; rerun generic -append-order/noop tests if shared adaptation helpers change. This is one prompt -for repetitive signature/adaptor work, not five new domain algorithms. +## Stage 12 — Avoid Disabled-Capture Construction -## Stage 15 — Build Shared Reconciliation Preparation +**Coverage:** CAT-003. **Prerequisites:** Stage 11. -**Status:** Complete. Synthetic preparation and core pipeline tests pass. -The contracts package's legacy fixture implementations do not compile after -the interface migration and remain deferred to the cutover; proposal evaluation -and production adapters remain scheduled below. +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. -**Goal:** Give families one typed entry into reconciliation without execution glue. +**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. -**Inspect:** `semanticreconcile/{preparation,requests,application,proposal}.go`, -all three normalizer procedures, and Stage 1's typed reconciliation sketch. +**Check:** `go test ./internal/framework/pipeline ./internal/framework/capture ./internal/modules/integration`. +Comment subtle deferred ownership; record all inspected boundaries in catalog. -**Work:** +## Stage 13 — Share Source Evidence At The Effective Sink -- Add a focused facility that constructs a core operation using existing neutral - preparation. Accept fixed original records, domain candidate projection, - native prompt selections, typed family application/diagnostic functions, and - existing supported fallback construction. -- Retain original merged fallback inputs separately from deterministically - preprocessed records. Prepare handles/windows/material once per operation. -- Centralize insufficient-candidate/no-model and preparation-limit decisions; - return their typed operation variants, not calls to core terminal helpers. - Ordinary projection/preparation errors still propagate. -- Supply initial native requests and correction builders from retained preparation; - preserve candidate-number range and namespace guidance. Share standard original/ - preparation evidence with lazy construction when disabled. -- Exercise the facility with a small synthetic record family before migrating - production families. Do not add NPC/item/location switches or imports. +**Coverage:** CAT-024. **Prerequisites:** Stages 11–12. -**Acceptance:** Families can describe reconciliation preparation without choosing -an assessor, cache, terminal helper, or native execution path. Existing limits -and their meaning remain unchanged. +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. -**Check:** `go test ./internal/framework/semanticreconcile` and relevant contracts -tests. Model evaluation/application lifecycle is completed in Stage 16. +**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. -## Stage 16 — Centralize Reconciliation Evaluation And Terminal Projection +**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. -**Status:** Complete. Synthetic native lifecycle tests cover proposal -replacement, safe partial output, failed correction, deterministic findings, -and preparation-limit fallback. Reconciliation and pipeline suites pass; -production family adapters remain scheduled below. +## Stage 14 — Remove Group Caps, Retain Sampling And Overflow Checks -**Goal:** Replace duplicated current-proposal bookkeeping with typed evaluations. +**Coverage:** CAT-009 capacity policy. **Prerequisites:** none. -**Inspect:** Proposal safety/application APIs, all three family interpretation/ -finish/fallback closures, core evaluation replacement, and evidence support. +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. -**Work:** +**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. -- Implement proposal decoding/safety assessment and a typed application callback - in the facility. Apply each complete proposal afresh to fixed originals; retain - safe groups and all affected originals according to existing application policy. -- Construct one typed reconciliation evaluation holding candidate, issues, - application omissions, family findings, and ordered guidance. Translate it to - the common core view without putting family data in core fields. -- Project final domain diagnostics from the same evaluation and core disposition. - Preserve no-model base findings, final safe-partial warnings, and original-input - fallback when no evaluation is eligible. Do not carry findings/omission counts - from a superseded or failed correction into final output. -- Centralize standard proposal/application evidence and result assembly. Families - retain semantic guidance, domain warning meaning, and fallback validation. -- Add focused synthetic lifecycle coverage for proposal replacement rather than - union, omitted safe groups, no-model/limit, and invalidation before correction. - Use the same core executor with native fakes; do not create another turn loop. +**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. -**Acceptance:** The facility owns lifecycle state and families supply typed policy. -Its current evaluation and native capture are separate; domain diagnostics are -about the final value, while historical proposal evidence remains available. +## Stage 15 — Separate Working State From Logical RunOutput -**Check:** `go test ./internal/framework/semanticreconcile ./internal/framework/pipeline`. +**Coverage:** CAT-006 structure; CAT-009/CAT-022 foundation. +**Prerequisites:** Stages 12–14. -## Stage 17 — Migrate NPC Registry Normalization +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. -**Status:** Complete. The NPC registry normalizer uses shared reconciliation -preparation and its focused semantic and deterministic tests pass. Item and -location adapters remain scheduled below. +**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. -**Goal:** Establish the first production reconciliation adapter. +**Check:** `go test ./internal/framework/pipeline ./internal/modules/integration ./internal/cli` +where buildable. Update internal terminology, not public contracts. -**Inspect:** `dnd/normalize/npcregistry/{normalizer,semantic_normalizer_test}.go`, -NPC identity, application, evidence, and normalization-result helpers. +## Stage 16 — Preserve Completed Diagnostics Independently Of Lanes -**Work:** - -- Replace the repeated native/no-model/limit/finish procedure with the shared - reconciliation operation builder. Keep NPC record preprocessing/projection, - canonical naming/identity, typed group application, and fallback validation local. -- Translate neutral issues and final typed application data into the existing - family guidance/diagnostics through a D&D-local adapter where genuinely shared. -- Remove engine storage and mutable proposal/findings state from the normalizer. - Core chooses fallback and the facility projects current evaluation diagnostics. -- Adapt semantic tests and registration to the core route; retain independent - expectations for safe aliases, invalid/overlapping groups, retained candidates, - fresh application, no-model output, and qualified fallback. +**Coverage:** CAT-008. **Prerequisites:** Stages 10, 15. -**Acceptance:** The normalizer reads primarily as NPC domain policy. A failed -later response cannot recover an earlier proposal's output or findings. +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. -**Check:** `go test ./internal/modules/dnd/normalize/npcregistry`. +**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. -## Stage 18 — Migrate Item Registry Normalization +**Check:** `go test ./internal/framework/pipeline -run 'Diagnostic|Concurrent|Cancellation|OrderedStep|Handoff'`; +`go test -race ./internal/framework/pipeline`. Update diagnostics flow docs. -**Status:** Complete. Item reconciliation uses the shared facility; focused -tests pass for currency compatibility, proposal replacement, fallback, and -evaluation evidence. Location reconciliation remains scheduled below. +## Stage 17 — Finalize Once, Retaining Primary And Finalization Causes -**Goal:** Exercise richer compatibility and omission guidance without family switches. +**Coverage:** CAT-009 correctness; CAT-022 foundation. +**Prerequisites:** Stages 14–16. -**Inspect:** `dnd/normalize/itemregistry`, currency compatibility/application -helpers, and the item tests for independent safe groups and all omission counts. +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. -**Work:** - -- Migrate to the same reconciliation facility. Preserve exact preprocessing, - same-denomination currency aliases, incompatibility with other denominations/ - non-currency items, evidence unions, and deterministic item identity. -- Return currency rejection guidance and omission details in the typed evaluation; - retain family diagnostic classification and supported fallback construction. -- Exercise a later proposal replacing earlier safe groups, native/correction - failure clearing candidate details, and accepted versus final fallback output. - Reuse core coverage where it already protects generic lifecycle behavior. -- Remove the local no-model/limit/finish choreography, stored engine, and parallel - `findings`/`advisories`/`discardedGroups`/`omissionDetails` state. - -**Acceptance:** Item-specific compatibility stays typed and local; generic core -does not learn currency or reuse stale omissions. No new permissive fallback -eligibility is introduced. +**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/modules/dnd/normalize/itemregistry`. +**Check:** `go test ./internal/framework/diagnostics ./internal/framework/pipeline ./internal/cli`. +Update finalization docs; errors convey incompleteness without new report fields. -## Stage 19 — Migrate Location Registry Normalization +## Stage 18 — Release Intermediates After Their Last Consumer -**Status:** Complete. All three registry normalizer suites and shared D&D -diagnostics tests pass. Location identity and anchor policy remain family-owned; -equivalent fallback diagnostic translation is shared. +**Coverage:** CAT-006 completion. **Prerequisites:** Stages 15–17. -**Goal:** Complete production reconciliation and preserve location distinctions. +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. -**Inspect:** `dnd/normalize/locationregistry`, location identity/anchor handling, -and tests for same-named locations, nesting, exact duplicates, and unsafe proposals. +**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. -**Work:** +**Check:** `go test ./internal/framework/pipeline ./internal/modules/integration`; +`go test -race ./internal/framework/pipeline`. Comment non-obvious last consumers. -- Replace lifecycle glue with the shared operation facility. Retain typed location - preprocessing, anchor/identity semantics, candidate eligibility, evidence, - safe application, and intrinsic fallback checks. -- Keep same-named but distinct places separate under the existing rules. Do not - reduce this family to NPC/item name identity to fit a shared helper. -- Use typed evaluation data for final findings/omissions and preserve no-model - and limit handling through core. Remove old engine/lifecycle state. -- Compare the three adapters after migration. Extract only genuinely equivalent - D&D diagnostic translation; revise the facility if family switches or repeated - framework coordination have appeared instead of hiding those differences. - -**Acceptance:** All three registry normalizers share lifecycle code, retain their -independent domain expectations, and use the same core execution path as extraction. - -**Check:** `go test ./internal/modules/dnd/normalize/locationregistry` -and the three registry-normalization packages together. - -## Stage 20 — Complete The Cutover And Remove Superseded Plumbing - -**Status:** Complete. Legacy producer execution and request/result wrappers -are removed; remaining fixtures use core operations. The specified framework, -module, CLI, and preflight checks pass, and all repository packages compile. -The one-shot combat semantic validator remains the intentional native caller. - -**Goal:** Remove the old authoring recipe and finish remaining callers. +## Stage 19 — Expose Cohesive Runner Phases -**Inspect:** The Stage 1 caller checklist; all production registrars; pipeline, -CLI, preflight, generic, and contracts test fixtures; generated handoff and reuse tests. - -**Work:** - -- Finish remaining programmatic/test callers of the changed stage interfaces. - Remove obsolete public lifecycle fields, helper wrappers, outcome-specializing - adapters, and module-side executor selection. Useful assessment/cache/capture - helpers can remain internal. Do not retain an obsolete recipe for tests alone. -- Verify registered extraction, merge, normalization, and chunk preparation all - reach the same executor; prepare-time exact-type/construction failures still - precede input parsing. Keep module keys, profiles/static dependencies, and - complete maintained example configurations valid. -- Review all remaining domain calls to producer/outcome helpers and engine - execution. Producers should prepare; the one-shot validator remains intentional. - Search results are review aids, not a test forbidding native types in modules. - -**Acceptance:** No obsolete production authoring path remains. The entire -repository compiles again. Resolve every earlier deferred migration repair before -proceeding, except documentation work assigned below. The next stage verifies -assembled behavior rather than making compatibility wrappers for failing fixtures. - -**Checks:** `go test ./internal/framework/... ./internal/modules/... ./internal/cli ./internal/preflight`. - -## Stage 21 — Verify Cross-Boundary And Concurrent Execution - -**Status:** Complete. The specified framework, module, CLI, and preflight -suite passes, as do focused pipeline and reconciliation race checks. Existing -assembled recovery, handoff, capture, admission, and worker tests were reviewed; -a synchronized native-operation test covers concurrent evaluation isolation. - -**Goal:** Establish behavior where correctness spans the new owners. - -**Inspect:** Core executor and stage adapters; existing pipeline worker, operation, -cache, capture, generated-handoff, CLI recovery, and native admission tests. - -**Work:** - -- Run representative assembled tests for full assessment/final turns, native - history and explicit selections, interpretation-only guidance, cache hits and - corrected writes, failed refresh, fallback-tainted generated consumers, and - required capture failure. Preserve partial output/error behavior already owned - by the runner/CLI; do not silently undertake deferred diagnostic-finalization work. -- Reuse worker/admission tests for concurrent operation-state isolation, bounded - jobs, cancellation/draining, and nested validation on a capacity-one backend. - Add controlled synchronization only where the new boundary lacks protection. -- Inspect gaps introduced by moving ownership. Retain one common lifecycle test - owner and representative family expectations; remove redundant legacy mock - choreography only after its meaningful behavioral protection is retained. - -**Acceptance:** Domain results, source handling, independent observations, -fallbacks, and reuse behave as selected; -concurrent operations cannot accidentally reuse another operation's evaluation. -Assembled tests verify behavior at the new boundary without adding an exhaustive -cross-product or reimplementing upstream structural repair tests. - -**Checks:** `go test ./internal/framework/... ./internal/modules/... ./internal/cli ./internal/preflight` -and `go test -race ./internal/framework/pipeline ./internal/framework/semanticreconcile`. - -## Stage 22 — Provide The Working Author Example And Internal Guides - -**Status:** Complete. The registered domain-neutral message example exercises -contextual correction and deterministic completion through core. Pipeline tests -pass, and affected internal-guide paths and API references were checked. - -**Goal:** Make the new boundary usable without reading producer implementation. - -**Inspect:** Stage 1's non-D&D sketches, actual finished APIs, and current -`docs/internal/{modules,pipeline,dnd,llm,state,overview}.md`. - -**Work:** - -- Finish one minimal domain-neutral working example, preferably an external - package test fixture under the framework with a real registrar/codec and a - local provider fake. Keep it reusable by the tests instead of creating a new - production demo command. Use generic text/metadata/chunks, not D&D conventions. -- Demonstrate preparation and execution, contextual domain interpretation, a - correction binding, and deterministic/no-model completion. The email/NWS - sketches must expose no forced scene/combat/registry assumptions; only one - concrete introductory example is needed. Point to a migrated registry for - richer reconciliation rather than duplicating it in the example. -- Rewrite Module Internals' recipe for core-owned preparation. Cover required - versus optional behavior, direct callers, ordinary errors versus domain - guidance/limits, supported fallback, evaluation lifetime, concurrency, and - evidence ownership. Link the tested example and real production adapters. -- Update Pipeline/D&D Internals and affected overview/LLM/state descriptions to - match the actual owners. Identify engine/capture/cache construction rather than - documenting upstream library features; link pinned native documentation for them. -- Document actual shared-instance/input/hook lifetimes without promising every - supplied writer/observer is thread-safe or installing blanket locks. No external - author study, readability gate, or new documentation test framework is needed. - -**Acceptance:** The introductory example executes through registration and core, -not a private producer import. Documentation presents one current recipe, with -domain-specific policy owned by families and volatile details in canonical homes. - -**Checks:** Run the package test containing the example; verify local links and -API references against source. Run affected example/config loading tests if changed. - -## Stage 23 — Record Ownership And Reassess Overlapping Audit Findings - -**Status:** Complete. ADR-0026 and architecture policy record the selected -boundary, ADR-0022 links its narrow supersession, and the audit catalog and -discussion distinguish resolved lifecycle/usability findings from remaining work. -Changed local documentation links were checked against the repository. - -**Goal:** Bring architectural guidance and audit status in line with the result. - -**Inspect:** Architecture policy, ADR-0022 and related ADR status links, -`audit/{catalog,discussion}.md`, and completed implementation/test evidence. - -**Work:** - -- Add the next sequential ADR (currently 0026) for core-invoked preparation, - core-owned operation lifecycle, explicit evaluations, and focused reconciliation. - Explain the integration boundary and why helper-only cleanup was insufficient. -- Update ADR-0022's status/navigation only to identify the narrow supersession - of module-composed producer mechanics. Retain its accepted body and unaffected - native continuation, assessment, guidance, and terminal policy decisions. -- Update architecture policy's concrete ownership description, including the - expanded neutral reconciliation responsibility. Preserve fixed stages, kit - ownership, ordinary error behavior, and selected acceptance/reuse contracts. - Do not turn new helper signatures or private representation into invariants. - Update its local last-updated date; retain the adopted upstream baseline. -- Reassess CAT-007, CAT-015, and CAT-016 with source/test links. Qualify partial - progress on CAT-003/006/008/009/014/017/018/022/023/024/025/032 where relevant; - do not mark entire findings resolved merely because nearby code moved. -- Update catalog summary/status wording and discussion Item 5's implementation - status to agree with the evidence. Keep original audit reports as historical - evidence, preserve unrelated outstanding entries and CAT-034's resolved status. - Do not implement the remaining audit in this step or retire its evidence. - -**Acceptance:** Architectural rationale and current guidance agree; the catalog -accurately describes what this sprint did and did not address. No broader -restrictions or guarantees have been introduced through documentation or tests. - -**Checks:** Review changed ADR/status links and documentation links; compare -catalog resolutions to actual tests and code, not just the migration inventory. - -## Stage 24 — Perform Final Sprint Acceptance - -**Status:** Complete. Full offline tests, vet, build, focused race checks, and -`git diff --check` pass. The caller and boundary review confirmed core-owned -execution, final-evaluation behavior, reuse/capture protections, and the -domain-neutral author example. No schema, configuration, CLI contract, or -output-format changes were introduced. Remaining audit findings are tracked in -the [catalog](audit/catalog.md); no release or push was performed. - -**Goal:** Establish that the target architecture is complete and ready for review. - -**Work:** - -- Run the checks below, fixing sprint regressions at their owning boundary. - Rerun any focused checks deferred because of the intermediate interface cutover. -- Review the caller checklist against current source: ten baseline extractors, - scene planning, three semantic registry normalizers, deterministic modules, - typed registration/preparation, direct callers, and the one-shot validator. - Additional discovered callers also require a documented disposition. -- Trace one extraction, one no-model operation, scene-plan correction, and - reconciliation end to end. Confirm that integrations no longer choose the - shared lifecycle and that native validation/admission remain upstream-owned. -- Verify one convenient and one custom correction path; final-evaluation - diagnostics; no stale candidate on failed corrections; current-source reuse; - fallback disclosure/ineligibility; required evidence and supplied observation; - and the tested non-D&D author example. Prefer existing sufficient behavioral - tests to additional matrices or private-structure assertions. -- Review diffs for unintended schema/config/CLI/output changes, new restrictions, - fallback eligibility changes, weakened optional checks, and out-of-scope audit - work. Keep only changes needed for the selected boundary and identified bugfix. -- Report checks performed, unresolved implementation defects if any, and remaining - audit work. Completion requires no known unfinished item from this plan. Do not - tag/release, push, or delete planning documents as part of acceptance. - -**Commands:** +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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 + +**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/semanticreconcile ./internal/modules/dnd/validate/scenedescriptions/combat_semantics +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 ``` -The ordinary build can leave an ignored root binary; do not stage generated -artifacts. Check maintained example loading, native prompt dependency preflight, -and CLI recovery/report behavior through their existing offline tests. Inspect -documentation links manually or with available repository checks; do not add a -new tooling dependency solely for this sprint. +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:** Full offline tests, vet, build, and focused race checks pass; -the author-facing API, production callers, documentation, and catalog agree. -The target is established by implementation and behavioral evidence, not by -smaller files, fewer callbacks, or an unchanged happy-path output alone. +**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. Scope and policy choices are settled in the feature roadmap. Stage 1 -selects concrete Go signatures using the prescribed ownership and representative -callers; that is bounded implementation design, not an unresolved product decision. +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.