From 78ad79d64d70ae9c7f177bd094e49e574979a9a7 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Thu, 26 Nov 2026 13:53:00 +0000 Subject: [PATCH] Remove completed audit history from the roadmap --- docs/roadmap/archive/audit.md | 2474 ----------------- .../warning-signal-and-presentation-audit.md | 648 ----- docs/roadmap/audit/01-correctness.md | 178 -- docs/roadmap/audit/02-efficiency.md | 277 -- docs/roadmap/audit/03-complexity.md | 476 ---- docs/roadmap/audit/04-concurrency.md | 229 -- docs/roadmap/audit/05-resources.md | 265 -- docs/roadmap/audit/06-error-handling.md | 259 -- docs/roadmap/audit/08-testing.md | 418 --- docs/roadmap/audit/10-equivalence.md | 461 --- docs/roadmap/audit/11-boundaries.md | 357 --- docs/roadmap/audit/12-deadcode.md | 225 -- docs/roadmap/audit/catalog.md | 792 ------ docs/roadmap/audit/discussion.md | 420 --- docs/roadmap/core-integration-api.md | 356 --- 15 files changed, 7835 deletions(-) delete mode 100644 docs/roadmap/archive/audit.md delete mode 100644 docs/roadmap/archive/warning-signal-and-presentation-audit.md delete mode 100644 docs/roadmap/audit/01-correctness.md delete mode 100644 docs/roadmap/audit/02-efficiency.md delete mode 100644 docs/roadmap/audit/03-complexity.md delete mode 100644 docs/roadmap/audit/04-concurrency.md delete mode 100644 docs/roadmap/audit/05-resources.md delete mode 100644 docs/roadmap/audit/06-error-handling.md delete mode 100644 docs/roadmap/audit/08-testing.md delete mode 100644 docs/roadmap/audit/10-equivalence.md delete mode 100644 docs/roadmap/audit/11-boundaries.md delete mode 100644 docs/roadmap/audit/12-deadcode.md delete mode 100644 docs/roadmap/audit/catalog.md delete mode 100644 docs/roadmap/audit/discussion.md delete mode 100644 docs/roadmap/core-integration-api.md diff --git a/docs/roadmap/archive/audit.md b/docs/roadmap/archive/audit.md deleted file mode 100644 index 987b9e41..00000000 --- a/docs/roadmap/archive/audit.md +++ /dev/null @@ -1,2474 +0,0 @@ -# Codebase Audit - -## Audit Metadata - -- **Production target:** `92e89076a268089e703978fb9d7176200e93344c` -- **Branch at target:** `main` -- **Audit date:** 2026-08-08 -- **Go version:** `go1.26.5 linux/amd64` -- **PromptKit version:** `gitea.maximumdirect.net/eric/promptkit v0.5.0` -- **Knowledge-graph project:** `notarius-audit-92e8907` -- **Knowledge-graph target:** branch `main`, head - `92e89076a268089e703978fb9d7176200e93344c` -- **Initial worktree:** Clean. There were no pre-existing production or roadmap - changes to record. - -The commit above is the production snapshot under audit. Later commits that -change only roadmap audit documents do not change that production target. - -## Executive Summary - -The frozen production target is healthy enough to build and pass its complete -fresh, race, vet, and shuffled test suites, but the audit found 33 actionable -issues: three High, seven Medium, and twenty-three Low. The principal risks are -typed-validator aliasing that can mutate accepted stage output (RUN-002), raw -provider errors escaping the LLM adapter (LLM-001), work dispatch after -cancellation (RUN-001), silently ignored configuration documents (CFGCLI-001), -lossy state-path identities (STATE-001), and D&D prompt/durable-boundary -contract mismatches (DND-OCC-001, DND-SCENE-001, and DND-COMBAT-001). - -The recurring remediation themes are narrow boundary checks, explicit value -ownership, cancellation and error containment, indexing repeated scans, reuse -of compiled or canonical values, and removal of unreachable helpers. Those -changes should preserve the explicit typed registries, ordered runner and CLI -lifecycles, family-owned D&D policy, canonical generated-reference codec -boundary, source/evidence separation, bounded dual worker pools, and exact -module prompt manifests documented below. No independent Test Quality finding -survived final review: missing regression cases are owned by the corresponding -production defects. RUN-004 is the only independent comment defect that meets -the repository's exact-invariant standard. - -The review found no production dependency inversion, unbounded framework -worker pool, completion-order-dependent result assembly, debug-to-cache -coupling, model-visible credential material in embedded LLM assets, or domain -leakage across the Seriatim and generic module boundaries. - -## Recommended Remediation Work Sets - -These are bounded sets of related ownership changes, not a required delivery -sequence. Sets without shared IDs can be implemented and reviewed -independently. - -- **Runtime containment:** RUN-001, RUN-002, RUN-003, LLM-001, and LLM-002. - Keep cancellation, candidate ownership, terminal warnings, and outward error - chains aligned across the provider and pipeline runtime boundaries. -- **Strict input and identity boundaries:** CFGCLI-001, CFGCLI-002, PIPE-001, - REF-001, REF-003, STATE-001, and LLM-003. Reject ambiguous or oversized input - before allocation or normalization can erase the distinction. -- **Construction and handoff efficiency:** PIPE-002, REF-002, STATE-002, and - MOD-002. Remove only copies, scans, or compilation repeated inside an already - established ownership boundary. -- **Physical and virtual publication infrastructure:** STATE-003 and LLM-004. - Reuse the existing confined writer and read-only in-memory filesystem - mechanics without combining their higher-level policies. -- **D&D evidence and durable contracts:** DND-REG-001, DND-REG-002, - DND-OCC-001, DND-SCENE-001, and DND-COMBAT-001. Align evidence range, - prompt/schema, catalog projection, and durable codec enforcement at the - family-owned boundaries. -- **D&D normalization cost and diagnostics:** DND-REG-003, DND-REG-004, - DND-OCC-003, and DND-SCENE-002. Index repeated identity work, reuse canonical - evidence, and bound warning output without changing ordering or fallback. -- **Focused cleanup and documentation:** ARCH-001, RUN-004, MOD-001, MOD-003, - DND-CORE-001, and DND-OCC-002. These are independent documentation, - reachability, or unused-input changes with narrow validation surfaces. - -## Finding Index - -Findings are ordered by severity, then by correctness risk, dependency -boundary, and expected remediation value. Stable IDs preserve the owning audit -area even when related findings are grouped for implementation. - -| ID | Severity | Category | Title | -| --- | --- | --- | --- | -| RUN-002 | High | Correctness | Isolate typed validator values from stage output | -| LLM-001 | High | Correctness | Keep raw provider errors inside the adapter | -| RUN-001 | High | Correctness | Check cancellation at unguarded dispatch boundaries | -| CFGCLI-001 | Medium | Correctness | Reject additional YAML documents | -| RUN-003 | Medium | Correctness | Preserve warnings from the terminal rejected attempt | -| STATE-001 | Medium | Correctness | Preserve distinct identities in state paths | -| DND-OCC-001 | Medium | Correctness | Align item occurrence evidence fields with the shared prompt | -| DND-SCENE-001 | Medium | Correctness | Expose catalog aliases to spell extraction | -| DND-COMBAT-001 | Medium | Correctness | Enforce enemy-event semantics at the durable codec boundary | -| REF-001 | Medium | Efficiency | Bound reference reads before allocating the file | -| CFGCLI-002 | Low | Correctness | Reject a blank command-level LLM profile | -| PIPE-001 | Low | Correctness | Reject normalized module-reference collisions in the resolver | -| REF-003 | Low | Correctness | Include canonical size in generated-reference fingerprints | -| LLM-002 | Low | Correctness | Recheck cancellation after scheduler admission | -| LLM-003 | Low | Correctness | Reject duplicate virtual prompt names | -| DND-REG-001 | Low | Correctness | Reject reversed evidence ranges at durable D&D codec boundaries | -| DND-REG-002 | Low | Correctness | Keep extraction evidence inside the current chunk | -| DND-SCENE-002 | Low | Correctness | Make D&D normalization and advisory diagnostics complete and bounded | -| PIPE-002 | Low | Efficiency | Clone construction inputs once per builder boundary | -| REF-002 | Low | Efficiency | Index accepted outputs once per ordered handoff | -| STATE-002 | Low | Efficiency | Remove redundant post-decode clones from canonical codecs | -| MOD-002 | Low | Efficiency | Reuse compiled response schemas within a prepared validator | -| DND-REG-003 | Low | Efficiency | Index duplicate groups across D&D families | -| DND-REG-004 | Low | Efficiency | Select location identity anchors without sorting | -| DND-OCC-003 | Low | Efficiency | Reuse canonical item occurrence evidence | -| STATE-003 | Low | Duplication | Publish output through the confined file writer | -| LLM-004 | Low | Duplication | Share the read-only in-memory filesystem mechanics | -| MOD-001 | Low | Simplicity | Narrow generic integer option decoding | -| MOD-003 | Low | Simplicity | Remove unreachable JSON metadata clone helpers | -| DND-CORE-001 | Low | Simplicity | Remove the unused lossy unit-reference constructor | -| DND-OCC-002 | Low | Simplicity | Remove unused campaign references from NPC occurrence normalization | -| ARCH-001 | Low | Documentation/Comments | Repair broken ADR cross-references | -| RUN-004 | Low | Documentation/Comments | Document the lane collector's liveness invariant | - -## Findings - -### Architecture And Dependency Boundaries - -### ARCH-001 — Repair broken ADR cross-references - -- **Severity:** Low -- **Category:** Documentation/Comments -- **Evidence:** - `docs/adr/0012-resolve-opaque-entity-identifiers-deterministically.md:15` - links ADR-0003 as `0003-strongly-typed-stage-interfaces.md`, and line 17 - links ADR-0009 as - `0009-prefer-minimal-evidence-grounded-extraction-artifacts.md`. Neither file - exists. The maintained files are - `0003-typed-interfaces-with-two-zone-data-model.md` and - `0009-minimal-evidence-grounded-extraction-artifacts.md`. -- **Impact:** Readers and documentation tooling cannot follow ADR-0012 to the - two architectural decisions it explicitly relies on. Runtime behavior is - unaffected. -- **Recommendation:** Correct only the two relative link targets in ADR-0012. -- **Preserve:** Keep the accepted decision text and its intended references to - ADR-0003 and ADR-0009 unchanged. -- **Validation:** Run a relative Markdown-link check across `docs/adr/` and - confirm both targets resolve; verify the change contains no decision-text - edits. -- **Grouping:** Independent. - -### Configuration And CLI Composition - -### CFGCLI-001 — Reject additional YAML documents - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** `internal/core/config/file_config.go:327`–`353` - constructs a `yaml.Decoder`, enables `KnownFields`, and calls `Decode` only - once. `yaml.Decoder.Decode` reads the next YAML document, so input such as a - valid version 4 configuration followed by `---` and another configuration is - accepted with the second document ignored. The strict file tests in - `internal/core/config/file_config_contract_test.go` cover malformed values, - unknown fields, and duplicate normalized identifiers, but not an additional - document. -- **Impact:** An operator can append a syntactically valid configuration - document, receive a successful validation result, and then run with only the - first document. Settings in the ignored document—including operational or - pipeline settings—have no effect without a diagnostic, contradicting the - documented strict single-file model. -- **Recommendation:** After decoding `FileConfig`, decode once more and require - `io.EOF`; reject any second document, including an empty or malformed one, - with a contextual configuration error. -- **Preserve:** Keep version gating before the full strict decode, unknown-field - and duplicate-key rejection, and the existing defaults → file → environment - precedence unchanged. -- **Validation:** Add focused parser cases for a second valid document, a - second malformed document, and ordinary trailing whitespace/comments; run - `go test ./internal/core/config ./internal/cli`. -- **Grouping:** Independent. - -### CFGCLI-002 — Reject a blank command-level LLM profile - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** `internal/cli/run.go:149`–`166` registers `--llm-profile` as a - plain string flag, while the command's presence-aware empty-value checks - cover session ID, reasoning effort, output/debug directories, and recompute - step but not this flag. `runPipelineCommand` passes the resulting string to - `Config.Resolve`; `internal/framework/pipeline/profile.go:1255`–`1277` trims - an empty override and treats it as absent. The run contract tests cover a - valid override and an unknown non-empty profile, but not an explicitly - supplied blank value. -- **Impact:** A shell expansion such as `--llm-profile "$PROFILE"` with an - unset or blank value succeeds by silently using binding, pipeline, or - PromptKit defaults. The run can therefore use a different model/profile than - the operator explicitly intended to select. -- **Recommendation:** Make the CLI flag presence-aware and reject an explicitly - supplied empty or whitespace-only profile ID as command syntax before config - loading or physical-state allocation. -- **Preserve:** Keep a genuinely omitted override optional, trim non-empty IDs, - retain command → binding → pipeline → PromptKit precedence, and continue to - apply overrides only to selected LLM-backed bindings and validators. -- **Validation:** Add command-contract cases for blank and whitespace-only - values that assert exit status 2 and no state allocation, plus retain the - valid and unknown-profile run cases; run `go test ./internal/cli`. -- **Grouping:** Independent. - -### Pipeline Resolution, Preparation, And Typed Registries - -### PIPE-001 — Reject normalized module-reference collisions in the resolver - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** `internal/framework/pipeline/profile.go:1239`–`1252` sends every - module binding's reference map through `normalizeReferenceMap`. That helper, - at lines 1361–1377, trims each key but overwrites - `rawByNormalized[trimmedKey]` without checking whether another raw key already - produced the same identity. A programmatic binding containing both `slot` - and ` slot ` therefore retains whichever raw key is visited last by Go's map - iteration, then silently emits only one resolved binding. The later strict - reference resolver sees only the collapsed map and cannot diagnose the - collision. `internal/core/config/validation.go:256`–`266` correctly rejects - this shape for validated file/config flows, but direct `ResolvePipeline` - callers do not pass through that owner and there is no focused framework - regression case. -- **Impact:** A programmatically assembled profile can resolve successfully to - different external paths or generated selectors across processes from the - same ambiguous input. The normal CLI configuration path is protected by - upstream validation, which limits current production exposure, but the - resolver's own contract is nondeterministic. -- **Recommendation:** Make binding reference normalization return an error for - empty or duplicate trimmed keys before constructing the normalized map, and - propagate stage/lane context through `resolveBinding` callers. Avoid relying - on the config layer to make the framework resolver deterministic. -- **Preserve:** Keep whitespace normalization, exact external-versus-generated - source validation, sorted resolved bindings, local-over-pipeline precedence, - and the config layer's earlier contextual diagnostics. -- **Validation:** Add focused `ResolvePipeline` cases for whitespace-equivalent - chunk, extract, merge, and normalize reference keys, including different - source forms, and assert deterministic contextual rejection; run - `go test ./internal/framework/pipeline ./internal/core/config`. -- **Grouping:** Independent. - -### PIPE-002 — Clone construction inputs once per builder boundary - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** `Prepare` and `prepareLane` clone binding option maps while - forming requests (`internal/framework/pipeline/prepare.go:102`–`104` and - 202–206), and `prepareValidatorChain` does the same at lines 258–263. - Registry/build boundaries then clone the complete request again. Typed - extractors, mergers, normalizers, and validators add another clone inside - their registered erased-builder adapters - (`extractor_registry.go:56`, `merger_registry.go:68`–`74`, - `normalizer_registry.go:63`–`69`, and `validator_registry.go:101`–`108`), - after `buildErasedModule` or `buildPreparedValidator` already called - `cloneBuildRequest` (`prepare.go:272`–`299` and 325–327). Each request clone - deep-copies materialized reference content as well as options, so typed - builders receive two reference copies and as many as three option copies; - untyped stage and validator builders use fewer copies. Spell extractor, - normalizer, and catalog-validator construction then call - `spells/catalog.ResolveEffectiveCatalog`; that helper clones every slot and - every item byte slice in the already owned `ReferenceSet` - (`internal/modules/dnd/spells/catalog/effective.go:55`–`62` and 411–426), even - though it reads only the `spell_catalog` slot and decodes its content into a - new overlay value. On extractor construction this needlessly recopies the - optional NPC registry and campaign-context references as well. -- **Impact:** Every preparation repeats allocation and byte copying for bounded - external references and nested options, with the highest cost and a - different ownership path specifically for typed lanes and validators. The - work is run-construction-time rather than a concurrent operation hot path, - so the issue is low severity. -- **Recommendation:** Designate one private construction invocation as the - ownership boundary and clone the complete `BuildRequest` exactly there. - Store raw builders or remove the caller-side clone consistently so all stage - and validator registry variants follow the same single-copy rule. Let spell - catalog resolution read the owned catalog slot directly instead of cloning - unrelated slots. -- **Preserve:** Builders must continue to receive independently owned options, - reference maps, slot slices, metadata, and content bytes; preparation must - retain its own immutable resolved/reference state; nil, key/name, execution - class, and exact artifact-type checks must remain contextual errors. -- **Validation:** Extend construction hooks to mutate nested options and - reference bytes for typed and untyped modules/validators, assert no aliasing - with resolved or sibling requests, and use allocation/byte-copy observations - or a focused benchmark to confirm a single defensive copy. Add a spell - catalog construction case with large unrelated slots and verify that - resolution neither copies nor mutates them; run - `go test ./internal/framework/contracts ./internal/framework/pipeline - ./internal/modules/dnd/spells/catalog`. -- **Grouping:** Independent. - -### References And Ordered Handoffs - -### REF-001 — Bound reference reads before allocating the file - -- **Severity:** Medium -- **Category:** Efficiency -- **Evidence:** `internal/framework/pipeline/references.go:88`–`164` implements - the external-reference materialization boundary. At lines 128–146, - `materializeReferenceTarget` calls `os.ReadFile(path)` before comparing the - resulting allocation with `ReferenceSlot.MaxBytes`. The focused - `TestMaterializeReferencesEnforcesMaxBytes` case uses a nine-byte file and - verifies the post-read diagnostic, but does not prove that reads are bounded - by the declared three-byte limit. -- **Impact:** A mistakenly selected very large file, growing file, device, or - named pipe can consume memory far beyond the slot's advertised bound before - the framework rejects it. CLI reference overrides expose the same path, so a - local operator error can terminate the process instead of producing the - intended bounded validation failure. -- **Recommendation:** Open the path and read through a limit of - `MaxBytes + 1` when a positive maximum is declared, rejecting an extra byte - before retaining or cloning content. A regular-file size precheck may improve - diagnostics, but the bounded reader must remain authoritative for changing or - non-regular inputs. Preserve the existing unbounded behavior only for slots - that explicitly declare no maximum. -- **Preserve:** Keep config-relative versus working-directory-relative path - resolution, UTF-8 and media-type validation, empty-file warnings, canonical - digest/size/origin metadata, contextual errors without content, and owned - reference bytes. -- **Validation:** Add a reader or file fixture that proves no more than - `MaxBytes + 1` bytes are consumed, including a non-regular or growing-input - case, while retaining the current UTF-8, media, empty, and ordinary oversize - diagnostics; run `go test ./internal/framework/pipeline ./internal/cli`. -- **Grouping:** Independent. - -### REF-002 — Index accepted outputs once per ordered handoff - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** `buildStepReferenceSets` walks every generated binding in the - receiving step (`internal/framework/pipeline/handoff.go:37`–`89`). For each - previously unseen producer, `generatedReferenceItem` allocates a `matches` - slice and scans the complete cumulative `outputs` slice to find that - step/lane (`handoff.go:104`–`133`). Its cache avoids rescanning when several - targets fan out from the same producer, but a step consuming `P` distinct - producers from `O` earlier outputs still performs `P * O` comparisons and up - to `P` temporary allocations. -- **Impact:** Ordered pipelines with many distinct generated dependencies pay - quadratic handoff preparation work before the consumer step can start. The - current production profiles are small and the scan is outside the lane - worker hot path, which limits present impact. -- **Recommendation:** Build one map from normalized `(step ID, lane ID)` to an - explicit zero/one/many accepted-output state at the start of - `buildStepReferenceSets`, then let `generatedReferenceItem` perform a direct - lookup. Keep ambiguity as data in the index so duplicate producer outputs are - still rejected rather than overwritten. -- **Preserve:** Retain exact accepted-output cardinality, codec - decode/re-encode canonicalization, producer lookup, complete schema/media - validation, per-target byte ownership, deterministic contextual errors, and - the rule that no consumer lane starts after a failed handoff. -- **Validation:** Add a many-producer/fanout case that retains missing and - duplicate rejection, then use a focused benchmark or comparison counter to - demonstrate one output-index pass plus direct producer lookups; run - `go test ./internal/framework/pipeline`. -- **Grouping:** Independent; do not combine with PIPE-002, which concerns - construction-request copying rather than runtime producer lookup. - -### REF-003 — Include canonical size in generated-reference fingerprints - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** The generated `ReferenceItem` records canonical content length - in `SizeBytes` (`internal/framework/pipeline/handoff.go:154`–`177`), and the - manifest provenance also retains that value at lines 210–232. However, - `generatedReferenceFingerprintIdentity` and - `generatedReferenceDependencies` (`handoff.go:234`–`287`) hash producer, - kind, complete schema identity, media type, and content digest without the - canonical size. This differs from the documented resume contract in - `docs/internal/state.md:49`–`54`. The focused fingerprint test changes only - canonical content and does not assert size participation. -- **Impact:** Consumer checkpoint identity does not cover one field that the - handoff and manifest declare part of canonical reference identity. Current - construction derives size directly from canonical bytes, so a practical - stale reuse also requires malformed internal metadata, a digest collision, - or a future producer-path change; the immediate risk is therefore low. -- **Recommendation:** Add `SizeBytes` to the private fingerprint identity and - populate it from the canonical generated item before JSON hashing. Keep the - existing normalized fingerprint name and all current identity fields. -- **Preserve:** Do not weaken the content digest, producer provenance, - artifact kind, complete schema digest/fields, media type, or canonical codec - checks. Continue to keep content bytes out of checkpoints, manifests, debug - summaries, and errors. -- **Validation:** Add a direct dependency-fingerprint case that holds the - other identity fields constant while changing size metadata, retain the - canonical-content sensitivity case, and run - `go test ./internal/framework/pipeline ./internal/modules/integration/...`. -- **Grouping:** Independent. - -### Execution, Validation, Retry, And Concurrency - -### RUN-001 — Check cancellation at unguarded dispatch boundaries - -- **Severity:** High -- **Category:** Correctness -- **Evidence:** `Runner.Run` invokes the input adapter at - `internal/framework/pipeline/runner.go:159`–`177` without checking - `ctx.Err()` first; the first framework-owned cancellation check on that path - is inside `runWithRetry` at lines 389–418, after source work and its - checkpoint/debug side effects. At the other end of the run, ordered lane work - completes at lines 278–282, then evidence/debug assembly and - `encoder.Encode` run at lines 297–346 without another cancellation check. - The worker and retry paths do check cancellation, but - `TestRunnerReturnsParentCancellationAndStopsQueuedExtracts` covers only - cancellation while two extract calls are active - (`runner_concurrency_test.go:559`–`585`). A context-ignoring input or output - module can therefore be called with an already-cancelled context; in the - output case it can return files and make the cancelled run report success. -- **Impact:** Work can start after cancellation, and a cancellation arriving - after lane completion or during output debug assembly can still publish a - successful logical output. This violates the documented guarantee that - parent cancellation prevents queued work and output encoding, and it leaves - correctness dependent on every module independently honoring an already - cancelled context. -- **Recommendation:** Add framework-owned cancellation gates at run entry and - immediately before every module dispatch not already protected by - `runWithRetry` or a lane worker, especially input parsing and output encoding. - Recheck after intervening collaborator/debug/evidence work so a cancellation - cannot slip between the gate and the operation, and after an unguarded module - returns so a module that did not observe mid-call cancellation cannot publish - success. Return the parent context error through the existing failed-output - path. -- **Preserve:** Continue to pass the caller context into active operations, - wait for all started lane work, suppress output files on framework failure, - select an actual framework error deterministically when the parent remains - live, and prefer the parent cancellation when it is set. -- **Validation:** Add a pre-cancelled run whose input adapter ignores context - and must not be called, plus a run whose debug recorder cancels immediately - before output dispatch while a context-ignoring encoder records calls, and an - encoder that cancels mid-call but returns files. Assert `context.Canceled`, no - invocation after pre-dispatch cancellation, and no output files in either - output case; retain the active-extract cancellation case and run the package - under `-race`. -- **Grouping:** Independent. - -### RUN-002 — Isolate typed validator values from stage output - -- **Severity:** High -- **Category:** Correctness -- **Evidence:** Extract, merge, and normalize serialize a canonical candidate - before validation, but pass the operation's original typed value alongside - it; representative extract code is - `internal/framework/pipeline/runner_concurrent.go:424`–`439`, and merge and - normalize do the same in `runner_typed.go:264`–`277` and 359–392. - `validateTypedArtifact` clones source input, references, metadata, and chunks, - but `requestTarget := target` leaves `target.value` shallow-copied - (`runner_typed.go:458`–`499`). The registered typed adapter then exact-casts - that value and passes it directly to the validator - (`validator_registry.go:109`–`119`). Struct values containing slices, maps, - or pointers therefore retain aliases to the stage output. A validator can - mutate what later validators and final checkpoint serialization observe, - while serialized validators and attempt debug continue to describe the - pre-mutation canonical candidate. Candidate-encoding tests verify encode - counts and rejection-before-checkpoint behavior, but no focused test mutates - a typed validator request. -- **Impact:** A buggy validator can corrupt an accepted output, cause validators - in one chain to inspect different values, or make persisted output differ - from the candidate that was serialized for validation and debug. This breaks - the documented immutable whole-output validation contract at all three typed - stages. -- **Recommendation:** Treat the already serialized canonical candidate as the - clone boundary. Decode a fresh exact typed value through the active codec for - each typed validator, or provide an equivalent codec-backed deep clone, and - never expose the stage operation's retained value. Keep serialized validators - on independent schema/content copies of the same candidate. -- **Preserve:** Retain exact Go-type checks, one canonical candidate encode per - attempt, validator declaration order, isolated request metadata/references, - serialized-validator byte ownership, contextual errors, and final encoding - only after the entire chain approves. -- **Validation:** Use an artifact with both slice and map fields. Have the first - typed validator mutate both, then assert that the next typed validator, a - serialized validator, attempt debug, and accepted extract/merge/normalize - output all observe the original canonical value. Run the focused package - tests under `-race` as well as normally. -- **Grouping:** Independent. - -### RUN-003 — Preserve warnings from the terminal rejected attempt - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** The runtime contract says warnings from the final accepted or - rejected attempt are preserved (`docs/internal/pipeline.md:122`–`126`). Each - retry closure assembles per-attempt operation and validator warnings, but - stores them only on acceptance. Generated chunk-plan rejection returns at - `internal/framework/pipeline/runner_chunk_plan.go:142`–`150` before assigning - `result.warnings` at line 154, and `Runner.Run` promotes chunk warnings only - for acceptance or a cache hit (`runner.go:228`–`233`). Extract follows the - same pattern at `runner_concurrent.go:425`–`457`; `finalizeLaneExtract` skips - directly from a rejected result to the next chunk at lines 469–476. Merge - and normalize collect `attemptWarnings` but return terminal rejections before - appending them to `RunOutput` (`runner_typed.go:264`–`301` and 359–415). - `runWithRetry` returns only the last rejection, not its warnings - (`runner.go:389`–`428`). Existing retry-warning tests prove that discarded - attempts are not promoted, and final-rejection debug tests prove rejection - recording, but neither asserts terminal rejection warnings. -- **Impact:** Module warnings and warnings from validators that approved before - the rejecting validator disappear exactly when the final candidate is - rejected. Operators receive the rejection but lose diagnostics produced by - that terminal attempt, contrary to the documented output contract. -- **Recommendation:** Carry the warnings associated with the last rejection - through the retry result, then promote only that terminal attempt's warnings - at chunk, extract, merge, and normalize rejection handling. Keep warnings - from earlier failed or rejected attempts confined to attempt debug. Coordinate - any persistence-format addition with the later checkpoint/state audit rather - than silently changing state ownership here. -- **Preserve:** Do not promote warnings from attempts superseded by a later - retry, do not turn rejection into a framework error, keep deterministic - lane/chunk warning order, and retain accepted and reused checkpoint warning - behavior. -- **Validation:** Add table-driven chunk, extract, merge, and normalize cases - with distinct first-attempt and final-rejection warning scopes. Assert that - only the final scopes reach `RunOutput`, rejection attempt counts remain - correct, intermediate warnings remain in attempt debug, and shuffled/race - runs preserve order. -- **Grouping:** Independent. - -### RUN-004 — Document the lane collector's liveness invariant - -- **Severity:** Low -- **Category:** Documentation/Comments -- **Evidence:** `laneEngine.collect` coordinates a dynamically enabled - continuation send, extract-result closure, cancellation, and the - `pending`/`launched`/`completed` counters in - `internal/framework/pipeline/runner_concurrent.go:256`–`281`, with state - changes split across `handleExtractResult` and `handleCompletion` at lines - 283–313. The loop has no invariant-level comment. Its non-obvious purpose is - to discard only unlaunched continuations after cancellation while continuing - to drain extract results and exactly one completion from every launched - continuation before the continuation channel is closed and workers are - awaited. -- **Impact:** Current tests and the race run support the implementation, but a - future change to channel buffering, cancellation cleanup, or a counter can - introduce a deadlock or early close without the ownership/liveness rule being - visible at the maintenance point. -- **Recommendation:** Add one short comment immediately above - `laneEngine.collect` stating that it is the sole owner of pending/launch/ - completion accounting and must drain closed extract results plus every - launched continuation completion even after cancellation. Do not narrate the - `select` cases. -- **Preserve:** Keep chunk-first/lane-second extract dispatch, bounded extract - and continuation pools, overlap between completed lanes and remaining - extracts, cancellation of undispatched work, and the final worker wait. -- **Validation:** Review the comment against the collector termination - predicate and retain the existing cancellation, reverse-completion, - continuation-overlap, worker-bound, race, and shuffled tests. -- **Grouping:** Independent. - -### State, Checkpoints, Debugging, And File Safety - -### STATE-001 — Preserve distinct identities in state paths - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** The resolver accepts any non-empty trimmed ordered-step and - lane IDs (`internal/framework/pipeline/profile.go:341`–`351` and - 1382–1392). Checkpoint path construction then sends both IDs through - `checkpointPathComponent` (`internal/framework/checkpoint/recorder.go:476`– - `508`), which maps `.`, `..`, and every value containing `..` to the single - component `_`. The trace side duplicates that encoder in - `debugPathComponent` (`internal/framework/pipeline/debug.go:37`–`62`), and - `cleanDebugPath` at lines 364–374 additionally applies `path.Clean` before - encoding. Thus valid distinct identities such as `.` and `_`, or `a..b` and - `_`, select the same checkpoint component and can also collapse to the same - debug path. Existing filesystem tests cover traversal and symlink rejection, - but no focused test asserts that accepted identities map injectively. -- **Impact:** Two valid lanes or steps in one resolved pipeline can overwrite - each other's checkpoint manifests and payloads. Exact manifest validation - prevents a mismatched artifact from being silently reused, but ordinary - resume repeatedly invalidates and re-executes the colliding work, and a - required selective-recompute predecessor can become unavailable after its - sibling overwrites it. Requested debug records can likewise overwrite or be - attributed to the wrong identity. Atomic rename does not protect against a - logical-name collision. -- **Recommendation:** Introduce one shared, injective path-component encoding - for accepted application identities. Preserve already-safe components, but - encode reserved dot components and every unsafe rune rather than replacing a - whole value with `_`; do not run identity-bearing debug paths through a - lossy clean operation first. Keep path joining and confinement separate from - identity encoding. -- **Preserve:** Retain trimmed non-empty identity validation, human-readable - ordinary IDs, exact step/lane checks inside checkpoint manifests, narrow - relative state paths, symlink rejection, and recoverable cold execution for - incompatible reconstructible cache entries. -- **Validation:** Add table and uniqueness cases covering `.`, `..`, `_`, - embedded `..`, separators, tildes, and Unicode, then run a two-identity - filesystem checkpoint/resume and debug trace case that proves distinct files - and successful accepted-normalize hydration. Include selective recomputation - so a required predecessor remains reusable. -- **Grouping:** Independent. - -### STATE-002 — Remove redundant post-decode clones from canonical codecs - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** `chunkmap.Codec.Decode` schema-validates and decodes JSON into a - fresh value, canonicalizes that value, then deep-clones it again before - returning (`internal/framework/chunkmap/codec.go:149`–`171`). - `evidencecontext.Codec.Decode` follows the same sequence - (`internal/framework/evidencecontext/codec.go:79`–`101`), while its - `canonicalize` already deep-clones the decoded document at lines 169–203; - the final `clone` at lines 299–320 therefore makes a second complete copy of - context/reference slices, source-unit structs, and nested metadata. Unlike an - encode caller, the JSON decoder retains no caller-owned object graph that - must be protected from canonicalization. -- **Impact:** Hydrating or consuming canonical artifacts performs avoidable - slice and nested-metadata allocations. The evidence-context path can clone a - large source-derived object graph twice after JSON decoding, increasing peak - allocation and latency without adding an ownership boundary. -- **Recommendation:** Separate canonicalization of an already-owned decoded - value from the defensive-copy entry point used by encoders and external - callers. Return the canonical decoded value directly once validation and - normalization succeed; retain exactly one clone wherever caller-owned input - could otherwise be mutated. -- **Preserve:** Keep schema validation, unknown-field and trailing-value - rejection, digest reconstruction, annotation/context normalization, - encode-time caller isolation, and a fully independently owned decode result. -- **Validation:** Retain and extend ownership tests that mutate both the input - value after encode and the returned value after decode, then use focused - allocation assertions or benchmarks for a nested chunk map and evidence - context to confirm that decode no longer performs the redundant deep copy. -- **Grouping:** Independent. - -### STATE-003 — Publish output through the confined file writer - -- **Severity:** Low -- **Category:** Duplication -- **Evidence:** The CLI's private `writeFileAtomic` - (`internal/cli/run.go:826`–`856`) independently implements the same - create-temp, write, chmod, close, rename, and cleanup sequence as - `internal/core/fileio.writeAtomic` (`internal/core/fileio/fileio.go:105`– - `133`). `writeOutputFiles` calls the CLI copy after its own path checks and - directory creation (`internal/cli/run.go:754`–`787`), while - `fileio.WriteBytes` additionally centralizes relative-path confinement and - symlink-component rejection. Debug summaries, traces, and checkpoints - already use that core primitive; durable output is the divergent state - writer. -- **Impact:** Atomic-publication fixes must be made and tested in two places, - and the copies have already drifted in their confinement checks. The fresh, - exclusively created run directory limits current output exposure, so this is - a maintenance and defense-in-depth issue rather than an observed escape. -- **Recommendation:** After prevalidating all logical output names and - exclusively creating the run directory, publish each file through - `fileio.WriteBytes` (or a narrowly exported equivalent) using the run - directory as root. Remove the CLI atomic-write copy rather than introducing - another generic filesystem abstraction. -- **Preserve:** Validate every logical name before allocating state, refuse an - existing run directory unchanged, retain a newly created partial bundle on a - later write failure, keep output directory/file modes at 0755/0644, and - preserve logical-name context in errors. -- **Validation:** Retain the existing output ordering, collision, permission, - and partial-bundle cases; add a symlink-component case at the shared writer - boundary and verify no temporary file remains after write, chmod, close, or - rename failure. -- **Grouping:** Independent. - -### LLM Runtime, Prompt Filesystems, And Assets - -### LLM-001 — Keep raw provider errors inside the adapter - -- **Severity:** High -- **Category:** Correctness -- **Evidence:** Preparation and ordinary execution failures wrap - `redactPromptKitError` with `%w` at - `internal/framework/llm/promptkit_client.go:140`–`145` and 149–172. The - returned `redactedProviderError` replaces bearer-token text only in its - `Error` method, then exposes the original upstream error unchanged through - `Unwrap` at lines 424–442. The outer error therefore prints a redacted - diagnostic, but `errors.Unwrap`, `errors.Is`, or `errors.As` can recover the - raw PromptKit/provider error, including its original text and concrete type. - This contradicts the adapter contract in `docs/internal/llm.md:177`–`190` - and 231–236, which requires provider-specific errors and credentials to stay - behind the provider-neutral boundary. Capacity exhaustion avoids this - particular chain by mapping the PromptKit sentinel explicitly and formatting - the sanitized diagnostic with `%v`. -- **Impact:** Any framework collaborator, logger, test helper, or future error - serializer that walks the standard error chain can disclose a bearer - credential that normal string formatting appeared to redact. It can also - couple application code to PromptKit/provider error types despite the - documented neutral transport boundary. -- **Recommendation:** Make sanitized upstream diagnostics opaque: do not - implement `Unwrap` and do not wrap a provider error directly after crossing - the adapter boundary. Classify context cancellation, capacity, invalid - structured output, and any other intentionally supported neutral categories - before sanitization, then expose only the corresponding contracts sentinel - plus credential-redacted text. -- **Preserve:** Keep caller-context precedence, prompt context, the - provider-neutral capacity and invalid-output sentinels, full internal - PromptKit error inspection before adaptation, and useful redacted operational - diagnostics. -- **Validation:** Return a typed upstream error containing a bearer secret from - both preparation and generation. Assert that every reachable error-chain - level and formatted form omits the secret, `errors.As` cannot recover the - upstream type, and `errors.Is` still recognizes only the documented context, - capacity, and invalid-output categories. -- **Grouping:** Independent. - -### LLM-002 — Recheck cancellation after scheduler admission - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** A queued scheduler waiter selects between its closed `ready` - channel and `ctx.Done()` at `internal/framework/llm/scheduler.go:50`–`73`. - `grantQueuedLocked` marks the waiter granted and closes `ready` at lines - 103–111. If cancellation and that grant become observable together, Go may - choose the ready case, so `Acquire` returns a permit even though the context - is already canceled. `Scheduler.Run` then invokes `fn(ctx)` immediately at - lines 77–86 without another cancellation check. The focused queued- - cancellation test cancels before releasing the existing permit and therefore - does not exercise the simultaneous grant/cancel branch. -- **Impact:** A scheduler user that does not independently reject an already- - canceled context can begin backend work after the caller canceled while it - was queued. The production PromptKit path receives the canceled context and - ordinarily stops downstream work, and the deferred release prevents a permit - leak, which limits current severity; the scheduler's own cancellation - contract is nevertheless incomplete. -- **Recommendation:** After admission and before dispatch, recheck `ctx.Err()` - while retaining the deferred permit release. Keep `Acquire`'s locked - grant-versus-remove accounting as the owner of queue state; the extra gate - should only prevent the admitted callback from starting. -- **Preserve:** Retain one process-wide FIFO queue, the fixed concurrency - bound, idempotent release functions, cancellation removal for still-queued - waiters, and permit transfer/release after all errors. -- **Validation:** Add a focused grant/cancel race case with a callback that - records invocation and intentionally ignores its context. Prove that an - already-canceled admitted request returns `context.Canceled`, never invokes - the callback, releases its permit, and allows the next FIFO waiter to run; - retain the concurrency, cancellation, and idempotent-release tests under - `-race`. -- **Grouping:** Independent; this is the provider scheduler boundary rather - than RUN-001's pipeline module-dispatch boundary. - -### LLM-003 — Reject duplicate virtual prompt names - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** `promptfs.ModulePromptFS` validates and reads every declared - module file, then assigns its bytes directly into a map at - `internal/framework/promptfs/prompt_fs.go:40`–`58`; shared files use the same - direct assignment at lines 60–80. Two names that are equal after trimming, - leading-slash removal, and cleaning therefore select the same virtual path, - and the later declaration silently replaces the earlier bytes. The asset - registry rejects duplicate flattened roots, but the module manifest boundary - has no equivalent check or focused duplicate test. All fourteen current D&D - manifests declare unique normalized names, so no maintained asset is - presently shadowed. -- **Impact:** A future or programmatically supplied prompt manifest can hash, - register, and execute successfully while using different prompt or shared - fragment bytes than one of its declarations implies. List order silently - decides the winner instead of producing the contextual asset-construction - error expected at startup. -- **Recommendation:** Track each cleaned virtual destination while assembling - `ModulePromptFS` and reject a second declaration before overwriting it. Report - whether the collision is module-owned or shared and include only the safe - virtual name, not file content. -- **Preserve:** Keep module and `sharedassets` namespaces distinct, reject - nested virtual names, read only explicitly declared files, return owned - bytes, and retain manifest order for fingerprinting and diagnostics where it - is semantically relevant. -- **Validation:** Add exact and normalization-equivalent duplicate cases for - module files and for shared files backed by different filesystems. Assert - deterministic contextual rejection while distinct module/shared basenames - remain valid; run the package under `-race`. -- **Grouping:** Independent. - -### LLM-004 — Share the read-only in-memory filesystem mechanics - -- **Severity:** Low -- **Category:** Duplication -- **Evidence:** `internal/framework/llm/asset_registry.go:279`–`430` implements - a complete map-backed read-only filesystem—path cleaning, `Open`, `ReadFile`, - `ReadDir`, directory discovery, sorted entries, cursor reads, file metadata, - and modes. `internal/framework/promptfs/prompt_fs.go:84`–`240` independently - repeats the same mechanics with renamed types. The copies have already - drifted: the asset filesystem represents an empty root as an existing empty - directory while the prompt filesystem reports it missing, and directory - `Read` returns a custom error in one implementation versus `io.EOF` in the - other. -- **Impact:** Filesystem-contract fixes and edge-case tests must be duplicated, - while callers receive subtly different behavior from two byte maps assembled - for the same PromptKit engine. The maintained registries are non-empty, so - the observed drift is a maintenance risk rather than a current prompt load - failure. -- **Recommendation:** Extract one narrow framework-owned read-only byte-map - filesystem with standard `io/fs` behavior and independently owned file - handles. Keep asset flattening, duplicate/root validation, schema selection, - and module/shared manifest construction in their existing domain owners. -- **Preserve:** Retain valid-path enforcement, deterministic directory order, - 0444/0555 metadata, immutable source bytes, independent reader offsets, - contextual domain errors before filesystem construction, and the asset - registry's direct owned `ReadFile` result. -- **Validation:** Run `fstest.TestFS` over empty, single-file, and nested trees; - test root and directory `Open`/`ReadDir`/`Read` behavior, file-handle - independence, sorted entries, missing/invalid paths, modes, and mutation - isolation. Retain both asset-registry and `ModulePromptFS` integration tests. -- **Grouping:** Independent; implement after or alongside LLM-003 without - moving manifest collision policy into the generic filesystem. - -### Generic And Seriatim Modules - -### MOD-001 — Narrow generic integer option decoding - -- **Severity:** Low -- **Category:** Simplicity -- **Evidence:** `internal/modules/generic/chunk/units/chunker.go:138`–`220` - routes only `max_units` and `overlap_units` through a 61-line numeric - conversion family that accepts every signed and unsigned Go integer type, - integral `float64` values, and `json.Number`. Its only production callers are - the two local positive/non-negative wrappers. In contrast, the other integer - option in this family, JSON output's `window_units`, accepts the - configuration-native `int` directly - (`internal/modules/generic/output/json/encoder.go:178`–`188`). The focused - chunker tests reject a fractional float and malformed `json.Number`, but do - not establish a caller or contract for any accepted non-`int` - representation. -- **Impact:** The generic chunker's private option surface is substantially - larger than its two-option configuration contract and silently treats a - floating-point value such as `2.0` as an integer while the adjacent generic - output decoder rejects that representation. Additional numeric branches and - architecture-dependent range logic can drift without providing behavior - used by the maintained configuration path. -- **Recommendation:** Define the supported module-option scalar type at the - configuration boundary and reduce these two options to that representation, - currently `int`, with their existing positive/non-negative and overlap - checks. If a second real option source requires `json.Number` or another - representation, normalize it once at that source rather than retaining a - speculative all-Go-numeric converter in this leaf module. -- **Preserve:** Keep defaults, strict unknown-option rejection, precise option - names in diagnostics, `overlap_units < max_units`, platform-safe values, and - validation/build decoding parity. -- **Validation:** Add focused rejection cases for integral floats and other - unsupported numeric representations, retain boundary/overlap tests, and run - `go test ./internal/modules/generic/chunk/units ./internal/core/config`. -- **Grouping:** Independent. - -### MOD-002 — Reuse compiled response schemas within a prepared validator - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** Every call to - `internal/modules/generic/validate/valid_json_schema.Validator.Validate` - delegates to `validate`, which parses the candidate, reparses the complete - response schema, creates a new `jsonschema.Compiler`, adds the schema - resource, and compiles it before validation - (`validator.go:29`–`56`). The framework constructs one validator instance per - prepared chain position (`internal/framework/pipeline/prepare.go:258`–`299`) - and invokes that same prepared instance for each chunk/artifact candidate - and retry (`runner.go:430`–`489` and `runner_typed.go:458`–`542`). Within a - chain position the active artifact schema is stable, while candidate content - changes. -- **Impact:** A run with many chunks or retries repeatedly pays schema parse, - compiler construction, resource loading, and compilation for identical - schema bytes. The cost is deterministic local CPU/allocation work on every - validation attempt; current LLM-backed workloads limit its overall severity. -- **Recommendation:** Cache the compiled schema on the prepared validator, - keyed by the complete schema identity including its JSON bytes or digest, - and make concurrent first use safe because extract validators can run in - parallel. Continue parsing each candidate independently and preserve support - for a validator instance receiving a different schema rather than assuming - one globally. -- **Preserve:** Retain operational errors for missing/malformed schemas, - ordinary `invalid_json` and `json_schema_invalid` rejections, support for - both chunk and artifact targets, exact candidate ownership, and standalone - use without a preceding `valid_json` validator. -- **Validation:** Add repeated-schema and changed-schema cases, exercise one - validator concurrently, verify malformed-schema errors are stable, and use a - focused benchmark or compiler hook to demonstrate one compilation per - distinct schema; run - `go test -race ./internal/modules/generic/validate/valid_json_schema ./internal/framework/pipeline`. -- **Grouping:** Independent. - -### MOD-003 — Remove unreachable JSON metadata clone helpers - -- **Severity:** Low -- **Category:** Simplicity -- **Evidence:** `cloneMetadata` and `cloneJSONMetadataValue` at - `internal/modules/generic/output/json/encoder.go:497`–`527` form a mutually - recursive deep-clone implementation. Knowledge-graph inbound-call inspection - and a scoped source search find only the calls between those two functions; - no encoder path, registration path, or test reaches either helper. Actual - output ownership is handled by `cloneNormalizeOutputs`, serialized-artifact - cloning, and immediate JSON serialization. -- **Impact:** Thirty-one lines of recursive, type-specific ownership code imply - a boundary that does not exist, add an untested maintenance surface, and can - mislead later changes into choosing the dead helper instead of the encoder's - active clone/serialization paths. -- **Recommendation:** Delete the two unreachable helpers. Do not replace them - with a shared abstraction unless a live metadata owner later demonstrates a - caller. -- **Preserve:** Keep request non-mutation, owned output bytes, exact preservation - of chunk-map annotation numbers, cloned normalized artifacts, and caller - mutation isolation after `Encode` returns. -- **Validation:** Retain the output encoder's request-mutation and annotation - number tests, run `go test ./internal/modules/generic/output/json`, and - confirm no production caller is removed with graph and compiler checks. -- **Grouping:** Independent. - -### Shared D&D Types, Codecs, And Family Mechanics - -### DND-CORE-001 — Remove the unused lossy unit-reference constructor - -- **Severity:** Low -- **Category:** Simplicity -- **Evidence:** `internal/modules/dnd/shared/unit_refs.go:24`–`27` exports - `UnitRefFromString`, discards the error from `parseUnitRefNumber`, and returns - a zero-valued `UnitRef` for every blank, whitespace-padded, non-integer, or - non-positive value. Knowledge-graph inbound-call tracing and a scoped source - search found no production or test caller. The live external boundary is - `UnitRef.UnmarshalJSON` at lines 47–71, which calls the same parser and - correctly propagates its error; `UnitRefFromInt` remains used by that decoder - and focused tests. -- **Impact:** The exported helper advertises a supported string-construction - path whose only distinguishing behavior is to erase invalid-input context. - A future caller could turn malformed model output or test data into a later, - less specific `must be positive` error, while the dead API adds maintenance - surface beside the authoritative strict decoder. -- **Recommendation:** Delete `UnitRefFromString`. If a non-JSON string boundary - later needs construction, expose a parsing function that returns - `(UnitRef, error)` and reuse `parseUnitRefNumber` without discarding errors. -- **Preserve:** Keep string-or-integer JSON compatibility, exact positive source - unit IDs rather than ordinal fallback, original string-versus-number JSON - rendering, and the contextual checks in `ResolveUnitID`. -- **Validation:** Confirm graph and compiler checks find no removed caller; - retain the string/integer/malformed JSON and exact-ID tests in - `internal/modules/dnd/shared/unit_refs_test.go`; run - `go test ./internal/modules/dnd/shared/...`. -- **Grouping:** Independent. - -### NPC, Item, And Location Registries - -### DND-REG-001 — Reject reversed evidence ranges at durable D&D codec boundaries - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** The three registry, three occurrence, spell, scene-description, - combat-turn, and enemy-event integration contracts require that a source - range's start not follow its end - (`docs/integrations/dnd-npc-registry-artifacts.md:32`–`34`, - `dnd-item-registry-artifacts.md:33`–`35`, and - `dnd-location-registry-artifacts.md:34`–`36`; and - `dnd-npc-occurrence-artifacts.md:33`–`36`, - `dnd-item-occurrence-artifacts.md:41`–`43`, - `dnd-location-occurrence-artifacts.md:33`–`35`, - `dnd-spell-artifacts.md:31`–`35`, - `dnd-scene-description-artifacts.md:33`–`35`, - `dnd-combat-turn-artifacts.md:31`–`33`, and - `dnd-enemy-event-artifacts.md:33`–`35`). Nine of the ten durable codecs check - at most that both endpoints are positive - (`internal/modules/dnd/codec/npcregistry/codec.go:96`–`106`, - `codec/itemregistry/codec.go:97`–`107`, and - `codec/locationregistry/codec.go:97`–`107`; and - `codec/npcoccurrences/codec.go:99`–`109`, - `codec/itemoccurrences/codec.go:117`–`127`, - `codec/locationoccurrences/codec.go:100`–`110`, - `codec/spells/codec.go:89`–`99`, - `codec/scenedescriptions/codec.go:101`–`109`, and - `codec/combatturns/codec.go:95`–`106`); the enemy-event codec checks only JSON - field presence and accepts even non-positive endpoints - (`codec/enemyevents/codec.go:86`–`135`). Direct registry references are - decoded and identity-checked by `npcs/registry.loadRegistry`, - `items/registry.loadRegistry`, and `locations/registry.loadRegistry`, but do - not pass through the generated-output source-reference validators. A durable - registry or occurrence artifact with - `{start_unit_id: 2, end_unit_id: 1}` and otherwise valid fields is therefore - accepted; for locations, `validIdentityReference` at - `internal/modules/dnd/locations/identity/identity.go:170`–`171` also treats - that reversed range as a valid identity anchor. The immutable scene- - eligibility registry also decodes approved scene artifacts directly before - projecting ID, range, and kind - (`internal/modules/dnd/scenedescriptions/registry/registry.go:174`–`223`). -- **Impact:** An externally supplied D&D artifact can be accepted as approved - even though its evidence cannot denote the documented forward source - interval. - NPC and item prompt projections then hide the malformed provenance, a - location can derive and retain a durable ID from it, and scene gating can - retain the impossible interval as eligibility metadata. A malformed combat- - turn artifact can likewise be accepted for enemy grounding, whose compact - projection then strips the malformed provenance; only later consumers with - source context may reject it. Generated pipeline outputs remain - protected by their source-reference validator chains, which limits current - exposure. -- **Recommendation:** Add the order-independent structural condition - `start_unit_id <= end_unit_id` to all ten codecs' durable - validation, and make location identity reject reversed anchors as a defense - in depth. - Keep document membership and current-chunk coverage in the existing - validators, where the source document is available. -- **Preserve:** Retain positive exact source-unit identifiers, strict unknown- - field/trailing-value rejection, location identity's earliest canonical - anchor policy, and the separation between source-independent durable shape - validation and source-dependent evidence validation. -- **Validation:** Add codec encode/decode cases for reversed ranges in all ten - families, a location identity case that refuses a reversed-only - anchor, and direct registry, occurrence, spell, scene-eligibility, combat- - turn, and enemy-event reference cases proving malformed referenced JSON is - rejected; run the - codec, identity, registry, spell, scene, occurrence, and assembled CLI suites. -- **Grouping:** Coordinate the enemy-event codec change with DND-COMBAT-001; - the remaining nine codec changes are otherwise independent. - -### DND-REG-002 — Keep extraction evidence inside the current chunk - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** The NPC, item, location, spell, combat-turn, and enemy-event - extractors receive only the current chunk, and all six default extract chains - run their family source-reference validator. Item and location validators require a non-nil - extraction chunk and reject references whose endpoints are not in it - (`internal/modules/dnd/validate/itemregistry/source_refs/validator.go:37`–`55` - and `validate/locationregistry/source_refs/validator.go:37`–`55`). The NPC - validator at `validate/npcregistry/source_refs/validator.go:36`–`53` checks - only that a reference is valid somewhere in the complete source document; it - neither requires `req.Chunk` during extraction nor checks chunk membership. - The spell and combat-turn validators have the same document-only behavior - (`validate/spells/source_refs/validator.go:35`–`51` and - `validate/combatturns/source_refs/validator.go:36`–`60`), while the enemy- - event validator correctly requires an extraction chunk and checks every - unit in each range (`validate/enemyevents/source_refs/validator.go:37`–`99`). - Spell and combat-turn tests exercise - valid, out-of-document, missing-document, malformed-shape, and bounded- - aggregate cases, but supply no stage or chunk and do not cover an existing - off-chunk range (`validate/spells/source_refs/validator_test.go:15`–`73` and - `validate/combatturns/source_refs/validator_test.go:15`–`73`). -- **Impact:** If an NPC, spell, or combat-turn extraction response supplies a - valid unit ID - from another chunk, the candidate can pass evidence validation despite the - model never receiving that passage. Relatedness can also succeed when the NPC - actor, NPC name, or spell appears only at the cited off-chunk range, causing - duplicated - or misattributed provenance across chunk results. The model usually copies - visible unit IDs, which limits the likelihood. -- **Recommendation:** Match the item/location extraction contract: require the - current chunk when `req.Stage` is extract and reject NPC, spell, and combat- - turn references - outside that chunk. Keep whole-document validation for normalize and other - non-extraction validation calls. -- **Preserve:** Retain full-document source-ID/range validation, shape deferral, - bounded aggregate diagnostics, normalization without a chunk, direct factual - third-party mentions, and source-relatedness as an advisory check rather than - an identity gate. -- **Validation:** Add NPC, spell, and combat-turn source-reference cases for an - existing off- - chunk range, a missing extraction chunk, an accepted in-chunk range, and - normalize-stage validation without a chunk; run the affected source-reference - validators, their extractors, and assembled pipeline tests; retain the enemy- - event in-chunk, off-chunk, and missing-chunk cases as the reference behavior. -- **Grouping:** Independent. - -### DND-REG-003 — Index duplicate groups across D&D families - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** NPC preprocessing indexes normalized comparison names in a map, - but `comparisonNameGroups` in - `internal/modules/dnd/normalize/itemregistry/normalizer.go:242`–`259` scans - every previously formed group for each item and recomputes the first member's - comparison key. `exactDuplicateGroups` in - `normalize/locationregistry/normalizer.go:229`–`246` repeats that nested scan - and performs `reflect.DeepEqual` over canonical source-reference slices for - each candidate group. Enemy-event normalization likewise scans all retained - events for every record and calls exact equality, which recanonicalizes both - evidence lists (`normalize/enemyevents/normalizer.go:207`–`227` and - `enemyevents/enemyevents.go:42`–`64`); its invariant validator repeats a - previous-event scan at `validate/enemyevents/invariants/validator.go:138`–`145`. - The knowledge graph reports loop depth two and transitive loop depth four for - enemy `collapseDuplicates`. With distinct records, all four paths are - quadratic. -- **Impact:** Large merged registries or enemy observation lists spend - avoidable deterministic CPU in - normalization, with the location cost also proportional to citation-list - comparisons. Normal artifact sizes bound the impact, and registry - reconciliation's later LLM request dominates its two paths today, so the - issue is low severity. -- **Recommendation:** Preserve first-seen group order while maintaining a local - index from the complete duplicate identity to its group position. Use the - existing comparison key for items and an exact, collision-safe key over the - comparison name plus canonical source-reference sequence for locations; - apply the same collision-safe complete identity index to enemy events in both - normalization and invariant validation. Verify equality on any hash - collision rather than using lossy concatenation. -- **Preserve:** Item duplicates remain name-identity duplicates regardless of - evidence; locations collapse only equal comparison names with exactly equal - canonical evidence; group/member order, input-index provenance, warning - scopes, and later proposal-only semantic reconciliation remain unchanged. - Enemy events continue to collapse only equal normalized subject identity, - kind, and complete canonical evidence; different outcomes, evidence, and - repeated observations remain distinct. -- **Validation:** Add many-distinct and repeated-key cases that compare output - groups and warning order with current fixtures, plus a focused benchmark or - comparison-count hook demonstrating linear expected grouping work; run the - item and location normalizer tests plus enemy normalizer and invariant tests. -- **Grouping:** Independent. - -### DND-REG-004 — Select location identity anchors without sorting - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** Location identity depends only on the least valid source - reference. `earliestReference` nevertheless calls `canonicalReferences`, - which allocates a full copy, sorts it, and deduplicates it - (`internal/modules/dnd/locations/identity/identity.go:137`–`167`). - `ValidateRegistry` calls `earliestReference` once to check evidence and then - calls `DeriveID`, which invokes it again for every syntactically valid record - (lines 106–121). Normalization has already canonicalized each location's - references before deriving its ID, but pays the same second ordering pass. -- **Impact:** Each validation performs two `O(r log r)` allocations/sorts per - location to obtain one minimum, and normalization adds another sort after - source-order canonicalization. Citation counts are bounded in ordinary - transcripts, so this is a localized allocation and CPU issue. -- **Recommendation:** Implement `earliestReference` as a non-mutating linear - minimum selection using the exact current source-ID/start/end comparator, and - compute that anchor once per record during identity validation before ID - comparison. Do not reuse document-position `SourceRefOrder`, whose ordering - contract differs from durable location identity. -- **Preserve:** Keep order-independent IDs, filtering of malformed anchors, - lexicographic source-ID then numeric start/end selection, same-name/different- - anchor distinction, exact compact JSON hash input, and input non-mutation. -- **Validation:** Retain the permuted-reference and same-name/different-anchor - identity fixtures, add mixed valid/invalid and tie-order cases, and use an - allocation or benchmark assertion to demonstrate one linear pass per record; - run the location identity, registry, and normalizer tests. -- **Grouping:** Independent. - -### NPC, Item, And Location Occurrences - -### DND-OCC-001 — Align item occurrence evidence fields with the shared prompt - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** The shared model-visible evidence instruction tells every D&D - extractor to return integer `start_unit_id` and `end_unit_id` fields - (`assets/dnd/shared/prompts/common-dnd-extraction-evidence.md:1`–`4`). NPC and - location occurrence extraction follow that convention, but the item - occurrence private response DTO instead requires `start_segment` and - `end_segment` - (`internal/modules/dnd/extract/itemoccurrences/model.go:16`–`18`), and its - strict structured-output schema requires the same incompatible names - (`assets/dnd/item-occurrences/schemas/dnd_item_occurrences_llm.v1.json:20`–`29`). - The representative generated pipeline fixture must likewise emit the - segment-named fields to pass - (`internal/cli/dnd_enemy_events_contract_test.go:318`–`334`). -- **Impact:** The prompt and enforced response schema give the model - contradictory instructions at one structured-output boundary. A model that - follows the shared evidence instruction produces missing required fields and - disallowed unknown fields, causing an otherwise valid item occurrence - candidate to be rejected and retried. Provider-side schema steering may - conceal the mismatch for some models, but cannot make the prompt contract - coherent. -- **Recommendation:** Rename the item occurrence private response fields and - schema properties to `start_unit_id` and `end_unit_id`, update the adapter - and fixtures, and verify that the affected response-schema fingerprint - changes. Add an assembled-prompt contract proving every evidence field named - by the item response schema matches the shared instruction. -- **Preserve:** Keep source IDs out of model output, inject the current source - identity locally, retain exact positive transcript unit IDs, strict - structured decoding, current-chunk evidence validation, and the unchanged - durable occurrence wire shape. -- **Validation:** Retain item extractor malformed-response and citation tests, - update the generated multi-family CLI fixture to use unit-named endpoints, - add the prompt/schema alignment assertion, and run the item occurrence and - CLI suites. -- **Grouping:** Independent. - -### DND-OCC-002 — Remove unused campaign references from NPC occurrence normalization - -- **Severity:** Low -- **Category:** Simplicity -- **Evidence:** NPC occurrence normalization declares the optional campaign - `glossary`, `party`, `players`, and deprecated `roster` slots as material used - for occurrence disambiguation - (`internal/modules/dnd/normalize/npcoccurrences/normalizer.go:38`–`43`) and - includes them beside the required registry in `ReferenceSlots` (lines - 252–263). Construction retains only an NPC registry resolver (lines 51–67), - and normalization resolves and uses only that registry plus the source - document (lines 99–123). Item and location occurrence normalizers expose - only their required family registry. -- **Impact:** Bindings that cannot affect NPC normalization are nevertheless - admitted into resolved profiles, materialized, recorded in manifests and - dependency identities, and can invalidate checkpoints when their content - changes. The descriptions also imply a disambiguation behavior the - deterministic normalizer does not implement. -- **Recommendation:** Remove the four campaign slots and their descriptions - from the NPC occurrence normalizer, leaving only required `npc_registry`. - Keep campaign context on extraction, where it is model-visible and can - actually influence selection. -- **Preserve:** Retain exact registry ID/name validation and canonicalization, - operation-time registry overrides, source-reference ordering, exact duplicate - collapse, bounded warnings, and all extraction reference slots. -- **Validation:** Update module-spec, reference-binding, manifest, and - checkpoint dependency tests to require exactly the registry slot during - normalization; prove extraction still accepts campaign context; run NPC - occurrence and assembled CLI tests. -- **Grouping:** Independent. - -### DND-OCC-003 — Reuse canonical item occurrence evidence - -- **Severity:** Low -- **Category:** Efficiency -- **Evidence:** Item normalization canonicalizes each occurrence's evidence - once in `normalizeOccurrence` - (`internal/modules/dnd/normalize/itemoccurrences/normalizer.go:174`–`195`), - then sorts those records through `itemoccurrences.Less` (lines 155–157) and - builds duplicate keys through `ExactIdentity` (lines 220–229). `Less` - canonicalizes both reference slices again at its final tie-breaker - (`internal/modules/dnd/itemoccurrences/itemoccurrences.go:95`–`125`), while - `ExactIdentity` canonicalizes each slice again at lines 145–163. The - invariants validator first verifies canonical order and uniqueness, then - calls both helpers again - (`internal/modules/dnd/validate/itemoccurrences/invariants/validator.go:65`–`95`). -- **Impact:** Tie-heavy merged lists repeatedly allocate, sort, and deduplicate - evidence that the normalizer has already canonicalized; normalized artifact - validation repeats the same work. Transcript and LLM costs dominate ordinary - runs, so this is a localized low-severity deterministic cost. -- **Recommendation:** Add canonical-input comparator and identity-key paths, or - precompute canonical sort/dedup keys per normalized record, and use them only - after the caller has established canonical evidence. Retain the current - defensive public helpers for arbitrary or malformed candidates that still - need literal-fallback ordering. -- **Preserve:** Keep exact canonical ordering, nil and invalid-reference - diagnostic behavior, holder and quantity distinctions, collision-safe - identity keys, stable input provenance for warnings, and non-mutating helper - contracts. -- **Validation:** Compare optimized normalization and invariant results against - the existing permuted/duplicate/invalid evidence fixtures; add a tie-heavy - benchmark or canonicalization-count hook showing one evidence canonicalization - per normalized record; run item occurrence normalize/validator tests. -- **Grouping:** Independent. - -### Spells, Scene Chunking, And Scene Descriptions - -### DND-SCENE-001 — Expose catalog aliases to spell extraction - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** The overlay contract says optional aliases contribute to spell - recognition (`docs/integrations/dnd-spell-catalog-overlays.md:3`–`6` and - 57–68), and the effective catalog correctly maps each accepted alias to its - canonical spell (`internal/modules/dnd/spells/catalog/effective.go:215`–`247`). - The extractor's model-visible projection serializes only - `EffectiveCatalog.CanonicalNames()` as `spell_names` - (`internal/modules/dnd/extract/spells/catalog_prompt_input.go:13`–`28`), while - its prompt explicitly says aliases are absent and requires exact canonical - spelling (`assets/dnd/spells/prompts/spell-catalog.md:1`–`6`). Focused and - assembled tests codify the omission by rejecting `Emberfall Aegis` from the - prompt even though the configured overlay maps it to `Aegis of Emberfall` - (`internal/modules/dnd/extract/spells/extractor_test.go:88`–`103` and - `internal/cli/spell_catalog_identity_contract_test.go:412`–`414`). The - downstream catalog validator and normalizer can resolve an alias only if the - model already returns it; they cannot teach the model that alias-only - transcript language denotes the configured spell. -- **Impact:** A real cast expressed only with a campaign alias can be omitted or - rejected because the extraction model receives neither the alias nor its - canonical mapping. This silently defeats a documented purpose of overlay - configuration and can lose durable spell-cast occurrences; canonical names - and base-catalog casts remain unaffected. -- **Recommendation:** Project a deterministic source-free list of canonical - spell names with their recognized aliases into `spell_catalog`, and instruct - the model to return the associated canonical spelling. Continue to omit - catalog source metadata, paths, licenses, rules text, and provenance. Treat - the projection shape and prompt change as semantic fingerprint changes. -- **Preserve:** Keep overlays recognition-only rather than evidence, retain - strict collision rejection and canonical display names, require current- - transcript cast evidence and an in-world caster, preserve NPC provenance - separation, and keep the existing prompt order and cache boundaries. -- **Validation:** Add base and overlay projection tests for stable canonical- - alias mappings, repeated aliases, and metadata exclusion; update the - assembled prompt contract to require `Emberfall Aegis` only as an alias of - `Aegis of Emberfall`; retain catalog rejection, normalization, checkpoint- - invalidation, and retry tests; run the spell extractor, catalog, normalizer, - validator, and CLI suites. -- **Grouping:** Independent. - -### DND-SCENE-002 — Make D&D normalization and advisory diagnostics complete and bounded - -- **Severity:** Low -- **Category:** Correctness -- **Evidence:** The maintained D&D convention says deterministic normalizers - issue bounded warnings for changes and collapsed duplicates - (`docs/internal/dnd.md:129`–`132`). Spell normalization emits a warning for - every canonicalized or unresolved name and changed reference list, then one - for every duplicate group, and returns the concatenated slice directly - (`internal/modules/dnd/normalize/spells/normalizer.go:89`–`105`, 108–149, - and 177–226); unlike the occurrence and registry normalizers, it never calls - `diagnostics.LimitWarnings`. Scene-description normalization has the inverse - gap: it trims title/summary, reorders records, and removes exact duplicates - (`normalize/scenedescriptions/normalizer.go:70`–`124`) but always returns the - value without any warnings (lines 53–68). Its primary test performs all three - mutations without asserting diagnostic provenance - (`normalizer_test.go:15`–`43`). Combat-turn normalization also emits per- - actor, per-reference, per-reorder, and per-duplicate-group warnings without - applying the shared limiter (`normalize/combatturns/normalizer.go:131`–`188` - and 235–273). Its advisory relatedness validator returns one warning per - unrelated turn without a limiter - (`validate/combatturns/source_relatedness/validator.go:45`–`67`), whereas - both enemy-event equivalents use `diagnostics.LimitWarnings`. -- **Impact:** A large spell list can publish an unbounded number of warnings, - inflating manifests, debug artifacts, output files, and checkpoint payloads. - Combat lists can have the same warning amplification. Scene normalization - silently changes accepted durable content, so operators - cannot distinguish an unchanged scene list from repaired whitespace/order or - collapsed duplicates. Artifact values remain deterministic and valid. -- **Recommendation:** Pass spell and combat-turn normalization warnings and - combat-turn relatedness warnings through the shared deterministic limiter - with stable omission reasons. Add bounded scene warnings that - distinguish prose trimming, canonical reordering, and exact duplicate - collapse while retaining stable input scopes and order. Emit no warning for - an already canonical value. -- **Preserve:** Keep current normalized values, source-position ordering, - conflict rejection, duplicate identities, input immutability, per-record - diagnostic order below the limit, and idempotent warning-free second passes. -- **Validation:** Add spell, combat-normalizer, and combat-relatedness cases - beyond `diagnostics.MaxWarnings` that assert stable omission summaries, and - scene cases for each mutation, combined overflow, canonical input, and - idempotence; run all affected normalizer/validator suites and assembled - output/checkpoint warning tests. -- **Grouping:** Independent. - -### Combat Turns And Enemy Events - -### DND-COMBAT-001 — Enforce enemy-event semantics at the durable codec boundary - -- **Severity:** Medium -- **Category:** Correctness -- **Evidence:** The enemy-event contract and embedded durable schema require a - non-empty subject, one of five event kinds, at least one source reference, - and a non-empty source ID with positive endpoints - (`docs/integrations/dnd-enemy-event-artifacts.md:19`–`35` and - `internal/modules/dnd/codec/enemyevents/assets/schemas/dnd_enemy_events.v1.json:4`–`34`). - `Codec.Decode` checks strict JSON and literal field presence, but - `validateRequiredJSONFields` does not enforce any of those value constraints; - `Codec.Encode` checks only that the event and reference slices are non-nil - (`codec/enemyevents/codec.go:52`–`95` and 98–160). The focused codec test - explicitly proves durable `Decode` accepts a whitespace name, unsupported - kind, blank source ID, zero start, and negative end - (`codec/enemyevents/codec_test.go:76`–`92`). The combat-turn codec, by - contrast, enforces all equivalent value constraints except the separately - recorded reversed-range condition (`codec/combatturns/codec.go:80`–`108`). -- **Impact:** A direct enemy-event artifact decode can report contract-invalid - JSON as approved typed data. More importantly, the supported validator- - override surface can replace both family validation chains; a model response - with these invalid values can then reach durable output because the final - codec encode does not re-establish its published schema. Default chains - reject the values, so maintained production configuration is protected. -- **Recommendation:** Preserve candidate encode/decode as the permissive retry - boundary, but make durable `Encode` and `Decode` apply one shared value - validator covering the schema's name, kind, non-empty references, source ID, - and positive endpoint constraints. Also apply the forward-range check in - DND-REG-001. Keep the raw-object presence pass on decode where omitted versus - zero-valued JSON fields must remain distinguishable. -- **Preserve:** Retain strict unknown-field and trailing-value rejection, - defensive source-reference ownership, empty top-level event lists, candidate - preservation before validators, and document/chunk membership checks in the - source-aware validator rather than the codec. -- **Validation:** Replace the semantic-acceptance durable codec case with - paired candidate-preservation and durable-rejection cases for every field, - including empty and reversed reference ranges. Add an assembled lane case - showing permissive validator overrides still cannot publish schema-invalid - enemy events; run the codec, enemy-event, pipeline, and CLI suites. -- **Grouping:** Coordinate with DND-REG-001; that finding owns the common - forward-range gap, while this finding owns enemy-event schema enforcement. - -## D&D Convention Matrix - -The matrix records the frozen production convention after the lane-specific -reviews. `E`, `M`, and `N` mean extract, merge, and normalize. Every extractor -is LLM-backed, every merger is the deterministic typed `appendorder` merger, -and every family also registers the typed deterministic `noop` normalizer as an -explicit alternate. `B` is the ordered default chain -`valid_json → shape → source_refs → valid_json_schema → source_relatedness`; -notations such as `B + identity` name the check inserted after `shape` and -before `source_refs`. `C` means the optional campaign-context slots `glossary`, -`party`, `players`, and deprecated `roster`. Every durable codec is -family-owned, uses media type `application/json`, embeds its own v1 durable -schema, publishes count metadata, and has a registered direct-source-reference -evidence projector. - -| Family | Durable kind / Go type | Modules and execution class | Default validator chains (E / N) | Reference dependencies (E / N) | Codec, prompt, and schema ownership | Documented exception and review result | -| --- | --- | --- | --- | --- | --- | --- | -| Spells | `dnd/spell-list` / `dnd.SpellList` | `dnd/spells` (LLM) → typed `appendorder` (deterministic) → `dnd/spells` (deterministic) | `B + catalog` / `B + catalog` | `C` plus optional `spell_catalog` and `npc_registry` / optional `spell_catalog` | `codec/spells`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: catalog and NPC grounding remain source-free recognition context; canonicalization, retry, and checkpoint identities are deterministic. DND-REG-001, DND-REG-002, DND-SCENE-001, and DND-SCENE-002 record codec, chunk-evidence, alias-projection, and warning gaps. | -| NPC registry | `dnd/npc-registry` / `dnd.NPCRegistry` | `dnd/npc-registry` (LLM) → typed `appendorder` (deterministic) → `dnd/npc-registry` (LLM) | `B` / `B + identity` | `C` / none | `codec/npcregistry`; extractor and normalizer own prompts; extractor owns its response schema, while normalize uses the shared private entity-reconciliation schema | Confirmed: normalized comparison-name identity, deterministic exact duplicate consolidation, proposal-only semantic groups, collision-safe application, retry/fallback, and immutable name/identity projections; DND-REG-001 and DND-REG-002 record evidence-boundary gaps. | -| Combat turns | `dnd/combat-turn-list` / `dnd.CombatTurnList` | `dnd/combat-turns` (LLM) → typed `appendorder` (deterministic) → `dnd/combat-turns` (deterministic) | `B` / `B + invariants` | `C`, optional `npc_registry`, required `scene_descriptions` / optional `npc_registry` | `codec/combatturns`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: exact combat classification alone enables prompting; exact non-combat and unavailable classifications produce accepted empty lists, with one warning only for unavailable classification. NPC names remain optional source-free grounding. DND-REG-001, DND-REG-002, and DND-SCENE-002 record codec, chunk-evidence, and warning gaps. | -| Item occurrences | `dnd/item-occurrence-list` / `dnd.ItemOccurrenceList` | `dnd/item-occurrences` (LLM) → typed `appendorder` (deterministic) → `dnd/item-occurrences` (deterministic) | `B + registry` / `B + registry + invariants` | `C` plus required `item_registry` / required `item_registry` | `codec/itemoccurrences`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: exact names-only registry resolution is all-or-nothing, registry provenance never becomes evidence, and quantity/holder rules survive canonical ordering and duplicate collapse. DND-REG-001, DND-OCC-001, and DND-OCC-003 record bounded codec, prompt/schema, and repeated-work gaps. | -| Item registry | `dnd/item-registry` / `dnd.ItemRegistry` | `dnd/item-registry` (LLM) → typed `appendorder` (deterministic) → `dnd/item-registry` (LLM) | `B` / `B + identity` | `C` / none | `codec/itemregistry`; extractor and normalizer own prompts; extractor owns its response schema, while normalize uses the shared private entity-reconciliation schema | Confirmed: name identity, exact duplicate evidence union, proposal-only aliases, collision safety, and denomination/type-preserving currency gate; DND-REG-001 and DND-REG-003 record boundary/grouping gaps. | -| NPC occurrences | `dnd/npc-occurrence-list` / `dnd.NPCOccurrenceList` | `dnd/npc-occurrences` (LLM) → typed `appendorder` (deterministic) → `dnd/npc-occurrences` (deterministic) | `B + registry` / `B + registry + invariants` | `C` plus required `npc_registry` / `C` plus required `npc_registry` | `codec/npcoccurrences`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: names-only selection resolves to exact registry pairs, registry provenance cannot become occurrence evidence, `mentioned` remains factual, and current-source evidence is canonicalized before exact duplicate collapse. DND-REG-001 and DND-OCC-002 record the codec and unused-normalizer-reference gaps. | -| Scene descriptions | `dnd/scene-description-list` / `dnd.SceneDescriptionList` | `dnd/scene-descriptions` (LLM) → typed `appendorder` (deterministic) → `dnd/scene-descriptions` (deterministic) | `B` / `B + invariants` | optional `glossary`, `party`, and `players` / none | `codec/scenedescriptions`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: one model classification is mapped onto the current chunk's local ID and exact range, while an immutable source-free ID/range/kind projection alone controls later eligibility. DND-REG-001 and DND-SCENE-002 record codec and warning gaps. | -| Enemy events | `dnd/enemy-event-list` / `dnd.EnemyEventList` | `dnd/enemy-events` (LLM) → typed `appendorder` (deterministic) → `dnd/enemy-events` (deterministic) | `B + engagements` / `B + invariants` | `C` plus required `npc_registry`, `scene_descriptions`, `combat_turns`, and `npc_occurrences` / required `npc_registry` | `codec/enemyevents`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: exact combat gating precedes prompt grounding; compact NPC, combat-turn, and opponent-occurrence projections contain no evidence or opaque IDs; extraction admits one engagement per comparison identity, while normalization preserves later observations and orders them by chronology, subject, kind, and evidence. DND-REG-001, DND-REG-003, and DND-COMBAT-001 record codec and duplicate-work gaps. | -| Location registry | `dnd/location-registry` / `dnd.LocationRegistry` | `dnd/location-registry` (LLM) → typed `appendorder` (deterministic) → `dnd/location-registry` (LLM) | `B` / `B + identity` | `C` / none | `codec/locationregistry`; extractor and normalizer own prompts; extractor owns its response schema, while normalize uses the shared private entity-reconciliation schema | Confirmed: comparison name plus earliest canonical evidence identity, same-name/different-anchor preservation, proposal-only aliases, and immutable context-qualified selectors without durable IDs; DND-REG-001, DND-REG-003, and DND-REG-004 record bounded gaps. | -| Location occurrences | `dnd/location-occurrence-list` / `dnd.LocationOccurrenceList` | `dnd/location-occurrences` (LLM) → typed `appendorder` (deterministic) → `dnd/location-occurrences` (deterministic) | `B + registry` / `B + registry + invariants` | `C` plus required `location_registry` / required `location_registry` | `codec/locationoccurrences`; extractor owns its prompt and private response schema; normalizer has no prompt | Confirmed: source-free contextual selectors disambiguate same-name locations without exposing durable IDs, unresolved selections reject the whole response, registry evidence remains separate, and explicit kind precedence preserves speculation/mention distinctions. DND-REG-001 records the codec gap. | - -Shared convention review classified the codec surface as safe typed adapters, -not a missing artifact-codec framework. `candidatejson` is the natural owner for -single-value JSON encoding and strict decoding (including unknown-field and -trailing-value rejection), while each codec retains exact Go type, kind, -metadata, embedded durable schema, and artifact-specific required-field or -semantic validation. Candidate encode/decode clones are limited to the two -families with retained pointer/slice ownership (`ItemOccurrenceList` and -`EnemyEventList`); schema bytes are owned because every `embed.FS.ReadFile` -call returns a fresh byte slice. The generic candidate helper intentionally -does not absorb family validation or durable-schema policy. - -Source-reference responsibilities are likewise separated by semantics: -`SourceRefOrder` owns document-position ordering, exact equality-based -deduplication, invalid-reference preservation for diagnostics, and nil versus -owned-empty behavior; `UnitRef.UnmarshalJSON` owns strict model-facing string -or integer parsing; `CitationResolver` owns current-document range expansion; -family validators own admissibility and evidence rules; and evidence projectors -copy only direct artifact references. Extractor-local response adapters remain -typed because their private response DTOs differ; replacing them with -reflection or callbacks would hide field ownership without consolidating -policy. DND-CORE-001 records the one dead constructor outside these live paths. - -Registration is explicit and complete for all ten codecs, extractors, mergers, -normalizers, noop alternates, evidence projectors, validator capabilities, and -default chains, plus the separate scene chunker. Prompt registration covers -every LLM extractor, the scene chunker, the three LLM registry normalizers, the -shared reconciliation schema, and the fallback profile. The registrar validates -every registry and the asset registry before mutation, registers in a fixed -order, and wraps failures with the exact D&D component name; a later failure -can leave the caller-supplied registries partially populated, but production -composition treats registration failure as terminal and no rollback contract -is documented. - -The shared registry resolver correctly distinguishes absent construction views, -empty generated-reference placeholders, operation-time overrides, raw-content -cache identity, and semantic identity while retaining owned loaded values. The -entity-reconciliation helper keeps durable IDs out of prompts, rejects invalid -or colliding selectors and overlapping groups, bounds transcript context, and -returns owned safe groups. Shared comparison policy is versioned, and shared -diagnostics bound displayed issues and warning counts. The registry and -occurrence reviews now confirm the noun-family identity, projection, category, -and merge decisions; scene/spell policy and combat/enemy behavior remain -assigned to their subsequent reviews. - -Finally, repeated `ManifestMetadata` and `CheckpointFingerprints` methods remain -module-local because their exact policy names, prompt/schema hashes, reference -projection digests, and ordering are checkpoint semantics. Small `Register`, -`New`, and `DecodeOptions` methods preserve typed registry construction, -module-local error context, dependency validation, and strict option surfaces; -parameterizing them would trade visible policy for callback-heavy helpers. The -shared prompt manifest/hash, candidate JSON, registry resolver, diagnostics, -source ordering, and entity reconciliation packages already own the exact -mechanics that recur without erasing those distinctions. - -## Intentional Complexity And Duplication To Preserve - -- `internal/modules/generic/register.Register`, - `internal/modules/seriatim/register.Register`, and - `internal/modules/dnd/register.Register` deliberately expose the same small - registrar shape while retaining family-local registration policy and - diagnostics. Combining them would move extension ownership out of the domain - registrars and weaken the composition boundary established by ADR-0004. -- Seriatim's `decodeOptionalSegmentID`, `decodeOptionalNumber`, and timestamp - checks deliberately keep separate external number handling at the input - adapter. Segment IDs accept only positive canonical decimal JSON numbers or - strings, while optional timestamps accept finite non-negative decimals and - preserve their lexical `json.Number` form in generic metadata. Replacing - these with a permissive generic number coercer would weaken the documented - source contract and leak an external-format decision into `core/source`. -- `generic/valid_json` and `generic/valid_json_schema` both detect malformed - JSON, but remain useful separate serialized-validator capabilities. The - former is a cheap format-only boundary; the latter must parse an instance to - apply an independently supplied schema and can be selected without the - former. MOD-002 concerns repeated compilation within one schema validator, - not merging the two module identities or requiring a particular chain. -- `internal/modules/dnd/register.registerModules`, `registerEvidence`, - `registerValidators`, and `registerDefaultChains` use explicit typed - registration lists. That repetition preserves artifact Go types, - module-specific validator order, and registrar-owned production policy. - Individual shared mechanics do not justify replacing these lists with a - dynamically typed registration engine. -- Combat-turn and enemy-event extractors deliberately own separate explicit - scene gates. Both consult the same immutable eligibility registry before any - LLM call, but the enemy lane must then resolve three required source-free - grounding projections while combat turns have only optional NPC grounding. - A callback-driven shared extractor would obscure required-reference and - empty-result ownership without removing meaningful policy duplication. -- Enemy engagement uniqueness deliberately belongs only to extraction. One - chunk represents one classified combat scene, so a comparison-key map can - reject repeated `engaged` observations there; the merged/normalized artifact - may contain later engagements for the same subject in separate scenes and - must preserve them rather than apply a terminal-state model. -- `internal/framework/pipeline.RegisterArtifactCodec` and - `exactTypedValue` perform apparently repetitive exact-type checks around - private erasure. The checks deliberately turn incompatible values into - errors at each erased boundary rather than permitting a panic or accepting a - near-matching type, preserving ADR-0003. -- `internal/cli.runPipelineCommand` is a large linear orchestrator, but its - ordering is policy: syntax and config rejection precede run identity and - debug allocation; resolution and profile inspection precede module - preparation and input parsing; framework success precedes durable output; - and terminal debug publication precedes the optional JSON receipt. Existing - helpers isolate reference selection, recomputation, stores, output, result - encoding, and terminal error precedence. A generic lifecycle abstraction - would hide physical-state allocation and publication boundaries; bounded - parsing fixes such as CFGCLI-002 should not reorganize that lifecycle. -- `internal/core/config.validatePipelineProfiles` explicitly walks pipelines, - ordered steps, lanes, bindings, and references. Its nested structure mirrors - the public configuration shape and retains the nearest pipeline/step/lane - context in errors. Replacing it with a reflection-driven validator would - weaken those diagnostics and the presence-aware file-model boundary. -- `internal/cli.selectedReferenceTargets` and `recomputePolicy` perform - explicit resolved-shape traversals for distinct CLI policies: disambiguating - reference selectors against selected module capabilities, and computing the - forward forced/backward reusable checkpoint closure. Keeping these typed - traversals separate avoids adding command syntax or checkpoint policy to the - framework resolver. -- `pipeline.ResolvePipeline` and `resolveArtifactLane` are long, but their - linear sections retain the authoritative composition order: normalize - identity, select lanes, prove capabilities and exact artifact variants, - resolve stage-local references and validator chains, apply effective LLM - profiles, validate options, and only then compute the digest. Splitting these - checks into a generic stage engine would erase the different input, chunk, - typed-lane, validator, and output contracts. PIPE-001 is a bounded - normalization fix and should not reorganize this sequence. -- `pipeline.validateGeneratedBindings` has deeply nested traversal because it - proves a cross-step selector against ordered producer identity, the target's - declared slot, accepted artifact kinds, registered codec, and accepted media - types in one pass. Those checks are distinct static composition invariants; - materialized bytes, runtime handoff construction, and checkpoint hydration - remain separate runtime owners. -- The stage, validator, codec, and evidence registries intentionally use - private typed entries and small stage-specific lookup methods. Their - repetition preserves compile-time generic types until a narrow erased - closure, exact artifact-kind variant selection, and stage-specific - diagnostics. PIPE-002 concerns redundant request copies around those - closures, not the typed registry split itself. -- Generated-reference handoff deliberately decodes and re-encodes an accepted - normalized artifact through the registered producer codec even though fresh - outputs were already serialized. The same boundary also receives hydrated - checkpoint artifacts, so canonicalizing once per unique producer verifies - exact kind, schema, media type, and bytes before fanout. REF-002 removes only - repeated output discovery; it must not bypass this codec check. -- Operation paths clone reference sets for each module request while retaining - a separate pristine set for dependency fingerprints and validators. That - apparent duplication isolates module mutation across chunks and retries and - keeps validators on authoritative inputs. PIPE-002 applies only to adjacent - construction-builder copies and should not remove these operation-time - ownership boundaries. -- `Runner.Run` is a long linear coordinator, but its sequence is the runtime - contract: source state precedes chunk planning; a rejected chunk plan skips - lanes but remains an encodable ordinary outcome; ordered steps are barriers; - evidence is built only from accepted normalized artifacts; and logical output - encoding is last. RUN-001 requires narrow cancellation gates and should not - replace that readable lifecycle with a generic stage engine. -- Extract jobs and lane continuations deliberately use separate pools, each - bounded by the resolved worker count. This permits a completed lane to enter - its serial merge/normalize continuation while other lanes are still - extracting, without letting either class grow with lane or chunk count. The - two pools should not be collapsed merely to make the configured limit a - process-wide semaphore; provider calls have their own shared scheduler. -- Chunk, extract, merge, and normalize retry closures repeat candidate debug, - rejection, and warning mechanics around different typed operations and - checkpoint transitions. Their common retry counter and cancellation policy - appropriately live in `runWithRetry`, while stage-specific serialization, - normalize fallback, and state recording remain explicit. RUN-003 calls for a - small terminal-warning result, not a parameter-heavy generic stage runner. -- `synchronizedCheckpointRecorder`, `synchronizedDebugRecorder`, and - `synchronizedLLMDebugRecorder` intentionally serialize collaborators whose - contracts do not promise concurrent safety. Each adapter owns one lock and - invokes only its wrapped collaborator, so there is no framework lock-order - cycle; removing them would push concurrency requirements into filesystem and - test implementations. -- Filesystem checkpoint recorder and loader methods intentionally repeat the - stage-shaped interface surface. Each small adapter fixes a stage, manifest - status, dependency set, and payload codec before delegating to shared - manifest validation or publication. Collapsing them into a reflection- or - string-driven state engine would weaken typed call sites and contextual - validation; STATE-001 concerns only their shared path-component encoding. -- The chunk-plan store intentionally does not use the general `fileio` writer. - Its source-addressed directory is an independently replaceable cache entry, - and its `os.Root`-relative implementation rejects non-directory digest - entries, non-regular or symlinked plans, named pipes, and replacement races, - while syncing a private temporary file before rename. Those stronger - cache-entry mechanics should remain local rather than being generalized into - output/debug/checkpoint publication. -- Source metadata, accepted chunk maps, and evidence contexts retain separate - clone helpers because their ownership graphs and canonical invariants differ: - source metadata handles nested dynamic values and cycles, chunk maps own - annotations and chunk slices, and evidence contexts own source units and - metadata. STATE-002 removes only copies of an already-owned decoded graph; it - should not replace these helpers with reflection or remove encode-time - isolation. -- `PromptKitClient.CompleteStructured` deliberately keeps prompt preparation, - the frozen prepared-detail snapshot, provider execution, PromptKit schema - validation, application decode, profile recording, and debug material - assembly explicit. Their order proves that debug and generation describe one - prepared request and that malformed provider output cannot become a typed - result. LLM-001 changes only the outward error chain; it should not hide this - sequence behind a generic transport pipeline. -- The CLI profile inspector and production PromptKit client intentionally own - separate engines while sharing the same profile-source option construction. - Inspection must resolve configured, fallback, built-in, and local-backend - policy without credentials, provider contact, or capacity admission; - reusing the runtime engine would blur that preflight boundary. -- Module prompt manifests and PromptKit YAML message lists explicitly enumerate - module-owned files, shared fragments, stable reference blocks, transcript - blocks, lane-specific grounding, and final instructions. This duplication is - content policy: it makes exact model-visible byte order and cache-control - breakpoints reviewable per workload. LLM-003 adds collision rejection, and - LLM-004 shares only the underlying filesystem mechanics; neither should - generate manifests dynamically or infer prompt order from filenames. -- The application scheduler and PromptKit backend limits intentionally remain - layered. The scheduler is the one process-wide provider-call bound across - profiles and modules, while PromptKit owns selected-backend capacity and maps - its exhaustion through a provider-neutral sentinel. LLM-002 closes an - admission/cancellation race without combining these limits or moving provider - capacity policy into the pipeline worker pools. -- `internal/modules/dnd/chunk/scenes.planFromResponse` intentionally keeps the - whole-source coverage policy explicit in one pass: it resolves opaque unit - IDs through the shared document index, compares document positions rather - than numeric IDs, rejects reversed ranges, gaps, and overlaps, and requires - exact first-to-last coverage before the framework independently canonicalizes, - validates, and materializes the plan. Its repeated-looking resolve/position - calls are constant-time index lookups that preserve contextual diagnostics; - a generic range collector would hide scene-specific full-coverage policy. -- `internal/modules/dnd/spells/catalog.composeEffectiveCatalog` intentionally - uses separate canonical-name, per-spell alias, and complete lookup maps. The - function validates base and overlay collisions while applying overlays in - sorted ID order, then produces stable names and a semantic digest. Its nested - loops traverse catalog entries and each entry's aliases without a linear scan - inside the loop. DND-SCENE-001 concerns the later model-visible projection, - not combining catalog composition with prompting or weakening collision - checks. - -## Cross-Cutting Test And Comment Review - -Every finding was re-read against its cited production owner, immediate -callers, and the narrowest maintained test boundary. The uncovered cases are -specific consequences of the production defects—for example second-document -parsing, post-cancellation dispatch, validator mutation, terminal rejected -warnings, state-identity collisions, provider-error redaction, prompt-name -collisions, evidence bounds, and durable enemy-event semantics—so their -regression tests remain in each finding's **Validation** clause rather than -becoming duplicate Test Quality findings. - -The focused-test inventories in the configuration, CLI, pipeline, state, LLM, -module, and D&D internal guides agree with the observed ownership. Contract and -matrix tests appropriately span files where the invariant is cross-component; -leaf codec, validator, resolver, scheduler, and filesystem tests own local -rules. No assertion-only duplication, private-helper coupling, flaky timing -dependency, or test fixture elaborate enough to justify a standalone finding -survived the review. - -Comments were judged only where code cannot express an ordering, concurrency, -or ownership invariant. Existing explanations around CLI/runner lifecycle, -operation-time cloning, cache publication, prompt order, scene coverage, and -typed erasure are specific and still accurate. RUN-004 remains because the -collector's non-obvious liveness proof depends on its caller draining every -lane channel; no other missing or stale comment met that bar. - -## Areas Reviewed Without Findings - -### Architecture And Dependency Boundaries - -- **Composition root:** `internal/cli.newProductionComponents` constructs the - complete registry set and asset registry, then invokes only the generic, - Seriatim, and D&D family registrars. Direct production imports confirm that - `internal/cli` is the only layer importing those registrar packages. -- **Dependency direction:** A direct production import map found no core or - framework package importing `internal/modules`, no module importing - `internal/cli`, no concrete generic or Seriatim module importing D&D, and no - module importing the file-backed checkpoint, chunk-plan, debug, file-I/O, or - debug-bundle implementations. PromptKit is imported directly only by - `internal/framework/llm`. -- **Graph cross-layer calls:** The refreshed graph reported one - framework-to-module edge from `pipeline.Prepare` to a symbol named `request` - in a D&D validator test. Tracing it showed a confidence `0.06` suffix match - from the local closure call in `Prepare`; `trace_path` classified the target - as test-only, and the production import map disproved a dependency. The graph - reported no module-to-CLI calls. -- **Assets leaf:** `assets/package.go` imports only `embed` and `io/fs`, embeds - content, and exposes the read-only `FS() fs.FS` accessor. It contains no - business logic and has no `internal` or PromptKit dependency. -- **Fixed pipeline shape:** `pipeline.ResolvePipeline` resolves input and - chunk once, fixed extract/merge/normalize bindings per artifact lane, and one - output binding. Ordered steps are barriers around those fixed lanes rather - than arbitrary graph topology. `pipeline.Prepare`, `Runner.Run`, - `runPreparedSteps`, and `runLanes` retain that shape through construction and - execution. -- **Typed artifact boundary:** Typed registrations retain the exact Go type for - codecs and lane operations. Private erasure in `RegisterArtifactCodec` and - `exactTypedValue` verifies exact types and returns contextual errors; - normalized values cross into output through serialized artifacts. -- **Physical-state ownership:** The CLI owns root selection, store factories, - and durable file placement (`chunkPlanStoreForRun`, checkpoint/debug setup, - and `writeOutputFiles`). The framework receives collaborator interfaces and - returns logical output files. The generic JSON output module's direct import - of `internal/framework/chunkmap` validates and republishes the accepted - serialized chunk-map contract; it neither chooses a physical root nor writes - files. -- **Accepted architectural decisions:** ADRs 0001–0005 and 0007–0012 were read - against the current high-level composition. Apart from ARCH-001, the - composition root, fixed ordered pipeline, typed boundary, domain packaging, - canonical chunk-plan policy, separate state surfaces, checkpoint policy, - evidence rules, workload profile ownership, centralized asset leaf, and - deterministic entity identity boundary have corresponding current owners. - -### Configuration And CLI Composition - -- **End-to-end command path:** `RunWithOptions` normalizes injectable process - collaborators once and dispatches to `runPipelineCommand`. The run command - parses and normalizes command input, discovers and loads configuration, - applies command overrides, builds the effective catalog, resolves reference - selectors and the pipeline, inspects effective profiles, materializes - references, constructs runtime/state collaborators, invokes `pipeline.Run`, - publishes output files, terminalizes debug state, and only then publishes a - requested JSON receipt. -- **Precedence and resolution:** `loadConfig` enforces explicit `--config` over - `NOTARIUS_CONFIG` over the system default, then applies `Default`, file - configuration, supported environment overrides, and run-only CLI overrides - in order. `Config.Resolve` recomputes derived worker defaults, validates, - clones the selected profile, and delegates catalog-dependent composition to - the framework resolver. Apart from CFGCLI-001 and CFGCLI-002, unknown fields, - malformed values, normalized-key collisions, unknown command flags, and - invalid selected modules/options are rejected at their owning boundary. -- **Profile-source equality:** Validation-time - `validateExplicitPromptKitProfiles` and runtime - `buildProductionLLMClient` pass the same profile directory, profile file, - mapped local backend, and shared fallback asset registry. Effective profile - collection is sorted, deduplicated, and limited to selected LLM-backed - modules and validators, so inspection and runtime selection use the resolved - profile values rather than recomputing inheritance. -- **Session identity:** `resolvePromptSessionID` uses a versioned SHA-256 value - over the trimmed resolved input-module key, a separator, and exact raw input - bytes. It contains no pipeline ID, reference, profile, retry, input path, - working directory, or run ID; an explicit non-empty session replaces the - generated value. Run contracts verify the same effective session reaches all - prompt-facing requests, manifests, debug metadata, and checkpoint identity. -- **Reference and recomputation controls:** CLI reference selectors are - resolved only against selected chunk/extract/merge/normalize capabilities - before the authoritative effective resolution. Recompute policy is derived - after reference materialization, forces the requested step and transitive - consumers, and requires reusable checkpoints for non-forced transitive - producers. Focused contract tests exercise selector ambiguity, lane - selection, ordered dependency closure, and execution behavior. -- **Publication and terminal outcomes:** Syntax/config failures before run - identity allocate no output or debug state. After debug allocation, - resolution, profile, preparation, input, framework, partial-summary, and - output failures all pass through `failPipelineCommand`. `terminalize` writes - a run report once, preserves an existing primary failure over report/error-log - failures, promotes a success-report failure to primary, and reports other - persistence failures secondarily. Framework cancellation follows the same - wrapped primary-error path. Durable outputs are attempted only after runner - success; a JSON result is encoded before output publication but written to - stdout only after output and debug terminalization. A receipt-delivery - failure leaves already published bundles intact and returns failure. -- **Test ownership:** Configuration tests own strict file/env application, - structural validation, effective cloning/digests, and redaction. CLI command, - run, reference, recomputation, session, production, example, result, and state - contracts assert process-level ordering and side effects rather than merely - repeating lower-level resolver assertions. The two uncovered command/parser - cases are recorded as CFGCLI-001 and CFGCLI-002. - -### Pipeline Resolution, Preparation, And Typed Registries - -- **Static composition:** `ResolvePipeline` rejects mixed legacy/ordered - shapes, empty and duplicate normalized step/lane identities, invalid - invocation filtering, unknown modules, missing capabilities, incompatible - artifact variants, unsupported lane-level validators, invalid generated - selectors, and missing output capabilities before producing a resolved - value. Apart from PIPE-001's direct-call collision, selected lanes and steps - have stable sorted/order-preserving identities. -- **Effective policy and identity:** Execution classes come from normalized - registry specs. Command override → binding → pipeline LLM-profile precedence - applies only to selected LLM-backed modules and validators; deterministic - bindings reject explicit profiles. Module and validator option validators - receive owned maps before `resolvedPipelineDigest` hashes the complete - effective composition. Digest tests cover map canonicalization, validator - policy, artifact schema identity, effective profiles, and exclusion of the - digest field itself. -- **Typed registry boundary:** Extractor registrations retain one exact Go type; - merger, normalizer, and typed-validator registrations select an exact - module/artifact-kind variant; codecs validate complete schema/media identity; - and evidence projectors must match the active codec type. Every erased - operation checks the implementation or value type and returns an error rather - than asserting or panicking. Kind-neutral `Spec` methods are confined to - catalog inspection, while behavior-sensitive resolution uses exact variant - lookups. -- **Construction boundary:** `Prepare` validates the resolved shape and needed - registries, clones retained bindings, options, validator chains, reference - targets, schemas, and bytes, then constructs input, chunker, chunk validators, - every ordered typed lane and local validator chain, output, and the optional - evidence plan before returning. Implementations and operations remain - private; public prepared bindings/lanes are separate clones. Focused tests - verify deterministic construction order, late failure before input parsing, - nil and identity rejection, generated-selector retention, and independent - builder reference inputs. PIPE-002 records only the extra adjacent copies. -- **Checkpoint supplements:** Preparation collects component-provided semantic - fingerprints only after the complete implementation set exists. Scopes - include stage, globally unique lane identity, module, and validator position; - empty or duplicate values fail preparation, results are sorted, and the - accessor returns a defensive copy. Scheduling limits and diagnostics are not - included. Resolved composition—including options, reference selectors, - effective profiles, retries, and validator order—remains owned by the - resolved digest rather than being redundantly restated as component - fingerprints. -- **Registry comparison:** Input, chunker, and output registries consistently - normalize keys/specs, reject nil validators/builders, validate options on - owned maps, clone stored specs, sort discovery output, and verify constructed - identity. Typed stage and validator registries add only the exact-type and - artifact-variant mechanics their contracts require. Validator-chain lookup - distinguishes absent, default, explicit replacement, and explicit empty - chains while returning defensive copies. No dead compatibility path or safe - consolidation was found beyond the copy reduction in PIPE-002. -- **Test ownership:** Contract tests cover clone/serialization boundaries; - registry tests cover invalid registration, sorted/defensive discovery, - strict options, exact types, schema compatibility, and evidence ownership; - resolution tests cover heterogeneous variants and effective identity; and - preparation tests own all-before-parse construction and fingerprint - collection. The missing module-reference collision case is recorded in - PIPE-001 rather than as a separate test-only finding. - -### References And Ordered Handoffs - -- **External path:** Pipeline defaults are filtered to declared slots; local - bindings override eligible defaults; CLI overrides apply to one exact final - target; and unbind removes only an external binding before required-slot - enforcement. Selected legacy lanes determine eligible targets, while - explicit ordered steps reject `--only`. Config-relative and CLI-relative - paths remain distinct, materialized values retain digest/media/size/origin, - preparation supplies owned construction inputs, and operation requests get - independent content. REF-001 records the only missing bound in this path. -- **Generated path:** Pipeline-level selectors are rejected. Ordered local or - step bindings must name a declared earlier step and selected lane whose exact - artifact kind, registered codec media type, and target slot constraints are - compatible. Because all edges point strictly backward, forward references - and cycles are rejected during resolution. At the step barrier, exactly one - accepted normalized output is decoded and re-encoded through its codec; - missing, duplicate, wrong-kind, wrong-schema/media, oversized, rejected, or - unavailable producer state stops the consumer before execution. REF-002 - concerns only the repeated lookup used to establish that cardinality. -- **Resume and recomputation:** Ordinary resume progressively compares - generated dependency fingerprints on extract, merge, and normalize - checkpoints. Selective recomputation instead forces the selected step and - transitive consumers while requiring unforced transitive producers to supply - accepted normalize state without extract/merge files or dependency matches. - Hydration validates stored provenance and canonical bytes through the active - codec before publishing an owned normalized output. REF-003 records the - omitted size field in the ordinary consumer fingerprint. -- **Provenance and evidence:** External manifests contain paths, digests, - media, sizes, and binding sources; generated manifests contain bounded - producer, codec/schema, digest, and size identity without content or a fake - path. Runtime stage debug envelopes omit reference sets, contract JSON omits - `ReferenceItem.Content`, and focused assembled-module tests confirm generated - references ground operations without becoming source evidence. -- **Complexity ownership:** Static target resolution keeps precedence, - unbinding, and required-slot policy together for contextual errors; - `validateGeneratedBindings` owns cross-step static compatibility; and - `buildStepReferenceSets` owns the runtime barrier. Apart from REF-002's - repeated full-output scan, their explicit traversals preserve distinct - invariants more clearly than a generic graph or reflection engine. -- **Test ownership:** Profile and CLI reference contracts cover defaults, - local precedence, unbinding, required slots, selected targets, ambiguity, - and typed producer compatibility. Reference materialization tests cover - origin, UTF-8, media, size diagnostics, warnings, and provenance; handoff and - runner tests cover canonical fanout, invalid/missing producers, ordering, - fingerprints, and accepted checkpoint hydration; assembled integration tests - cover semantic generated-reference consumers. REF-001 and REF-003 identify - the two unproved identity/resource details. - -### Execution, Validation, Retry, And Concurrency - -- **Runtime state diagram:** The audited framework lifecycle is: - - ```text - input validation / owned metadata - -> source load or parse -> document validation - -> chunk load or plan -> materialize -> whole-plan validator chain - -> rejected: terminal ordinary outcome ----------------------+ - -> accepted: for each ordered step | - -> generated handoff barrier | - -> initialize lane checkpoint states | - -> dispatch extract jobs (chunk first, lane second) | - -> operation -> canonical candidate -> validators | - -> retry | rejected chunk | accepted chunk | - -> completed lane enters bounded continuation | - -> merge -> validators -> retry/reject | - -> normalize -> validators -> retry/reject | - -> await all started work -> stable lane merge -> barrier | - +---------------------------------------------------------------+ - -> manifest/evidence -> logical output encoder - - any framework error or parent cancellation - -> cancel derived work -> stop dispatch -> drain/await started work - -> stable error selection -> failed output (no logical files) - ``` - -- **Ordering and bounded work:** `dispatchExtractJobs` enumerates chunks first - and lanes second. One fixed extract pool and one fixed continuation pool are - each bounded by `ExtractWorkers`; a lane continuation is serial merge then - normalize, while different completed lanes may overlap remaining extracts. - Results are indexed by lane and chunk, extracts are sorted by chunk index, - lane outputs merge in prepared order, and framework errors sort by stage, - lane, and chunk after child cancellation errors are filtered. Reverse- - completion, continuation-overlap, continuation-bound, provider-bound, and - stable-error tests confirm these contracts independently of goroutine finish - order. -- **Cancellation and liveness:** The lane engine checks cancellation before - starting queued extract and continuation work, stops dispatch, clears - unlaunched continuations, drains worker results, receives every launched - completion, and waits for both pools. The retry loop checks before an attempt - and after failed/rejected attempts. Parent cancellation takes precedence over - collected child cancellation, while an actual framework failure is selected - deterministically when the parent remains live. RUN-001 records the two - unguarded outer dispatch boundaries; no additional worker leak or deadlock - path was found. RUN-004 records the missing collector invariant comment. -- **Terminal outcomes:** Chunk, extract, merge, and normalize validators inspect - whole candidates, not partial streams. A rejection is collected as ordinary - output: a rejected chunk plan skips all lanes, a rejected extract chunk does - not prevent accepted chunks in that lane from merging, and merge/normalize - rejection terminates only that lane. A framework error cancels sibling work, - blocks later ordered steps, and returns through `failOutput`, which leaves no - logical output files. RUN-002 records the typed-value ownership violation; - serialized validators receive owned canonical bytes. -- **Retries and diagnostics:** Operation and complete validator-chain execution - share one retry budget. Debug persistence failure is terminal rather than - retried; cancellation stops retries; rejections record their final attempt; - and normalize retry directives use the same budget before validating their - final fallback. Candidate serialization precedes validation and accepted - checkpoint serialization follows it, so invalid candidates are not recorded - as success. Intermediate-attempt warnings remain only in attempt debug as - intended; RUN-003 records loss of the final rejected attempt's warnings. -- **Collaborator synchronization:** Runner-local wrappers serialize checkpoint, - debug, and LLM-debug collaborators without acquiring multiple framework - locks at once. Module/provider concurrency remains separately bounded by the - shared LLM scheduler. No duplicate recording or permit leak was found in the - audited execution layer; durable checkpoint transitions and filesystem - atomicity remain in the next audit area. -- **Focused test review:** Concurrency tests exercise chunk-first dispatch, - reverse completion, extract and continuation bounds, intended overlap, - provider limits, stable stage/lane error priority, ordinary rejection, parent - cancellation, and stopped queued extracts. Retry, rejection, candidate- - encoding, session, manifest, typed-checkpoint, debug-attempt, accepted- - checkpoint, and generated-handoff tests cover the remaining execution - branches. The consequential missing runtime cases are included in RUN-001 - through RUN-003 rather than duplicated as test-only findings. - -### State, Checkpoints, Debugging, And File Safety - -- **Independent state lifecycles:** `runPipelineCommand` selects output, - chunk-plan, checkpoint, and debug roots only in the CLI. Bypass returns before - resolving or constructing a chunk-plan store; disabled checkpoints construct - only no-op collaborators and reject resume; enabled recording always creates - a recorder but creates a loader only for resume; and debug allocation occurs - only after an explicit debug request. None of these roots enters a module or - another state family's identity, and debug records are never read by reuse - code. -- **Chunk-plan cache:** The store accepts only a canonical lowercase SHA-256 - source digest as its key, opens the exact digest directory through `os.Root`, - rejects symlink/non-directory digest entries and symlink/non-regular plan - files, strictly decodes one schema-versioned JSON value, revalidates plan - provenance and digest, and returns typed missing/invalid/hit decisions. A - reused plan is cloned, materialized against the current document, and passed - through the whole-plan validators. Only a newly accepted plan is published; - random 0600 temporary files are synced and renamed within the confined 0700 - entry. Missing, invalid, or deleted entries are reconstructible. -- **Checkpoint identity and ordinary resume:** Identity hashes the complete - resolved pipeline, raw input, selected lanes, runtime overrides, external and - generated reference provenance, observed profile/runtime provenance, and - prepared component fingerprints. The directory uses readable/prefix - components, while every manifest retains and validates the complete identity - digest and exact stage/step/lane/module/dependencies. Payload publication - precedes a succeeded manifest, and the manifest retains payload digests, so - interruption or a changed dependency produces execution/invalidation rather - than stale reuse. STATE-001 records the remaining non-injective step/lane - component mapping. -- **Selective recomputation:** The CLI computes a forward forced closure and a - backward set of required reusable producers. The runner applies - `forced_recompute` before decoding an otherwise reusable artifact. Required - producers use only an accepted workspace-v3 normalize manifest with exact - invocation, producer provenance, artifact digest, active codec/schema/media, - and canonical bytes; they deliberately do not require extract/merge state or - current consumer dependencies. A failed required load records its typed - decision and stops before producer or consumer execution. -- **Decisions and diagnostics:** Checkpoint readers assign category and reason - code at the validation branch for missing, path, read, decode, schema, - identity, stage, dependency, payload, digest, and reuse outcomes. Runner - hydration adds codec and canonicality codes, forced policy adds the recompute - code, and required-predecessor errors name only stable step/lane identity and - code. Event detail is selected from code-owned text, UTF-8 normalized, and - bounded rather than copied from a cache error or caller payload. -- **File safety and recovery:** Output names are all validated before exclusive - run-directory creation; existing output/debug run directories are refused; - later output failure intentionally retains the new partial bundle. General - state writes use same-directory temporary files and atomic rename after - narrow relative-path checks, with 0700/0600 cache/debug modes and 0755/0644 - output modes. General file I/O rejects existing symlink components; the - chunk-plan store additionally uses root-relative no-follow opens and - race-oriented entry rechecks. No production path automatically moves, - deletes, or cleans output, cache, or completed debug state; debug allocation - removes only its just-created partial leaf on setup failure. -- **Debug and terminalization:** A bundle owns distinct summary and trace - directories. Summary records use redacted invocation/configuration and - bounded checkpoint decisions; trace requests receive cloned application - payloads and no environment enumeration. Debug write failures fail the - requested run but cannot affect checkpoint identity or reuse. Guarded - terminalization writes one report, preserves an existing primary error over - report failure, attempts one error log, and joins persistence failures only - as secondary diagnostics. STATE-001 records trace-name collisions, not a - cache dependency or redaction leak. -- **Canonical ownership:** Source digesting uses canonical document/plan - serialization and cycle-aware metadata cloning. Chunk-map and evidence- - context codecs strictly validate schema, reject unknown fields and trailing - values, canonicalize nested identities/annotations/context, and return owned - graphs. Their encode-time clones are required ownership boundaries; - STATE-002 records only the redundant copies after decoding already-owned - JSON. STATE-003 records the one extractable duplicate writer; checkpoint - stage adapters, cache-specific `os.Root` mechanics, and type-specific clone - helpers remain intentional. -- **Focused test review:** File-I/O and debug-bundle tests cover confinement, - atomic replacement, symlinks, modes, refusal, cleanup, and redaction. - Checkpoint tests cover identity, manifests, interrupted publication, - categories/reason bounds, dependency invalidation, accepted normalize, and - codec canonicality. Chunk-plan tests cover corrupt entries, races, named - pipes, strict decode, materialization, and permissions; chunk-map and - evidence-context tests cover canonical round trips and ownership. CLI cache, - recomputation, state-hardening, run-contract, and terminal tests cover the - composed lifecycles and primary-error precedence. The uncovered identity, - copy, and writer issues are recorded as STATE-001 through STATE-003. - -### LLM Runtime, Prompt Filesystems, And Assets - -- **Completion path:** Every production structured completion crosses the - scheduled client and the shared scheduler before the PromptKit adapter. The - adapter forwards the stable session ID directly, renders inputs and variables - once, prepares one frozen execution target, snapshots its details, invokes - that exact prepared target, accepts only PromptKit schema-valid structured - output, decodes into the caller's target, records normalized profile - provenance, and emits caller-owned debug material. Context and capacity are - adapted to provider-neutral categories; LLM-001 records the raw error chain - that still escapes on other provider failures. -- **Scheduling:** Production constructs one scheduler around the one PromptKit - client, so all LLM-backed bindings and validators share the configured - application limit. Queue insertion and grant are FIFO, active counts change - under one mutex, canceled queued entries are removed or return an already - granted permit, and idempotent deferred release covers success and error. - LLM-002 records only the simultaneous grant/cancel dispatch window; no permit - leak or second application scheduler was found. -- **Profiles and cache identity:** Preflight inspection and runtime construction - share configured directory/file, embedded fallback, built-in catalog, and - optional local-backend option builders while retaining separate engines. - Inspection does not load credentials or contact a provider. Checkpoint - fingerprints cover the compiled catalog identity, every configured profile - file's content identity, fallback asset identity, reasoning override, and a - hashed local endpoint without publishing profile contents, paths, endpoint, - environment values, or concurrency limits. Successful manifests record only - selected non-secret profile/provider/model/backend/reasoning provenance. -- **Sessions, bytes, and cache points:** The CLI resolves one stable session ID - before physical run construction and the same value flows through pipeline - requests into PromptKit's native `SessionID`; it is not reconstructed from a - transcript. All maintained extraction prompts render a stable shared system, - identity/reference prefix before the transcript, then lane-specific evidence - and grounding, with the final instructions last. Focused composition tests - assert identical cached prefixes, exact-once input placement, suffix order, - and ephemeral cache controls at reference, transcript, and final-instruction - boundaries. -- **Asset ownership:** The root `assets` package imports only `embed` and - `io/fs` and exposes one read-only filesystem. Module manifests explicitly - flatten only selected module files and shared fragments; the asset registry - clones bytes, rejects duplicate flattened prompt/schema/profile roots, - validates schema manifests, and hashes selected semantic assets. All fourteen - D&D prompt manifests currently use unique normalized virtual names; LLM-003 - records that `ModulePromptFS` does not enforce this invariant itself. -- **Model-visible content:** Every maintained PromptKit YAML file, shared - fragment, module instruction/grounding file, private response schema, and - fallback profile was searched and representative complete compositions were - read. The only provider/model-named content is the intentional fallback - profile target. No bearer token, credential variable/value, endpoint, - provider-generated opaque identifier, UUID, digest-copy instruction, or - duplicated model instruction was found in model-visible assets. Durable - private-schema `$id` values remain schema metadata rather than requests to - reproduce internal identifiers. -- **Filesystem mechanics and tests:** Asset and module prompt filesystems - enforce valid scoped paths, sorted directory entries, read-only metadata, and - owned bytes, while prompt/schema loaders are exercised through real - PromptKit preparation. LLM-004 records the duplicated map-filesystem - implementation and its drift. Focused client tests cover direct sessions, - prepared-snapshot consistency, default/explicit/fallback/local profiles, - response validation/decode, capacity mapping, debug redaction, profile - provenance, and scheduled concurrency; scheduler and promptfs tests cover - limits, queued cancellation, release, path scoping, reads, and ownership. - -### Generic And Seriatim Modules - -- **Seriatim source boundary:** The transcript adapter strictly decodes one - top-level JSON object, requires metadata and a non-empty segment array, - validates unique positive canonical IDs, non-empty speaker/text values, and - finite ordered timestamps, then chooses a deterministic document ID from the - request, metadata, or raw-byte digest. It constructs generic units with - exact self-references, computes the canonical source digest, and runs the - framework document validator. Transcript-only speaker/start/end helpers and - external metadata remain in the adapter package; the resulting document - exposes only generic source fields and metadata. -- **Generic chunk planning:** The unit chunker validates the complete source - document, computes source-addressed ranges by unit position with bounded - overlap, returns only the source digest and unit-ID ranges, and leaves - materialization, chunk identity, and plan validation to the framework. Tests - cover defaults, exact boundaries, overlap, invalid/unknown options, empty - sources, and non-retention of source units. MOD-001 records the only - avoidable option-decoder surface found. -- **Merge, normalize, and validation ownership:** Typed append-order combines - values in framework order through a family-supplied typed combiner, while - typed no-op normalization preserves the exact artifact type; D&D registrars - instantiate those domain-neutral mechanics without introducing D&D imports - into the generic packages. Always-accept/reject, JSON, and JSON-Schema - validators retain distinct selectable targets and strict empty option sets. - Schema mismatch remains an ordinary rejection and malformed schema remains - an operational error. MOD-002 records only repeated schema compilation. -- **JSON output and evidence:** Output decoding rejects unknown and - context-incompatible fields, normalizes/deduplicates/sorts evidence lane - allowlists, and validates configured lanes before preparation. Preparation - retains the full configured policy while selecting active exact-typed - evidence projectors; runtime evidence is built only from compatible accepted - normalized outputs. The encoder sorts lanes and logical files, rejects - unsafe or colliding lane filenames, emits no physical paths, validates and - republishes opt-in chunk-map and prepared evidence-context artifacts, and - preserves annotation number bytes. MOD-003 records only unreachable clone - code outside those live ownership paths. -- **Registration and dependency direction:** Generic registration checks all - required registries before mutation and registers the unit chunker, four - validators, and JSON output; Seriatim independently registers only its input - adapter. Direct import inspection found no D&D package in either family and - no Seriatim package below the input registrar. Typed append/no-op libraries - are instantiated by the D&D family rather than acquiring domain concepts. -- **Composed contracts:** Focused module tests cover strict registration, - source parsing/identity/metadata, chunk planning, typed combination, - validator outcomes, JSON bundle determinism, chunk-map/evidence validation, - and mutation isolation. Framework evidence-preparation/output tests prove - invocation filtering and exact codec/projector compatibility; maintained CLI - example contracts prove Seriatim input through generic JSON publication and - opt-in chunk-map provenance. - -### Shared D&D Types, Codecs, And Family Mechanics - -- **Durable family inventory:** `internal/modules/dnd/types.go`, the ten codec - packages, and D&D registration agree on ten exact kind/type variants. Each - has one LLM extractor, one typed append-order merger, a concrete normalizer, - a typed noop alternate, an evidence projector, artifact-specific validators, - and extract/normalize default chains. The convention matrix above records the - three intentionally LLM-backed registry normalizers and every reference - dependency; no missing or extra durable family registration was found. -- **Codec boundary:** All family codecs publish `application/json`, codec-local - v1 durable schemas and count metadata, strictly decode through the shared - candidate JSON helper, reject unknown fields and trailing values, and apply - family required-value validation only at durable encode/decode. Ownership - clones are present for the two mutable nested shapes that need them, and - schema reads return owned bytes. The common adapter surface is already at its - natural owner; a further generic codec would have to parameterize the exact - behavior the typed boundary is meant to expose. -- **Reference mechanics:** Shared campaign slots return owned media-type and - slot declarations; source ordering uses document positions with literal-ID - fallback, stable exact deduplication, and diagnostic preservation of invalid - refs. Strict unit-reference JSON parsing, current-document citation - expansion, typed family canonicalization, validator admissibility, and direct - evidence projection remain distinct owners. DND-CORE-001 records the only - dead/lossy API found in this layer. -- **Shared registry and reconciliation mechanics:** The generic registry - resolver validates one typed JSON artifact, bounds it by the family-declared - maximum, copies content at retention boundaries, and caches raw and semantic - identities behind a mutex. Entity reconciliation renders source-free - selectors and bounded transcript windows, keeps durable IDs model-invisible, - discards unsafe or overlapping proposals, and returns defensive copies. - Diagnostics and Unicode comparison policy are shared and bounded/versioned; - registry-specific identity and merge outcomes remain deferred. -- **Registration and assets:** The registrar validates all collaborators before - mutation and gives every failed component contextual identity. All ten - durable schemas, fourteen family prompt manifests, the shared reconciliation - schema, evidence projectors, generic validator capabilities, typed - always-accept/reject capabilities, default chains, and the fallback profile - are registered. Sequential registration is intentionally fail-stop rather - than transactional; production discards the composition on any error. -- **Repeated method classification:** Module-local metadata and fingerprint - methods enumerate semantic cache/checkpoint inputs; constructors and - registrars preserve exact dependencies and typed error context; strict empty - option decoders make supported surfaces locally visible. Existing shared - helpers already consolidate prompt assets, candidate JSON, reference slots, - comparison, diagnostics, resolution, and reconciliation. No additional - callback- or reflection-driven helper reduced demonstrated drift. -- **Completed lane questions:** Registry identity, reconciliation, immutable - projections, occurrence-category/grounding policy, spell catalogs, scene - chunking, scene identity/classification, combat gates, engagement uniqueness, - collective labels, and enemy observation ordering are now confirmed. The - convention matrix records every family exception, with DND-CORE-001, - DND-REG-001 through DND-REG-004, DND-OCC-001 through DND-OCC-003, - DND-SCENE-001, DND-SCENE-002, and DND-COMBAT-001 recording the bounded gaps. - No shared D&D question remains deferred to the final synthesis. - -### NPC, Item, And Location Registries - -- **End-to-end artifact path:** Each LLM extractor decodes a private - name/evidence response, injects the current source ID, canonicalizes direct - citations, orders candidates by earliest evidence, and derives family-owned - IDs before the typed append-order merger. Normalizers own display cleanup, - exact duplicate consolidation, proposal-only semantic reconciliation, - deterministic fallback, final identity derivation, and owned output. Shape, - identity, current-source reference, schema, and advisory relatedness checks - remain ordered in the declared chains before canonical codec publication. - Generated references cross the strict typed codec boundary; external - approved references use the immutable family registry loaders. DND-REG-001 - records the structural rule missing from that direct path, and DND-REG-002 - records the NPC extractor's missing current-chunk evidence gate. -- **Identity and lookup policy:** NPC and item identity is the versioned Unicode - comparison name hashed through compact JSON, with duplicate comparison names - rejected after normalization. Location identity adds the lexicographically - earliest valid source anchor, intentionally permitting equal display names at - distinct anchors. Family registries validate IDs, clone retained records and - citations, build exact ID/name lookups where supported, publish semantic - durable and projection digests, and return defensive copies. DND-REG-004 - concerns only repeated work in selecting the location anchor. -- **Reconciliation safety:** All three normalizers render source-free candidate - keys with bounded transcript context, invoke the shared strict reconciliation - schema only when at least two eligible candidates exist, reject unknown, - colliding, duplicate, or overlapping groups, apply only disjoint safe groups, - and retry discarded proposals before deterministic warning-bearing fallback. - NPCs consolidate aliases under the selected canonical name; items additionally - refuse groups that mix currency with non-currency or conflicting - denominations; locations union citations and recompute anchored identity. - DND-REG-003 records only the pre-reconciliation exact-group scan. -- **Proper-name and currency behavior:** NPC extraction requires a proper name, - stable title, or individually identifying alias and excludes players, - generic roles, groups, and hypotheticals. Location extraction requires a - stable physical proper or uniquely identifying designation and excludes - generic, relative, transient, and merely descriptive references. Item - extraction keeps named/unique concrete reusable objects, materially distinct - stable types, and each currency denomination while excluding generic or - vague mentions. Normalization proposes equivalence but cannot invent records, - source evidence, or unsupported canonical names. -- **Location grounding:** Immutable location grounding groups comparison names, - exposes name-only selectors for unique names, and exposes exact canonical - ranges plus cited context only when same-name records need disambiguation. - Durable IDs and source IDs remain model-invisible, selectors resolve by exact - contextual identity, collisions and invalid contextual citations fail - construction, and prompt/resolved values are defensively copied. -- **Test ownership:** Extractor tests own prompt manifests, strict response - decoding, citation adaptation, order, and fingerprints; identity/registry - tests own compact hash inputs, same-name behavior, lookup/digest projections, - direct resolution, empty placeholders, grounding, and mutation isolation; - normalizer tests own exact/semantic consolidation, currency and location - safety gates, diagnostics, retry/exhaustion fallback, context, and prompt - fingerprints; validator tests own shape deferral, identity diagnostics, - current-source/chunk evidence, relatedness warnings, and bounded messages. - The prescribed package suite passes. - -### NPC, Item, And Location Occurrences - -- **End-to-end selection path:** Each extractor renders semantic registry - selectors without durable IDs, decodes a private factual occurrence - response, resolves every selection against the immutable required registry, - rejects the whole candidate on an unknown or ambiguous selector, injects the - current source ID, canonicalizes current-chunk citations, and attaches the - exact durable ID/name pair before the typed append-order merger. NPC and item - selectors are exact names because those registries prohibit comparison-name - collisions; location selectors add exact canonical evidence and bounded - cited context only for same-name records. DND-OCC-001 records the one private - response vocabulary that contradicts the shared evidence instruction. -- **Evidence and identity separation:** Registry prompt and grounding - projections omit durable/source IDs, and registry provenance is never copied - into occurrence evidence. Extract validators require direct current-source, - current-chunk evidence; normalizers and registry validators independently - re-establish exact ID/name pairs for artifacts entering through other - boundaries. Generated-reference checkpoint dependencies bind the complete - producer content/provenance while semantic registry projection digests bind - selection behavior, so an approved registry change cannot silently reuse a - stale occurrence result. -- **Canonicalization and family policy:** All three normalizers preserve nil - versus present-empty list meaning, retain invalid data long enough for - ordered diagnostics, canonicalize evidence without mutating input, sort - deterministically, collapse only exact valid-evidence duplicates, and bound - warnings. Their local policies intentionally remain distinct: NPC categories - encode factual presence/dialogue/combat roles; item identity includes - quantity and directionally constrained holders; location ordering uses an - explicit semantic kind precedence and retains same-name records with - different durable IDs. A generic occurrence normalizer would obscure these - contracts. DND-OCC-003 concerns only avoidable repeated canonicalization - inside the item implementation. -- **Boundary and reference review:** Durable codecs strictly reject unknown - fields, trailing values, absent lists, empty required values, unsupported - kinds, and item holder/quantity violations. DND-REG-001 now also covers the - shared reversed-range structural omission at the occurrence codecs. Extract - campaign context remains legitimate model grounding, while deterministic - normalizers require only their immutable registry; DND-OCC-002 records the - NPC normalizer's four inert campaign slots rather than changing extraction. - Family-specific shape, registry, source, relatedness, and invariant - validators remain separate because their ordered deferral and source-aware - responsibilities differ from durable decoding. -- **Generated handoffs and tests:** Production resolution requires an earlier - compatible generated producer or a strictly decoded compatible external - registry for each family. The representative assembled D&D flow proves exact - registry IDs, independent occurrence evidence, and distinct same-name - location selection through extraction and normalization. Extractor tests own - prompt/schema adaptation and all-or-nothing resolution; normalizer tests own - ordering, exact duplicates, holders/quantities, same-name locations, warning - order, and ownership; validator tests own pair, source, relatedness, and - invariant defenses. The prescribed occurrence and CLI suites pass. - -### Spells, Scene Chunking, And Scene Descriptions - -- **Accepted scene-plan path:** The scene chunker validates the complete source, - supplies the whole transcript after optional cached campaign context, and - decodes only ordered start/end unit IDs. `planFromResponse` resolves those - IDs against document positions and enforces non-empty, contiguous, - non-overlapping first-to-last coverage. The framework then canonicalizes, - validates, and materializes the plan before storing it. Only an accepted plan - is serialized into the distinct chunk-map artifact with exact source, - requested-chunker, producer, plan-digest, chunk-ID/range/count, and cloned - annotation metadata; lane rejection does not erase that accepted structural - artifact, while plan rejection publishes no chunk map. The D&D scene planner - deliberately emits empty annotations rather than duplicating classification - or source text, and the production contract verifies that separation. -- **Scene-description identity and eligibility:** Extraction maps exactly one - private kind/title/summary response onto the local current chunk ID and exact - range, so the model cannot select or invent durable identity. Extract - validation rechecks that exact chunk match; normalization uses source-document - positions, rejects ID/range conflicts, and removes only exact duplicates. - The immutable registry strictly decodes one approved artifact and projects - only ID, complete range, and kind into a semantic eligibility digest. Its - exact/missing/mismatched match state prevents title, summary, source prose, - or registry provenance from becoming later combat evidence. DND-REG-001 and - DND-SCENE-002 record the bounded codec and diagnostic exceptions. -- **Spell catalog, grounding, and evidence:** Construction strictly decodes the - optional single JSON overlay, composes it with the embedded 2014 SRD catalog - in sorted overlay-ID order, rejects cross-spell canonical/alias collisions, - and binds a semantic catalog digest to extractor, catalog-validator, and - normalizer checkpoints. Optional NPC grounding is resolved independently and - projected as source-free names; neither NPC nor catalog provenance becomes - cast evidence. The extractor injects the current source ID, canonicalizes - references and cast order, and the normalizer canonicalizes catalog names and - reference order before collapsing only exact valid-evidence duplicates. - DND-SCENE-001 records the missing model-visible alias mapping, DND-REG-002 the - extraction chunk gate, and PIPE-002 the redundant construction copy. -- **Validation, retries, and cache identity:** Default spell and scene chains - preserve shape deferral, strict private and durable schemas, source-aware - rejection, advisory relatedness, and normalization invariants. Catalog - rejection participates in the framework's bounded retry path, terminal - accepted-attempt warnings are retained, and rejected-attempt warnings are - suppressed as intended. Raw reference dependencies bind provenance/content, - while semantic catalog and NPC/scene projections bind behavior; focused CLI - tests prove catalog, mapping-policy, prompt/profile, and generated-reference - changes prevent stale checkpoint reuse. -- **Prompt and test ownership:** Scene planning follows the intentional D&D - prompt order of system, cacheable campaign references, uncached task - instructions/schema, and final ephemeral whole transcript. Per-chunk scene - descriptions and spells use the shared current-chunk evidence fragments; - local response schemas expose no source IDs or chunk IDs. Focused assets, - codecs, extractors, normalizers, validators, registries, catalog composition, - checkpoint/retry, and production chunk-map tests cover the reviewed contracts, - and the prescribed package suite passes. - -### Combat Turns And Enemy Events - -- **Eligibility and extraction:** Both extractors prepare the current chunk and - consult the immutable scene-description registry before prompt construction. - Only an exact `combat` match reaches the model; an exact non-combat match - returns an accepted present-empty list, while a missing/mismatched match adds - exactly one bounded `scene_classification_unavailable` warning. Scene title, - summary, evidence, and provenance never enter either model input or output - evidence. -- **Grounding and identity:** Combat turns optionally project canonical NPC - names without copying registry references. Enemy events require normalized - NPCs, scene eligibility, combat turns, and NPC occurrences, but project only - NPC names, combat actor/kind pairs, and named `combat_opponent` occurrence - pairs. The prompt and maintained CLI test exclude source ranges and opaque - IDs from these projections; unmatched transcript-grounded actors and narrow - collective enemy labels remain valid durable display subjects. -- **Canonicalization and validation:** Extractors inject the current source ID, - canonicalize exact reference order/deduplication, and order candidates by - valid document chronology while preserving malformed candidates for their - validators. Combat normalization uses a collision-safe complete duplicate - key; enemy normalization applies explicit chronology, subject identity, - display, kind, and evidence ordering and collapses only exact observations. - Shape, source, relatedness, normalized-invariant, and extract-only engagement - validators retain their documented ownership. DND-REG-002 records combat's - missing extraction-chunk check; DND-REG-003 records enemy's pairwise exact- - duplicate work; DND-SCENE-002 records combat warning bounds. -- **Handoffs, retries, and publication:** The maintained three-step example - produces NPC and scene artifacts before combat/NPC occurrences, then binds all - four approved generated artifacts into enemy extraction and the NPC registry - into normalization. Pipeline reference identities, module prompt/schema/ - policy fingerprints, bounded extraction retries, rejection suppression, and - accepted checkpoint hydration apply unchanged. Focused CLI execution proves - only the classified combat chunk prompts for enemy events and publishes typed - combat/enemy JSON plus direct evidence context. DND-REG-001 and - DND-COMBAT-001 record the remaining durable codec gaps. -- **Tests and complexity:** Extractor fixtures cover exact/non-combat/missing/ - mismatched gates, source-free grounding, generated references, chronology, - malformed candidates, and metadata; normalizer/validator fixtures cover - canonical names, reference and event order, exact duplicate identity, - engagement uniqueness, collective subjects, warning bounds where implemented, - and idempotence. Graph traces and complexity inspection found no unbounded - family loop; the intentional generated-reference sequencing is linear, while - the pairwise enemy duplicate paths are isolated in DND-REG-003. All prescribed - family and CLI tests pass. - -## Validation Record - -| Date | Scope | Command or check | Result | -| --- | --- | --- | --- | -| 2026-08-08 | Initial worktree | `git status --short` | Pass; no output | -| 2026-08-08 | Knowledge graph | Full index as `notarius-audit-92e8907` | Pass; 8,322 nodes and 47,887 edges; branch/head matched the production target | -| 2026-08-08 | Baseline tests | `go test ./...` | Pass | -| 2026-08-08 | Baseline static analysis | `go vet ./...` | Pass | -| 2026-08-08 | Baseline build | `go build ./cmd/notarius` | Pass | -| 2026-08-08 | Baseline whitespace | `git diff --check` | Pass | -| 2026-08-08 | Production imports | Direct `go list` import-edge audit plus graph call tracing | Pass; no production dependency inversion found | -| 2026-08-08 | Accepted ADR links | Relative Markdown-link target scan under `docs/adr/` | Two unresolved targets recorded as ARCH-001 | -| 2026-08-08 | Audit target integrity before configuration/CLI review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | YAML decoder contract | `go doc gopkg.in/yaml.v3.Decoder.Decode` and `ParseFileConfigYAML` call trace | Decode consumes the next document; no EOF/second-document check, recorded as CFGCLI-001 | -| 2026-08-08 | Focused configuration and CLI tests | `go test ./internal/core/config ./internal/cli` | Pass | -| 2026-08-08 | Focused configuration and CLI static analysis | `go vet ./internal/core/config ./internal/cli` | Pass | -| 2026-08-08 | Audit target integrity before pipeline composition review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Pipeline graph review | Architecture, complexity query, exact symbol reads, and call traces for `ResolvePipeline`, binding normalization, typed registries, `Prepare`, and checkpoint fingerprints | Pass; PIPE-001 and PIPE-002 recorded; generated handoff execution deferred to the next area | -| 2026-08-08 | Focused contracts and pipeline tests | `go test ./internal/framework/contracts ./internal/framework/pipeline` | Pass | -| 2026-08-08 | Focused contracts and pipeline static analysis | `go vet ./internal/framework/contracts ./internal/framework/pipeline` | Pass | -| 2026-08-08 | Audit target integrity before references/handoffs review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Reference and handoff graph review | Architecture, exact symbol reads, and call traces across external materialization, target resolution, operation cloning, generated codec handoff, consumer fingerprints, ordered execution, and accepted-checkpoint hydration | REF-001, REF-002, and REF-003 recorded; no content/evidence leak found | -| 2026-08-08 | Focused pipeline and CLI tests | `go test ./internal/framework/pipeline ./internal/cli` | Pass | -| 2026-08-08 | Assembled integration tests | `go test ./internal/modules/integration/...` | Pass | -| 2026-08-08 | Audit target integrity before runtime review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Runtime graph and state-machine review | Exact symbol reads, complexity inspection, call traces, cancellation-search coverage, and focused concurrency/retry/rejection/session/checkpoint/debug/manifest/handoff test review | RUN-001 through RUN-004 recorded; bounded work, stable assembly, and worker draining otherwise confirmed | -| 2026-08-08 | Pipeline race tests | `go test -race ./internal/framework/pipeline` | Pass | -| 2026-08-08 | Fresh pipeline tests | `go test -count=1 ./internal/framework/pipeline` | Pass | -| 2026-08-08 | Shuffled pipeline tests | `go test -shuffle=on ./internal/framework/pipeline` | Pass | -| 2026-08-08 | Audit target integrity before state review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | State graph and lifecycle review | Exact symbol reads, complexity and call traces across CLI root construction, core file I/O/debug allocation, chunk-plan storage, checkpoint identity/loading/recording, runner reuse decisions, trace/summary writers, terminalization, and canonical codecs | STATE-001 through STATE-003 recorded; independent lifecycle, typed decisions, accepted hydration, debug isolation, and primary-error precedence otherwise confirmed | -| 2026-08-08 | State collaborator race tests | `go test -race ./internal/core/fileio ./internal/core/debugbundle ./internal/framework/checkpoint ./internal/framework/chunkplan ./internal/framework/chunkmap ./internal/framework/debug ./internal/framework/evidencecontext` | Pass | -| 2026-08-08 | CLI state and terminal tests | `go test ./internal/cli` | Pass | -| 2026-08-08 | Audit target integrity before LLM/assets review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | LLM and asset graph/content review | Exact symbol reads and call traces across scheduled completion, PromptKit adaptation, profiles/preflight/fingerprints, sessions, debug, asset flattening/hashing, prompt filesystems, all fourteen manifests, every prompt YAML, shared/model-visible content, private schemas, and the root asset leaf | LLM-001 through LLM-004 recorded; profile parity, exact prompt order/cache points, asset ownership, and secret-free model-visible content otherwise confirmed | -| 2026-08-08 | LLM and prompt filesystem race tests | `go test -race ./internal/framework/llm ./internal/framework/promptfs` | Pass | -| 2026-08-08 | Composed CLI and D&D prompt-cache tests | `go test ./internal/cli ./internal/modules/dnd/register` | Pass | -| 2026-08-08 | Audit target integrity before generic/Seriatim review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Generic and Seriatim graph/code review | Architecture clusters, exact symbol reads, call traces, scoped caller/search checks, and complete implementation/test inspection across input parsing, chunk planning, typed merge/normalize helpers, validators, JSON output, registration, evidence preparation, and output publication | MOD-001 through MOD-003 recorded; source/domain boundaries and live ownership paths otherwise confirmed | -| 2026-08-08 | Generic and Seriatim module tests | `go test ./internal/modules/generic/... ./internal/modules/seriatim/...` | Pass | -| 2026-08-08 | Published source-artifact codec tests | `go test ./internal/framework/chunkmap ./internal/framework/evidencecontext` | Pass | -| 2026-08-08 | Composed evidence/output contracts | Focused `go test` runs in `./internal/framework/pipeline` and `./internal/cli` for evidence preparation/publication, maintained minimal JSON output, and production chunk-map provenance | Pass | -| 2026-08-08 | Generic and Seriatim import boundaries | Direct `go list` import-edge audit plus scoped transcript-adapter import search | Pass; no D&D dependency in generic/Seriatim packages and no production import of the transcript adapter outside Seriatim registration | -| 2026-08-08 | Audit target integrity before shared D&D review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Shared D&D graph/code review | Scoped architecture, exact symbol reads, inbound traces, and complete implementation/test inspection across ten durable types/codecs, candidate JSON, source-reference utilities, resolver/reconciliation/diagnostics, typed mergers, evidence, registration, default chains, shared assets, and representative family prompt/schema owners | DND-CORE-001 recorded; family registration, codec ownership, reference/evidence separation, shared reconciliation safety, and typed adapter boundaries otherwise confirmed | -| 2026-08-08 | Required shared D&D tests | `go test ./internal/modules/dnd/codec/... ./internal/modules/dnd/shared/... ./internal/modules/dnd/register` | Pass | -| 2026-08-08 | Audit target integrity before registry-family review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Registry-family graph/code review | Exact symbol reads, complexity queries, and call traces across NPC, item, and location extraction, canonicalization, identity, immutable registries and projections, reconciliation eligibility/application/retry/fallback, normalization, validation, codecs, prompt assets, schemas, and focused tests | DND-REG-001 through DND-REG-004 recorded; name/anchor identity, same-name location, currency, proposal safety, diagnostics, fallback, and immutable projection policies otherwise confirmed | -| 2026-08-08 | Required NPC, item, and location registry tests | `go test ./internal/modules/dnd/extract/npcregistry ./internal/modules/dnd/extract/itemregistry ./internal/modules/dnd/extract/locationregistry ./internal/modules/dnd/npcs/... ./internal/modules/dnd/items/... ./internal/modules/dnd/locations/... ./internal/modules/dnd/normalize/npcregistry ./internal/modules/dnd/normalize/itemregistry ./internal/modules/dnd/normalize/locationregistry ./internal/modules/dnd/validate/npcregistry/... ./internal/modules/dnd/validate/itemregistry/... ./internal/modules/dnd/validate/locationregistry/...` | Pass | -| 2026-08-08 | Audit target integrity before occurrence-family review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Occurrence-family graph/code review | Exact symbol reads, complexity queries, and call traces across NPC, item, and location semantic registry projections/resolution, response adaptation, current-source evidence attachment, canonical ordering/deduplication, normalization, validation, codecs, prompt assets, private schemas, and generated-reference tests | DND-OCC-001 through DND-OCC-003 recorded and DND-REG-001 broadened; all-or-nothing identity attachment, evidence separation, category/holder/quantity/same-name policy, nil/empty ownership, and handoff behavior otherwise confirmed | -| 2026-08-08 | Required NPC, item, and location occurrence tests | `go test ./internal/modules/dnd/extract/npcoccurrences ./internal/modules/dnd/extract/itemoccurrences ./internal/modules/dnd/extract/locationoccurrences ./internal/modules/dnd/normalize/npcoccurrences ./internal/modules/dnd/normalize/itemoccurrences ./internal/modules/dnd/normalize/locationoccurrences ./internal/modules/dnd/validate/npcoccurrences/... ./internal/modules/dnd/validate/itemoccurrences/... ./internal/modules/dnd/validate/locationoccurrences/...` | Pass | -| 2026-08-08 | Generated occurrence handoff tests | `go test ./internal/cli` | Pass | -| 2026-08-08 | Audit target integrity before spell/scene-family review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Spell and scene graph/code review | Scoped architecture, exact symbol reads, complexity inspection, and call traces across whole-source scene planning, framework plan canonicalization/materialization, chunk-map serialization/publication, per-chunk scene extraction, normalization, validation and eligibility projection, effective spell catalog composition, NPC grounding, response canonicalization, normalization, validation, checkpoint identity, retry, codecs, prompt assets, schemas, and focused tests | DND-SCENE-001 and DND-SCENE-002 recorded; DND-REG-001, DND-REG-002, and PIPE-002 broadened; structural/evidence separation, exact scene eligibility, and catalog/checkpoint behavior otherwise confirmed | -| 2026-08-08 | Required spell, scene chunking, and scene-description tests | `go test ./internal/modules/dnd/chunk/scenes ./internal/modules/dnd/extract/scenedescriptions ./internal/modules/dnd/normalize/scenedescriptions ./internal/modules/dnd/validate/scenedescriptions/... ./internal/modules/dnd/scenedescriptions/... ./internal/modules/dnd/extract/spells ./internal/modules/dnd/normalize/spells ./internal/modules/dnd/validate/spells/... ./internal/modules/dnd/spells/...` | Pass | -| 2026-08-08 | Audit target integrity before combat/enemy review | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Combat and enemy graph/code review | Scoped architecture, exact symbol reads, complexity inspection, and call traces across scene gates, optional NPC grounding, required enemy projections, response mapping, chronology, normalization/deduplication, extract/normalize validator chains, engagement identity, codecs, prompts, private schemas, generated references, retry/checkpoint identity, maintained CLI example, and focused tests | DND-COMBAT-001 recorded; DND-REG-001 through DND-REG-003 and DND-SCENE-002 broadened; exact eligibility, source-free grounding, collective labels, engagement uniqueness, observation preservation/order, and generated handoffs otherwise confirmed | -| 2026-08-08 | Required combat-turn and enemy-event tests | `go test ./internal/modules/dnd/extract/combatturns ./internal/modules/dnd/normalize/combatturns ./internal/modules/dnd/validate/combatturns/... ./internal/modules/dnd/extract/enemyevents ./internal/modules/dnd/normalize/enemyevents ./internal/modules/dnd/validate/enemyevents/... ./internal/modules/dnd/enemyevents` | Pass | -| 2026-08-08 | Combat and enemy durable codec tests | `go test ./internal/modules/dnd/codec/combatturns ./internal/modules/dnd/codec/enemyevents` | Pass | -| 2026-08-08 | Assembled combat and generated-reference integration tests | `go test ./internal/modules/integration/...` | Pass | -| 2026-08-08 | Generated combat/enemy handoff and publication tests | `go test ./internal/cli` | Pass | -| 2026-08-08 | Audit target integrity before final synthesis | `git diff --quiet 92e89076a268089e703978fb9d7176200e93344c..HEAD -- . ':(exclude)docs/roadmap/**'` | Pass; production target unchanged | -| 2026-08-08 | Cross-cutting finding, test, and comment review | Complete finding reread against cited production owners and callers, focused-test inventories, complexity/comment hotspots, intentional-complexity entries, and coverage matrix | All 33 findings retained with distinct root causes; no new finding, contradiction, duplicate Test Quality issue, or unsupported comment issue found | -| 2026-08-08 | Fresh full test suite | `go test -count=1 ./...` | Pass | -| 2026-08-08 | Full race suite | `go test -race ./...` | Pass | -| 2026-08-08 | Full static analysis | `go vet ./...` | Pass | -| 2026-08-08 | Production build | `go build ./cmd/notarius` | Pass | -| 2026-08-08 | Final whitespace | `git diff --check` | Pass | -| 2026-08-08 | Full shuffled test suite | `go test -shuffle=on ./...` | Pass | - -## Coverage Matrix - -| Audit area | Status | Packages and documents inspected | Validation run | Finding IDs | -| --- | --- | --- | --- | --- | -| Architecture and dependency boundaries | Reviewed | Architecture, documentation, and testing policies; internal overview; accepted ADRs; `internal/cli/catalog.go`; production registrars; root `assets` package; representative pipeline, typed-codec, output, and state-owner symbols | Full baseline, fresh graph, direct import map, cross-layer call traces, ADR link scan | ARCH-001 | -| Configuration and CLI composition | Reviewed | `docs/config.md`, `docs/cli.md`, `docs/operations.md`, internal configuration/CLI docs; `internal/core/config/`; CLI run, catalog, session, profile, result, and terminal owners; focused config, command, run, reference, recomputation, session, production, example, result, and state tests | Target-integrity check, graph call/data-owner traces, YAML decoder contract, focused tests and vet | CFGCLI-001, CFGCLI-002 | -| Pipeline resolution, preparation, and typed registries | Reviewed | Internal pipeline/module docs; `internal/framework/contracts/`; pipeline profile, options, module, construction, preparation, fingerprint, stage/validator/chain/codec/evidence registry implementations and focused tests | Target-integrity check, graph architecture/complexity/call traces, focused tests and vet | PIPE-001, PIPE-002 | -| References and ordered handoffs | Reviewed | Reference and ordered-step sections of configuration, internal pipeline, and state docs; pipeline reference resolution/materialization, preparation ownership, generated handoff, consumer fingerprint, checkpoint hydration, and runner barriers; CLI selector/recomputation owners; focused profile, reference, handoff, checkpoint, recomputation, and assembled integration tests | Target-integrity check, graph architecture/complexity/call traces, focused pipeline/CLI tests, assembled integration tests | REF-001, REF-002, REF-003 | -| Execution, validation, retry, and concurrency | Reviewed | Internal pipeline runtime contract; runner, chunk planning/validation, concurrent lane engine, typed execution/validation, retry/normalize, synchronization, output suppression, and focused concurrency, retry, rejection, session, typed-checkpoint, debug, manifest, candidate-encoding, and handoff tests | Target-integrity check, graph state-machine/call/complexity review, race tests, fresh tests, shuffled tests | RUN-001, RUN-002, RUN-003, RUN-004 | -| State, checkpoints, debugging, and file safety | Reviewed | State and operations docs plus architecture state/security policy; CLI output, cache-root, checkpoint identity, recomputation, debug allocation, and terminal owners; core file I/O, debug bundle, and source digest/clone helpers; framework checkpoint, chunk-plan, chunk-map, debug, evidence-context implementations and focused tests | Target-integrity check, graph architecture/complexity/call traces, state collaborator race tests, CLI tests | STATE-001, STATE-002, STATE-003 | -| LLM runtime, prompt filesystems, and assets | Reviewed | LLM internal/integration/configuration/operations docs and related ADRs; scheduled client, scheduler, PromptKit adapter/profile inspector, profile/source fingerprints, redaction, debug, asset registry, schema loader, promptfs implementations and focused tests; root assets, fallback profile, all fourteen module manifests and prompt YAML files, shared/model-visible fragments, private response schemas, and representative composed loaders | Target-integrity check, graph architecture/symbol/call review, content scan and exact prompt-order comparison, focused race tests, composed CLI and D&D prompt-cache tests | LLM-001, LLM-002, LLM-003, LLM-004 | -| Generic and Seriatim modules | Reviewed | Internal module guide; Seriatim, JSON output, chunk-map, and evidence-context integration contracts; all implementation/tests under `internal/modules/generic/` and `internal/modules/seriatim/`; framework evidence preparation/output paths and focused tests; maintained CLI example and production output contracts | Target-integrity check, graph architecture/symbol/call/caller review, direct import map, required module and codec tests, focused composed evidence/output tests | MOD-001, MOD-002, MOD-003 | -| Shared D&D types, codecs, and family mechanics | Reviewed | D&D internal/module docs and all D&D integration contracts; root durable types; all ten codec packages and candidate JSON; shared references, ordering, citations, inputs, comparison, diagnostics, registry resolver, entity reconciliation, and assets; typed merger/evidence/default-chain/fallback/family registration; representative module asset declarations and focused tests; all lane-specific identity, grounding, order, and eligibility exceptions | Target-integrity checks, scoped graph architecture/search/traces, completed ten-family convention matrix, required codec/shared/register and lane-family tests | DND-CORE-001, DND-REG-001, DND-COMBAT-001 | -| NPC, item, and location registries | Reviewed | NPC/item/location registry integration contracts and relevant identity/evidence ADRs; extractors, candidate models and response schemas; identity, immutable registry, prompt/identity projection, location grounding, reconciliation, normalizer, validators, codecs, prompt assets, and focused tests for all three families | Target-integrity check, scoped graph architecture/complexity/search/traces, full family comparison, required extractor/identity/registry/normalizer/validator tests | DND-REG-001, DND-REG-002, DND-REG-003, DND-REG-004 | -| NPC, item, and location occurrences | Reviewed | NPC/item/location occurrence integration contracts and deterministic opaque-ID ADR; extractors, private response models/schemas, semantic registry projections and resolvers, canonicalizers, normalizers, validator chains, codecs, prompt assets, and generated/external registry handoff tests for all three families | Target-integrity check, scoped graph architecture/complexity/search/traces, full family comparison, required extractor/normalizer/validator tests, generated CLI handoff tests | DND-REG-001, DND-OCC-001, DND-OCC-002, DND-OCC-003 | -| Spells, scene chunking, and scene descriptions | Reviewed | Spell, overlay, scene-description, and accepted chunk-map integration contracts; D&D scene chunker and prompt/schema assets; framework plan canonicalization, validation, materialization, accepted chunk-map serialization/publication and production tests; scene-description extractor, normalizer, validators, immutable eligibility registry, codec, prompts, schemas, and tests; spell extractor, effective/base/overlay catalogs, NPC grounding, canonicalizer, normalizer, validators, codec, prompts, schemas, checkpoint/retry/CLI tests | Target-integrity check, scoped graph architecture/complexity/symbol/call review, full family comparison, required chunker/extractor/normalizer/validator/registry/catalog tests | PIPE-002, DND-REG-001, DND-REG-002, DND-SCENE-001, DND-SCENE-002 | -| Combat turns and enemy events | Reviewed | Combat/enemy integration contracts and D&D internals; extractors, scene/NPC resolvers, compact combat/opponent projections, canonicalizers, normalizers, shared enemy ordering/identity helpers, shape/source/relatedness/engagement/invariant validators, codecs, prompt assets, private schemas, focused and assembled integration tests, generated-reference CLI contracts, and maintained complete example | Target-integrity check, scoped graph architecture/complexity/symbol/call review, full family comparison, required extractor/normalizer/validator/helper tests, codec tests, assembled integration tests, generated CLI handoff/publication tests | DND-REG-001, DND-REG-002, DND-REG-003, DND-SCENE-002, DND-COMBAT-001 | -| Test ownership, comments, and final synthesis | Reviewed | Complete audit report; testing and documentation policies; focused-test inventories in configuration, CLI, pipeline, state, LLM, modules, and D&D internal guides; every finding's cited production owner, callers, tests, comments, and intentional-complexity entries | Target-integrity check, graph symbol/caller/complexity review, complete fresh and race test suites, vet, production build, whitespace check, shuffled suite | No new IDs; all 33 findings revalidated, including RUN-004 as the only independent comment defect | diff --git a/docs/roadmap/archive/warning-signal-and-presentation-audit.md b/docs/roadmap/archive/warning-signal-and-presentation-audit.md deleted file mode 100644 index c9bbc634..00000000 --- a/docs/roadmap/archive/warning-signal-and-presentation-audit.md +++ /dev/null @@ -1,648 +0,0 @@ -# Warning Signal And Presentation Audit - -## Executive Assessment - -Notarius warning execution is mechanically stronger than its operator-facing -presentation. Terminal-attempt promotion, stable ordering after concurrent -work, checkpoint replay, validation summaries, and debug retention are all -substantially correct. The audit found no general duplicate-append defect in -the extract, merge, or normalize handoffs and no leakage of abandoned-attempt -warnings into a successful result. - -The warning channel itself is not coherent. One flat `contracts.Warning` type -currently represents at least four materially different concepts: - -- actionable degradation or incomplete validation; -- heuristic data-quality doubt; -- successful but potentially reviewable fallback; and -- routine canonicalization, ordering, and deduplication observations. - -That conflation is the primary reason successful runs produce a count that is -large but operationally weak. The maintained complete D&D example demonstrates -the problem without a live provider: an approved run with no rejected outputs -published 12 warning records, all from three advisory relatedness checks. An -operator separately reported a successful complete D&D run with 10 outputs, -one rejection, and 85 warnings. The production bundle for that run was not -available in this environment, so its reason-code distribution could not be -measured. - -The current implementation also has four correctness or robustness gaps: - -1. warning records lose stage, step, lane, module, validator, and chunk - provenance when promoted, which makes safe aggregation and diagnosis - impossible from `warnings.json` alone; -2. there is no framework-level validation or aggregate bound, and the NPC- and - spell-relatedness validators bypass the D&D warning limiter entirely; -3. warnings returned by an output encoder are added after `warnings.json` has - already been encoded, so the receipt, stderr, debug bundle, and published - warning file can disagree; and -4. a skipped validator contributes to `incomplete` validation but does not - receive the warning generated for an exhausted validator failure. - -The recommended end state is a structured diagnostic contract with explicit -disposition, category, origin, occurrence count, and bounded samples. Warnings -are reserved for process-level degradation or incompleteness. LLM-judged or -deterministically inferred extraction-quality signals are advisories, never -warnings, and routine normalization observations remain inspectable without -being reported as top-level warnings. An ordinary successful run in which all -configured work completes normally should therefore report zero warnings. This -is an architectural and durable-contract change, not merely revised CLI prose. - -## Evidence And Limits - -The audit used: - -- a complete static search of production `contracts.Warning` constructors, - reason-code constants, result fields, and promotion sites under `internal/`; -- call-path inspection through producer attempts, validators, lane - coordination, chunk-plan reuse, checkpoints, output encoding, debug output, - CLI presentation, and run-result construction; -- the maintained complete and minimal D&D examples with offline fake LLMs; -- focused deterministic tests for warning bounds, semantic-reconciliation - fallback, `warn_continue`, semantic retries, terminal rejection, concurrency - ordering, and checkpoint reuse; and -- the operator-provided observation of an 85-warning complete D&D run. - -No provider-backed production run was attempted because this environment has -no API key. Consequently, the audit can establish warning mechanics, possible -multiplicity, synthetic volume, and obvious heuristic limitations, but cannot -estimate production frequency or the real false-positive rate of individual -D&D advisories. Those measurements are not required to choose the recommended -architecture; they are required before strengthening any heuristic advisory -into a rejection or setting a numerical production acceptance target. - -## Complete Warning-Producer Inventory - -### Framework And Generic Boundaries - -| Producer | Reason code | Trigger and consequence | Multiplicity and bound | Current surfaces and coverage | -| --- | --- | --- | --- | --- | -| Reference materialization in `internal/framework/pipeline/references.go` | `empty_reference` | A bound external reference is a valid, accepted media type but contains zero bytes. The prompt may receive materially incomplete context. | One per empty bound file; finite by configuration but no shared run-level cap. | Enters `RunInput.Warnings`; reference tests protect contextual scope. | -| Producer-attempt policy in `internal/framework/pipeline/producer_attempts.go` | `validator_execution_incomplete` | An applicable validator exhausted its execution budget and `warn_continue` accepted the otherwise valid candidate. | One per failed validator on each terminal candidate. An extract chain can multiply this by chunks and lanes. There is no global cap. | Durable warning, receipt count, stderr, debug, and validation summary. `TestWarnContinueRecordsOneWarningForEachExhaustedValidator` covers failures. | -| Chunk, extract, merge, normalize, and output module result contracts | Module-defined | A module may return arbitrary warnings with its successful candidate. | No contract validation, message limit, per-result cap, or global cap. Current production modules are inventoried below. | Terminal-attempt filtering and concurrency ordering are well tested. | -| Production JSON output encoder | None | The encoder copies incoming warnings into `warnings.json`; it does not currently create warnings. | Same count as its input. | JSON encoder and assembled-pipeline tests compare the incoming run warnings with the published file. | -| Output encoder result contract | Module-defined | Any output encoder may return warnings discovered during encoding. | Unbounded by contract. No production encoder currently exercises this capability. | Appended to final `RunOutput` only after logical files were encoded; this is the cross-surface defect described in AUD-WARN-004. | - -Input adapters and production mergers do not currently have independent -warning producers. Chunk-plan and checkpoint decisions are structured manifest -or debug provenance rather than warnings. Cancellation and hard persistence, -reference, parsing, serialization, and provider failures remain errors. - -### D&D Extraction Gates - -| Producer | Reason code | Trigger and consequence | Multiplicity and bound | -| --- | --- | --- | --- | -| `dnd/combat-turns` extractor | `scene_classification_unavailable` | The chunk has no exact matching scene-description classification. The extractor returns an empty accepted result and skips the LLM, so combat-turn output may be incomplete. | At most one per chunk for this lane. | -| `dnd/enemy-events` extractor | `scene_classification_unavailable` | The same missing or mismatched scene gate causes accepted empty enemy-event output. | At most one per chunk for this lane. | - -An exact non-combat classification produces an intentional empty result without -a warning. An exact combat classification proceeds normally. The two producers -share a code and operator consequence but use different messages; their module -origins are not retained in the final warning record. - -### D&D Source-Relatedness Validators - -All ten relatedness validators are deterministic advisories: they approve the -candidate and warn when contextual prose or an entity name is not lexically -present in cited text. Shape and source-reference failures are deliberately -left to blocking validators earlier in the chain. The same relatedness -validator is registered in both the extract and normalize default chain for -each artifact family in `internal/modules/dnd/register/chains.go`. - -| Artifact family | Warning reason | Per-record trigger | Local bound | Omission reason | -| --- | --- | --- | --- | --- | -| Combat turns | `combat_turn_not_near_source` | Actor token sequence absent | 20 per validator invocation | `combat_turn_relatedness_warnings_omitted` | -| Enemy events | `enemy_event_not_near_source` | Subject token sequence absent | 20 | `enemy_event_relatedness_warnings_omitted` | -| Item occurrences | `item_occurrence_source_unrelated` | Item name token sequence absent | 20 | `item_occurrence_relatedness_warnings_omitted` | -| Item registry | `item_not_near_source` | Item name token sequence absent | 20 | `item_relatedness_warnings_omitted` | -| Location occurrences | `location_occurrence_not_near_source` | Location name token sequence absent | 20 | `location_occurrence_relatedness_warnings_omitted` | -| Location registry | `location_not_near_source` | Location name token sequence absent | 20 | `location_relatedness_warnings_omitted` | -| NPC occurrences | `npc_occurrence_not_near_source` | NPC name token sequence absent | 20 | `npc_occurrence_relatedness_warnings_omitted` | -| NPC registry | `npc_not_near_source` | NPC name token sequence absent | **Unbounded** | None | -| Scene descriptions | `scene_description_not_near_source` | No significant title or summary token appears; up to two findings per scene | 20 | `scene_description_relatedness_warnings_omitted` | -| Spells | `spell_not_near_source` | Spell-name token sequence absent | **Unbounded** | None | - -The eight limiter-generated omission records are presentation artifacts, not -new source-relatedness conditions. They occupy a warning slot and make list -length differ from the actual occurrence count. - -### D&D Normalizers - -Every production D&D normalizer bounds its returned warning slice to 20 through -`internal/modules/dnd/shared/diagnostics`, including a final omission record -when needed. Registry semantic retries reserve space for their fallback -warning. The following table is complete by semantically distinct condition; -codes listed together are parallel artifact-family variants. - -| Condition | Reason codes | Result impact | Current classification assessment | -| --- | --- | --- | --- | -| Display or field whitespace/name canonicalization | `npc_fields_normalized`, `item_fields_normalized`, `location_fields_normalized`, `spell_name_canonicalized`, `combat_actor_canonicalized`, `enemy_event_name_canonicalized`, `item_occurrence_name_canonicalized`, `location_occurrence_name_canonicalized`, `scene_description_prose_normalized` | Deterministic successful mutation. The item-occurrence code can also describe `from`/`to` whitespace, not only the item name. | Routine observation. | -| Durable ID recomputation | `npc_id_recomputed`, `item_id_recomputed`, `location_id_recomputed` | Restores the deterministic name-derived ID. | Routine observation; invalid identity is separately rejected by default chains. | -| Source-reference sorting or deduplication | `source_references_normalized` | Sorts and removes exact duplicate references while deliberately preserving invalid references for their validators. | Routine observation. Shared code is useful but ambiguous without producer origin. | -| Canonical record ordering | `combat_turns_reordered`, `enemy_events_reordered`, `item_occurrences_reordered`, `location_occurrences_reordered`, `npc_occurrences_reordered`, `scene_description_order_normalized` | Deterministic order changes only. | Routine observation. | -| Exact or approved semantic duplicate consolidation | `duplicate_npc_collapsed`, `duplicate_item_collapsed`, `duplicate_location_collapsed`, `duplicate_spell_cast_collapsed`, `duplicate_combat_turn_collapsed`, `duplicate_enemy_event_collapsed`, `duplicate_item_occurrence_collapsed`, `duplicate_location_occurrence_collapsed`, `duplicate_npc_occurrence_collapsed`, `scene_description_duplicate_collapsed` | Removes duplicate records and preserves or combines canonical evidence according to the artifact policy. Registry codes cover both exact and accepted semantic consolidation. | Durable normalization observation; not normally operator-actionable. | -| Unresolved external membership | `spell_name_unresolved`, `item_occurrence_unknown_item_id`, `location_occurrence_unknown_location_id` | The value is preserved but is not grounded in the effective catalog or registry. Default chains normally reject the same condition before normalization; it remains reachable with validator overrides or defensive direct use. | Actionable data-quality warning. | -| Unsafe currency consolidation proposal | `item_semantic_proposal_invalid` | The proposed group is rejected and all records are preserved because denominations or currency/non-currency members are incompatible. The same code is also used internally as a retry reason. | Advisory about model proposal quality; no accepted-data loss. The control and diagnostic meanings should be separated. | -| Semantic reconciliation unavailable or exhausted | `npc_semantic_reconciliation_exhausted`, `item_semantic_reconciliation_exhausted`, `location_semantic_reconciliation_exhausted` | The safe deterministic result is accepted, but possible semantic duplicates remain. | Actionable fallback warning. | -| Local warning truncation | `npc_normalization_warnings_omitted`, `item_normalization_warnings_omitted`, `location_normalization_warnings_omitted`, `spell_normalization_warnings_omitted`, `combat_turn_normalization_warnings_omitted`, `enemy_event_normalization_warnings_omitted`, `item_occurrence_normalization_warnings_omitted`, `location_occurrence_normalization_warnings_omitted`, `npc_occurrence_normalization_warnings_omitted`, `scene_description_normalization_warnings_omitted` | Reports that individual records were omitted from presentation. | Group metadata, not an independent warning. | - -No production D&D normalization warning exposes raw model responses, -correction guidance, or provider errors. Most dynamic names are quoted and -truncated by the shared helper. That local discipline is not enforced by the -generic warning contract, and the spell relatedness message does not use the -shared truncation helper. - -## Warning Propagation And Surface Map - -```text -external-reference warnings -----------------------------+ - | -module candidate warnings -> validation chain warnings | - | | | - +---- producer-attempt terminal policy -------+ - | | - accepted / terminal rejection only | - | | - chunk or lane result in canonical order | - | | - checkpoint record/replay and ordered step merge | - | | - RunOutput.Warnings <------------+ - | - OutputRequest -> output encoder - | | - warnings.json OutputResult.Warnings - | - appended to final RunOutput only - | - receipt, stderr, final debug warning summary -``` - -### Attempts And Validation - -- `runProducerAttempts` promotes only the terminal accepted or terminal - rejected candidate's module and completed-validator warnings. Operational, - structural, semantic, and module-directed attempts that are superseded are - retained in attempt debug artifacts but not in the final collection. -- A module-directed semantic-reconciliation retry adds its fallback warning - only when no retry remains. Earlier attempt warnings are discarded. -- On `warn_continue`, warnings from the otherwise accepted candidate and - completed approved or rejected validators are retained. One fixed, - non-sensitive `validator_execution_incomplete` warning is added for every - failed validator. Skipped validators affect the validation summary and final - `incomplete` status but do not receive such a warning. -- A semantic terminal rejection retains only warnings from that rejected - attempt. Structural rejection after producer failure cannot retain a - candidate warning because no valid candidate result exists. - -These behaviors are protected by the producer-attempt, extract-handoff, -rejection-warning, normalize-retry, and attempt-debug tests. They are the right -foundation for the redesign and should not be replaced with early-exit or -all-attempt accumulation. - -### Concurrency And Ordering - -Extract jobs are dispatched chunk-first and lane-second. Results are stored by -chunk index, finalized in ascending chunk order, and lane continuations are -merged into a slice indexed by configured lane order. Pipeline steps run in -configured order. The resulting public order is therefore: - -1. pre-run reference warnings; -2. chunk-stage warnings; -3. step order; -4. configured lane order within each step; -5. chunk order within extract; -6. merge warnings; then -7. normalize warnings; followed by any output-result warnings. - -`TestRunnerBoundsExtractJobsAndStabilizesReverseCompletion` exercises warning -order under reversed completion. No completion-order leak was found. - -### Chunk Plans And Checkpoints - -- A reusable chunk plan stores producer warnings only. Current validators run - again, and their current warnings are appended. Warnings from a cached plan - candidate that fails current validation are discarded before regeneration. -- Accepted extract, merge, and normalize checkpoints store the terminal - warnings for their stage. Reuse loads and appends those warnings once at the - same logical handoff. Tests compare fresh and resumed warning collections and - preserve their order. -- Validation-incomplete accepted outputs are not reusable, preventing a later - run from silently treating incomplete validation as complete. -- Required accepted-normalize hydration replays that normalize checkpoint's - warnings; checkpoint decisions separately expose that reuse occurred. - -The recommended redesign should keep fresh and resumed logical diagnostics -equivalent. Whether a result was reused belongs in checkpoint provenance, not -in the diagnostic grouping key; adding a `reused` distinction would fragment -groups and make equivalent runs present differently. - -### Terminal Surfaces - -| Surface | Current content | Audience | Audit result | -| --- | --- | --- | --- | -| `RunOutput.Warnings` | Flat final slice | Framework and CLI | Canonical in-memory list, but lacks origin and bounds. | -| Published `warnings.json` | Object containing the warnings passed into the output encoder | Durable consumers | Exact for the production JSON encoder unless the encoder itself returns warnings. | -| `index.json` | Path to `warnings.json` | Durable consumers | Stable discovery path; no separate diagnostic-detail path. | -| Run-result v1 | `warning_count = len(final RunOutput.Warnings)` | Subprocess callers | Count only; no group/occurrence distinction. | -| Human stderr | `run completed with N warning(s)` | Operators | Count only and no direct detail path. Successful exit remains zero. | -| Manifest | Validation and rejection summaries, no warning collection | Durable provenance | Correctly avoids duplicating the flat list. | -| Debug summary `warnings.json` | Raw final warning array | Operators/developers | Includes final output-result warnings and can therefore differ from published `warnings.json`. | -| Debug run report | Final warning count | Operators/developers | Same final slice length as receipt and stderr. | -| Attempt/stage debug | Candidate-local warning detail and origin in path/envelope | Forensics | Sufficient to diagnose provenance, but debug capture is optional and is not a durable consumer contract. | - -## Empirical Measurements - -### Offline And Synthetic Runs - -| Scenario | Result | What it establishes | -| --- | --- | --- | -| Maintained complete D&D config and transcript with the repository's offline fake LLM | Approved, 10 normalized outputs, 0 rejected outputs, 12 warnings; receipt, stderr, and published file all reported 12 | An ordinary structurally successful workflow can be noisy without fallback or incomplete validation. | -| Same complete run, grouped after publication | Three reason codes, seven exact `(reason, scope, message)` tuples, maximum exact-tuple repetition of three | The flat count materially overstates distinct operator conditions. Scope resets within chunks and does not identify origin. | -| Maintained focused scene-description workflow | Approved, one normalized output, 0 warnings | The warning channel can be quiet when synthetic model text is lexically grounded. | -| Generic warning publication contract | One warning reaches successful stderr, durable output, and debug summary | The ordinary pre-output path is consistent. | -| NPC semantic-reconciliation candidate-limit fallback | No LLM call, all records preserved, one exhaustion warning, total warnings no greater than 20 | Fallback is bounded and materially different from routine normalization. | -| `warn_continue` with two failed validators and one skipped validator | Validation status contains all three incomplete validators; warning slice contains two execution-incomplete records | Current warning count does not describe all incomplete validation. | -| Retrying extract candidate | Two producer attempts; only the accepted attempt's one warning is final | Retry does not amplify abandoned warnings. | -| Terminal semantic rejection | Only the final rejected attempt's operation and validator warnings are final | Rejection diagnostics are retained without retaining superseded warnings. | -| Fresh versus reused extract checkpoint | Warning collections are deeply equal | Checkpoint replay does not itself amplify warnings. | -| Spell normalizer with 21 unresolved entries | 20 records: 19 samples plus one omission record saying two additional warnings were omitted | `warning_count` is neither exact occurrence count nor distinct-condition count. | - -The focused audit tests passed in `internal/cli`, -`internal/framework/pipeline`, the NPC-registry and spell normalizers, and all -D&D packages. - -### Bounded Sample Review - -The complete offline D&D run produced: - -| Reason | Count | Sample | Review | -| --- | ---: | --- | --- | -| `location_not_near_source` | 4 | `Moon Gate` was absent from cited text | Correctly identifies deliberately unsupported fake output. Three records shared the same exact tuple because chunk and stage origin were lost. | -| `location_occurrence_not_near_source` | 4 | A `Moon Gate` visit was absent from cited text | Correctly identifies the same unsupported registry-driven occurrence, but repeats the same operator concern across extraction and normalization. | -| `scene_description_not_near_source` | 4 | A title or summary had no significant exact token in cited text | Mixed value. Generic `session scene` prose is ungrounded, while `Arrival` versus transcript `arrive` illustrates an expected lexical false positive. | - -This fake workflow is an integration fixture, not a model-quality benchmark. -It nonetheless proves that the checks carry useful evidence while being too -imprecise and repetitive to serve as one-warning-per-record operator alerts. - -### Production Evidence Still Needed - -The reported 85-warning run establishes that high volume occurs in practice, -but the following remain unknown: - -- dominant production reason codes and stage/lane sources; -- unique group count versus repeated occurrence count; -- false-positive rate for each relatedness family; -- how much volume comes from normalization observations versus advisories; -- whether fresh and resumed production runs remain equivalent; and -- a defensible numerical acceptance target. - -If further data is worthwhile, the operator can supply the v1 receipt, -`warnings.json`, and manifest validation summaries without supplying transcript -or lane artifacts. An initial privacy-preserving report should group by reason -code and normalized scope family, count exact repeated tuples, and omit message -text. Reviewing heuristic precision requires a separately approved bounded -sample with its cited source context. - -## Classification Of Current Conditions - -| Target disposition | Current families | Result impact | Operator action | Durable placement | -| --- | --- | --- | --- | --- | -| **Warning** | Empty reference; validator failure or skip accepted under `warn_continue`; unavailable required scene classification; exhausted semantic reconciliation | A configured process completed under an allowed degraded or incomplete policy rather than completing normally | Correct reference/configuration, inspect provider/validator, or rerun | Actionable `warnings.json`, receipt summary, stderr summary, debug | -| **Advisory** | Source-relatedness heuristics; unresolved spell or registry membership; guarded invalid semantic proposal; any future LLM-judged uncertainty or extraction-quality signal | Uncertain data quality or poor model proposal, but accepted data is structurally valid and deterministic guards prevented unsafe mutation | Optional model/source review; no routine action for every record | Durable diagnostic detail and debug; never a top-level warning | -| **Observation** | Whitespace/name/ID/source-reference canonicalization; canonical ordering; exact and approved semantic duplicate consolidation | Successful intended normalization | None under normal operation | Durable bounded normalization diagnostics or debug; no stderr warning | -| **Not a diagnostic** | Rejection, invalid structure, cancellation, persistence error, provider failure under fail-run policy | Candidate or run did not complete according to policy | Inspect rejection/error and retry or correct input/configuration | Existing rejection, validation summary, error, and debug contracts | - -Exact and semantic duplicate consolidation should remain distinguishable in -category or reason metadata even though both are observations. Semantic -reconciliation exhaustion remains a warning because a capability was not -applied; successful approved consolidation is an observation because it is the -normalizer's intended work. - -## Ranked Findings - -### AUD-WARN-001 — The Flat Warning Type Destroys Signal Quality - -- **Priority:** High operator impact; high implementation leverage. -- **Evidence:** `contracts.Warning` has only scope, reason, and message. Routine - normalizer changes, heuristic doubt, fallback, and incomplete validation all - enter the same slice and the same CLI count. The offline complete run's 12 - records were all advisories; the operator observed 85 records in a successful - real run. -- **Impact:** Operators cannot tell whether a warning requires a rerun, a - configuration repair, optional review, or no action. Repeated routine output - trains them to ignore the channel. -- **Recommendation:** Replace the flat semantic contract with explicit - `warning`, `advisory`, and `observation` dispositions plus a small category - vocabulary. Do not infer disposition from message text or require every - downstream consumer to maintain a reason-code policy table. - -### AUD-WARN-002 — Warning Records Lose The Origin Needed For Diagnosis And Aggregation - -- **Priority:** High correctness and usability impact. -- **Evidence:** The runner knows stage, step, lane, module, validator, chunk ID, - and chunk index at promotion time, but `terminalWarnings` flattens module and - validator records into `[]contracts.Warning`. Per-chunk scopes such as - `locations[0]` and `occurrences[0]` then repeat without identifying their - chunk or producer. `source_references_normalized` is intentionally shared - across families and is therefore especially ambiguous. -- **Impact:** `warnings.json` cannot answer which stage or module produced a - record. Message- or scope-based deduplication would merge unrelated findings - or retain accidental duplicates. -- **Recommendation:** Keep module findings free of framework context, then have - the framework add a structured origin envelope before promotion. Validator - findings must retain validator identity instead of passing through - `validationReport.Warnings()` as a flat slice. - -### AUD-WARN-003 — Warning Volume Is Not End-To-End Bounded Or Validated - -- **Priority:** High robustness impact; medium immediate likelihood. -- **Evidence:** D&D's `LimitWarnings` caps most individual producers at 20, but - NPC- and spell-relatedness return one warning per record without the helper. - Every extract validator is invoked per chunk, all ten relatedness checks run - again after normalization, and there is no run-level collector. The generic - contract validates neither disposition nor reason/message size, UTF-8, - blankness, or total records. -- **Impact:** Warning memory and output grow with chunks, lanes, configured - validators, and record counts. Local omission records lose exact occurrence - semantics while still incrementing `warning_count`. -- **Recommendation:** Add a generic bounded diagnostic collector that preserves - exact occurrence counts and bounded samples. Validate all diagnostic fields - at the module/framework boundary. Immediately bring NPC and spell - relatedness under the existing cap if the full redesign is staged. - -### AUD-WARN-004 — Output Encoder Warnings Make Durable Surfaces Disagree - -- **Priority:** Medium current impact; high contract correctness risk. -- **Evidence:** `Runner.Run` passes existing warnings to `encoder.Encode`, then - the production encoder serializes `warnings.json`. Only after encoding does - the runner append `OutputResult.Warnings`. The receipt, stderr, debug summary, - and debug run report see the final slice; the already-created published file - cannot. No production encoder currently returns a warning, so ordinary JSON - runs do not trigger the defect. -- **Impact:** A valid output-module implementation can violate the documented - claim that `warning_count` describes the published warning collection. -- **Recommendation:** Remove successful output warnings from the output-module - contract unless a demonstrated use case requires them; encoding failures - should be errors and optional encoder observations should be debug data. A - two-phase finalize API is the viable but more complex alternative. - -### AUD-WARN-005 — Validation Skips Are Incomplete But Not Warned - -- **Priority:** Medium operator/correctness impact. -- **Evidence:** `firstIncompleteValidation` treats failed and skipped validators - alike, and validation summaries include both. `incompleteValidationWarnings` - emits records only for `validationFailed`. The focused test demonstrates - three incomplete validators but two warnings. -- **Impact:** A successful run can have `validation_status: incomplete` while - its warning count understates or even omits the affected validators. A caller - that checks only warnings receives a weaker signal than the manifest and - receipt status. -- **Recommendation:** Produce one aggregated incomplete-validation warning - group whose occurrences cover both failure and skip, while retaining typed - outcome and safe reason metadata in the validation summary. Do not expose - provider errors or arbitrary skip prose in model or operator messages. - -### AUD-WARN-006 — Relatedness Checks Are Useful But Repetitive And Lexically Weak - -- **Priority:** Medium operator impact; low acceptance-policy urgency. -- **Evidence:** Every family runs the advisory in both extract and normalize - chains. The complete fixture contains exact repeated tuples, and the checks - rely on exact normalized token sequences or a minimal significant-token - overlap. Reason naming drifts between `*_not_near_source` and - `*_source_unrelated`. -- **Impact:** The checks can catch unsupported entities, but aliases, pronouns, - inflection, and generic scene prose create predictable false positives. Flat - per-record presentation magnifies them. -- **Recommendation:** Retain the validators and their stage-local execution, - but classify and aggregate them as advisories. Normalize reason-code naming - when the diagnostic contract changes. Do not strengthen them into rejection - rules without a human-reviewed production evaluation. - -### AUD-WARN-007 — `warning_count` Has No Stable Operational Meaning - -- **Priority:** High downstream-contract impact. -- **Evidence:** The receipt and CLI use `len(output.Warnings)`. One list element - can be an omission summary representing several hidden occurrences; repeated - records can represent the same condition; and skipped validators can be - absent. A 21-occurrence spell test produces a list length of 20. -- **Impact:** The value is neither an exact occurrence count nor a distinct - warning-group count. Consumers cannot set policy or present a trustworthy - summary from it. -- **Recommendation:** Introduce explicit warning-group and warning-occurrence - counts in a versioned receipt. Do not silently redefine the v1 field. - -## Recommended Target Contract And Presentation Model - -### Diagnostic Model - -Use one validated internal diagnostic model with these concepts: - -- **disposition:** `warning`, `advisory`, or `observation`; -- **category:** a small enum such as `configuration`, `degradation`, - `validation_incomplete`, `data_quality`, `fallback`, or `normalization`; -- **reason code:** stable semantic identity owned by the producer; -- **origin:** framework-added phase/stage, step ID, lane ID, module key, - validator name, chunk ID, and chunk index when applicable; -- **occurrence count:** exact number of matching findings; -- **samples:** a small deterministic list of bounded scope/message pairs; and -- **omitted sample count:** `occurrence_count - len(samples)`, represented as - metadata rather than another diagnostic record. - -Errors and rejected outputs must not become diagnostic dispositions. A warning -means that the run completed under policy despite a process-level degradation -or incomplete configured operation. Advisory and observation dispositions can -describe accepted artifact quality and transformation provenance, but no -LLM-judged extraction-quality signal may be promoted to a warning. Validation -status remains authoritative for approval, rejection, and incomplete -validation. - -### Aggregation - -The framework runner should own aggregation after it enriches findings with -origin and before public output construction. Modules and validators retain -semantic ownership of disposition, category, reason, scope, and message; they -must not own CLI or file presentation. - -The default stable key should be: - -```text -disposition + category + reason_code -+ phase/stage + step_id + lane_id + module_key + validator_name -``` - -Chunk, record scope, and message text belong in samples and must not be part of -the group key. This groups repeated per-chunk findings without merging the same -code across distinct producers or pipeline locations. Group order should be -the first occurrence in the runner's existing canonical order; sample order -should follow the same order. A final canonical sort by the complete origin key -is also viable, but completion timing must never choose either order. - -Aggregation must be incremental and bounded. Producers should use a shared -collector that counts every occurrence while retaining only bounded samples; -the framework then merges producer groups without reconstructing counts from -omission prose. A global maximum group count is also required, with overflow -represented by structured aggregate metadata and with actionable groups given -priority over lower dispositions. - -### Durable Files - -Keep one canonical home for each class: - -- `warnings.json` should contain versioned, grouped actionable warnings only; -- a new `diagnostics.json` should contain versioned advisory and observation - groups only, avoiding duplication of warning groups; -- `index.json` should link both files; -- `rejected.json` and manifest validation summaries should retain their current - separate responsibilities; and -- debug bundles should retain candidate-attempt detail plus the final grouped - projections. - -This is preferable to keeping all detail in `warnings.json` and filtering only -the CLI: downstream consumers would otherwise continue to receive a semantically -mixed warning contract, and routine observations would still dominate the -durable file. - -### CLI And Receipt - -For a successful human run with actionable warnings, print a concise summary -such as: - -```text -notarius: run completed with 2 warning groups (7 occurrences); details=/.../warnings.json -``` - -Advisories and observations should not produce the warning line. Their durable -path remains discoverable through `index.json`; a concise non-warning count can -be added to the ordinary success line only if operator testing shows value. An -ordinary successful run with no process degradation should write nothing to -the warning stream even when it publishes quality advisories or normalization -observations. - -Create `notarius.run-result.v2` rather than redefining v1. It should expose at -least: - -- `warning_group_count`; -- `warning_occurrence_count`; and -- `diagnostic_group_count` for non-warning durable groups. - -The receipt should continue to expose validation status, validation summaries, -and rejected-output count independently. Process exit behavior should not -change as part of warning presentation reform. - -### Checkpoint Semantics - -Store the structured terminal diagnostic groups with accepted checkpoints and -replay them exactly once at their logical stage. Fresh and reused runs should -produce the same public groups and counts. Checkpoint events and debug records, -not diagnostic identity, should disclose whether computation was reused. - -### Output Encoder Boundary - -Prefer removing `OutputResult.Warnings`. A successful output encoder should -either return the complete logical files or fail. If future encoders genuinely -need to produce durable post-encoding warnings, introduce an explicit -two-phase prepare/finalize contract so those warnings can be included in the -same published collection. Do not retain the current self-inconsistent -one-pass capability. - -## Resolution Of Required Design Questions - -| Question | Recommendation | Viable alternative and tradeoff | -| --- | --- | --- | -| Explicit severity/disposition or external reason mapping? | Put validated disposition and category in the contract. | A central reason-code registry avoids payload fields but makes new modules depend on a second synchronized policy table and leaves downstream meaning implicit. | -| Keep all detail in `warnings.json` or separate it? | Separate grouped actionable warnings from grouped advisories/observations in `diagnostics.json`. | Keep the flat durable list and aggregate only CLI output; simpler migration, but it preserves the noisy downstream contract and ambiguous count. | -| Who owns aggregation? | Framework runner/coordinator after origin enrichment. | Output module aggregation keeps framework types smaller but duplicates policy across encoders and cannot repair missing validator origin. | -| Stable aggregation key? | Disposition, category, reason code, and full producer origin; exclude chunk/scope/message. | Explicit producer-supplied grouping keys offer flexibility but add another identity that can drift from reason codes. Message-template grouping is brittle and unsafe. | -| Samples and omissions? | Exact occurrence count plus deterministic bounded samples and numeric omitted-sample count. | Omission warning records preserve the current representation but inflate group counts and require prose parsing. | -| `warning_count` semantics? | Version receipt and replace ambiguity with group and occurrence counts. | Keep v1 count as published record length and add optional fields; compatible, but two competing warning counts remain easy to misuse. | -| Which normalization changes remain warnings? | Only exhausted process fallback. Unresolved membership is a data-quality advisory; successful canonicalization, reordering, ID repair, source-ref dedupe, and duplicate consolidation are observations. | Treat unresolved membership or semantic duplicate consolidation as warnings because they affect grounding or cardinality; more conservative, but it violates the process-only warning rule and reports accepted artifact quality as an operational failure. | -| Source-relatedness disposition? | Grouped advisory by default; preserve current approve behavior. | Retain warning disposition or make rejection configurable. Rejection requires production precision evidence; current lexical rules are not strong enough. | -| Checkpoint-loaded warnings? | Present the same logical groups as fresh execution and use checkpoint events for reuse provenance. | Mark groups as replayed; aids forensics but fragments aggregation and makes semantically equivalent runs differ. | -| ADR and schema versions? | Add an ADR and version the run receipt and diagnostic files. | Treat the work as CLI-only presentation and avoid an ADR; insufficient because module contracts, output files, checkpoint payloads, and downstream fields change. | - -## Compatibility, Documentation, And ADR Implications - -The target alters public and internal contracts enough to require a new ADR. -It should record: - -- the distinction among warnings, advisories, observations, rejections, and - errors; -- the invariant that warnings are process-level signals, LLM-judged extraction - quality is never a warning, and ordinary non-degraded success has zero - warnings; -- module semantic ownership versus framework origin/aggregation ownership; -- bounded group and sample semantics; -- fresh/checkpoint equivalence; and -- the output-encoder decision. - -Implementation should introduce `notarius.run-result.v2`. The grouped warning -and diagnostic envelopes should each carry their own schema version. Because -the content of `warnings.json` changes incompatibly from a flat array wrapper -to groups, release notes and the published JSON integration contract must call -out the migration. `index.json` gains the diagnostic file path. - -Canonical documentation updates belong in: - -- `docs/cli.md` for stderr presentation only; -- `docs/operations.md` for operator review and debug workflow; -- `docs/integrations/json-output.md` for warning and diagnostic file schemas; -- `docs/integrations/run-result.md` for v2 fields and compatibility; -- `docs/consumers/subprocess.md` and `docs/consumers/dnd-pipeline.md` for - downstream policy checks; -- `docs/internal/pipeline.md` for promotion, aggregation, retry, and checkpoint - mechanics; -- `docs/internal/modules.md` and `docs/internal/dnd.md` for producer rules and - the D&D classification matrix; and -- `docs/policy/architecture.md` for the durable ownership invariant after the - ADR is accepted and implemented. - -No configuration knob is required for the first implementation. A fixed, -well-documented taxonomy is easier to reason about than per-reason display -overrides. Configurable escalation or suppression can be considered only after -production review demonstrates a concrete operator need. - -## Test Coverage Assessment - -Existing coverage worth preserving includes: - -- accepted-attempt and terminal-rejection warning promotion; -- validator failure retry exhaustion and `warn_continue`; -- module semantic retry fallback; -- deterministic warning order under concurrent lane completion; -- chunk-plan invalidation and discarded-cache warning behavior; -- fresh/checkpoint warning equivalence; -- local D&D warning caps and safe dynamic-message quoting; -- JSON warning-file publication; and -- CLI stderr, debug, and receipt counts. - -Material gaps are: - -- no bound test for NPC- or spell-relatedness warnings; -- no generic warning-field or result-size validation; -- no test for output encoder warnings versus published `warnings.json`; -- no operator-level aggregation or bounded-sample tests; -- no fresh/resume test for grouped counts because groups do not yet exist; and -- no production evaluation of advisory precision. - -Tests should protect the semantic relationships: exact occurrence counts, -bounded samples, deterministic group order, actionable-only warning -presentation, and cross-surface equality. They should not assert one exact -warning count for every complete D&D run or treat message wording as a public -API unless the wording itself enforces a security boundary. - -## Audit Conclusion - -The application is in a good position for warning reform. Its retry, -validation, checkpoint, and concurrency mechanics provide reliable points at -which to attach structured diagnostics. The most valuable change is not to -suppress individual reason codes; it is to replace the semantically flat, -origin-free collection with bounded typed groups and to reserve the word -“warning” for conditions that merit operator attention. - -Provider-backed runs would improve prioritization and help tune the D&D -advisories, but they are not necessary to conclude that routine normalization -and heuristic doubt should not dominate stderr or the durable warning -contract. They should be gathered before changing heuristic acceptance policy -or adopting a numerical production warning-volume target. diff --git a/docs/roadmap/audit/01-correctness.md b/docs/roadmap/audit/01-correctness.md deleted file mode 100644 index d55ffd6d..00000000 --- a/docs/roadmap/audit/01-correctness.md +++ /dev/null @@ -1,178 +0,0 @@ -# Functional Correctness Audit - -## Baseline And Scope - -Reviewed revision `3887d89b763b7040efc866d4a57eb910d8778730` on 2026-11-24. -This is an audit of current behavior, not only the recent ReleaseKit changes. -Production code and repository tests were not modified. - -The review followed the implemented boundaries and their established contracts: - -| Area | Correctness concerns examined | -| --- | --- | -| CLI and configuration | Native loading/engine handoff, path origins and identifier normalization, reference overrides/unbinds, session/run composition, output and debug completion. | -| Source and chunk planning | Seriatim decoding and timestamps, source identity, document-position references, chunk materialization, accepted-plan reuse. | -| Pipeline orchestration | Complete assessment, initial/correction/fallback transitions, cancellation, ready-job dispatch and result ordering, merge/normalize execution, generated handoffs and reuse eligibility. | -| Domain transformations | Representative registry reconciliation and application, contextual identity resolution, spell/combat/item/location/enemy ordering and exact deduplication, scene normalization. | -| Output and state | Evidence-window union, JSON file naming and collisions, accepted-artifact codecs/cache I/O, confined atomic writes, partial publication and requested capture. | -| Release integration | Reused the immediately preceding stage-by-stage ReleaseKit review and its native build/version, profile, launcher, CI-template, and documentation checks; the subsequent cleanup changed documentation only. | - -Three reproducible numerical boundary defects warrant follow-up. No additional -ordinary-path correctness defect was substantiated in the inspected paths. -The scope is risk-directed rather than an exhaustive proof of every function or -every supported composition. Green tests do not cover the three cases below. - -## Finding 1: A Valid Large Generic Chunk Size Causes A Panic - -**Priority:** P2 — accepted module options can panic during ordinary planning. - -**Relevant code:** -[Chunker.Plan](../../../internal/modules/generic/chunk/units/chunker.go#L65), -especially the capacity expression at line 66; -[DecodeOptions](../../../internal/modules/generic/chunk/units/chunker.go#L108) -accepts positive `max_units` and non-negative overlap smaller than that maximum. - -**Circumstances and reproduction:** Parse a valid three-unit Seriatim document. -Decode the generic chunker options using -`map[string]any{"max_units": int64(math.MaxInt)}`, leaving overlap at zero, -construct the chunker with those options, and call `Plan`. On the reviewed -64-bit host the option is `9223372036854775807` and passes option decoding and -the checks at the beginning of `Plan`. - -**Expected:** A single range covering the whole three-unit document. A maximum -chunk size larger than the input should not require a large allocation. - -**Actual:** The ceiling-division numerator `len(units) + step - 1` overflows. -The resulting capacity is negative, and `make` panics with -`runtime error: makeslice: cap out of range` instead of returning a plan or an -error. The diagnostic harness recovered this panic only to record the result; -the production function does not recover it. A control with `max_units = 3` -returns the correct single range. - -**Reachability:** Unlike Finding 3's radius, `max_units` is a supported generic -chunker option. `pipeline.IntOption` admits the `int64` representation used by -ConfigKit dynamic option maps on the supported 64-bit platform. This is not a -claim that the default size of 50 is defective. - -**Potential remediation:** Use overflow-safe ceiling division for non-empty -input, such as `1 + (len(units)-1)/step`, or omit the optional preallocation. -Review endpoint arithmetic at the same boundary using remaining-length -comparisons rather than unchecked addition. No arbitrary new chunk-size limit -is needed. Follow-up tests should cover a small document with a maximum integer -chunk size, ordinary sizes, and overlap behavior. - -## Finding 2: Negative Timestamp Underflow Bypasses Non-Negativity Validation - -**Priority:** P2 — input-contract violation on an extreme numeric value. - -**Relevant code:** -[validTimestamp](../../../internal/modules/seriatim/input/transcript/adapter.go#L174), -especially the floating-point sign check at line 186 and exact rational parsing -at line 189. `sourceUnit` uses the returned rationals for start/end ordering. - -**Established contract:** The -[Seriatim input contract](../../integrations/seriatim.md#accepted-shape) -requires finite, non-negative start and end timestamps. Original numeric values -are retained in source-unit metadata. - -**Circumstances:** A negative timestamp has sufficiently small magnitude to -underflow `float64`, for example `-1e-1000`. `strconv.ParseFloat` returns negative -zero without an error. The expression `parsed < 0` is then false. Subsequent -`big.Rat.SetString` correctly recovers a genuinely negative value but its sign -is not checked. - -**Reproduction:** Call the production `transcript.New().Parse` with: - -```json -{ - "metadata": {}, - "segments": [ - {"id": 1, "start": -1e-1000, "end": 1, "speaker": "A", "text": "test"} - ] -} -``` - -**Expected:** Reject the negative start timestamp. - -**Actual:** Parsing succeeds and retains the negative timestamp in the document. -An ordinary `-1` start is correctly rejected; zero and a tiny positive value -are accepted. These controls and the defective case were executed against the -real adapter using a temporary diagnostic executable. - -**Potential remediation:** Check the exact parsed rational's sign with -`rat.Sign() < 0` before returning it, retaining the existing numeric/finiteness -handling unless a separate contract change is intended. This fixes the -underflow case without imposing a new magnitude restriction. Follow-up regression -coverage should include tiny negative/positive values, zero/negative zero, and -the existing high-precision start/end ordering case. - -## Finding 3: Context-Radius Addition Can Overflow And Omit All Evidence - -**Priority:** P3 — latent internal API defect; not reached by the current fixed -production defaults. - -**Relevant code:** -[Limits.Validate](../../../internal/framework/semanticreconcile/preparation.go#L42) -accepts every non-negative radius; -[Prepare](../../../internal/framework/semanticreconcile/preparation.go#L222) -adds that radius to each cited interval's ending position before applying `min`. - -**Established contract:** `Prepare` constructs bounded source-backed model -materials, and `Ready` means those materials are complete. `Limits` is an -explicit package input; no upper radius bound is established. The separate -byte budget already controls whether the resulting materials can be emitted. - -**Circumstances and reproduction:** Parse a valid three-unit document with IDs -1, 2, and 3. Supply two candidates citing unit 2 and unit 3, respectively. Take -`DefaultLimits()` and set `ContextRadius = math.MaxInt`, leaving the candidate -and byte budgets unchanged. On the reviewed 64-bit host the radius is -`9223372036854775807` and passes `Validate()`. - -**Expected:** Clamp the expanded context to the whole three-unit document. Since -that fits the existing byte budget, return `Ready` with all three units, marking -units 2 and 3 as cited. More generally, return the ordinary limit-exceeded -disposition if complete material exceeds the byte budget. - -**Actual:** `interval.end + limits.ContextRadius` wraps to a negative integer -before `min` can clamp it. Preparation returns `Ready`, no error, and: - -```json -{"windows":[{"units":[]},{"units":[]}]} -``` - -The same production function with radius 2 returns the expected three-unit -window. This was reproduced through the real `Prepare` API, not a copied -arithmetic example. A caller using the extreme accepted value could consequently -send a semantic reconciliation request without its supporting transcript text. - -**Current reachability:** The implemented D&D registry normalizers call -`DefaultLimits()` with radius 2 and expose no operator radius option. This is -therefore a package-boundary correctness issue, not evidence of missing context -in ordinary deployed runs. - -**Potential remediation:** Use overflow-safe clamping before addition: compare -the radius with the remaining distance to the last source position, and add -only when safe. The existing evidence-context builder's `expandEnd` demonstrates -this approach. Preserve the byte budget and accepted non-negative radius domain; -an arbitrary new maximum is unnecessary. A follow-up regression should exercise -an extreme radius, a normal radius, and existing byte-limit behavior. - -## Verification Performed - -Using Go 1.27.0, `GOWORK=off`, and `GOPROXY=off`: - -- `go test -mod=readonly ./...` passed, including cached results for unchanged - package inputs. -- `go vet -mod=readonly ./...` passed. -- Fresh focused tests (`-count=1`) passed for Seriatim input, semantic - reconciliation, evidence context, core configuration, and module integration. -- Race-enabled tests passed for pipeline, CLI, shared registry resolver, and - debug recorder. -- A temporary diagnostic executable, selected through a Go source overlay of - the CLI entry point, reproduced all three findings against the actual adapter, - reconciliation core, and generic chunker. It added no - repository tests or production edits. - -No model-quality evaluation, production inference, real API credential use, -source release publication, or hosted artifact delivery was performed. Upstream -kit internals were not independently audited as part of this application audit. diff --git a/docs/roadmap/audit/02-efficiency.md b/docs/roadmap/audit/02-efficiency.md deleted file mode 100644 index 2236999f..00000000 --- a/docs/roadmap/audit/02-efficiency.md +++ /dev/null @@ -1,277 +0,0 @@ -# Algorithmic Correctness, Efficiency, And Scalability Audit - -## Baseline And Scope - -Reviewed revision `e42031f2f6b9e8f29562a02a792dcbc59064bd7e` on 2026-11-24. -Its production code is unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; -the intervening commit records the [functional correctness audit](01-correctness.md). -This pass changed only this report. - -The review used code-graph discovery, current source and call-site inspection, -existing tests, and algorithmic cost analysis. It did not gather production -performance data, benchmark model calls, or audit the implementations of upstream -libraries. Findings describe opportunities for consideration, not approved new -contracts or an implementation plan. - -Expressly selected algorithms and boundaries were left intact: ordered step -barriers and the bounded ready-job pool; complete assessment of each candidate; -detached validator inputs; native continuation/history; typed codec handoffs; -bounded single-request semantic reconciliation; stable domain ordering and exact -identity rules; and the accepted-artifact cache policy. In particular, expensive -work required to emit or independently own the selected data is not itself a -finding. The findings below concern avoidable repeated work within those choices. - -## Architecture And Review Coverage - -Notarius remains a typed, modular Go pipeline: - -```text -input -> chunk -> ordered steps [extract per chunk -> merge -> normalize] -> output -``` - -ConfigKit owns configuration mechanics; CommandKit and its integrations own the -standard CLI surfaces; one native PromptKit engine owns model execution, -continuation, structural repair, and admission. The framework owns preparation, -assessment, ready-job coordination, generated-reference barriers, accepted-result -reuse, and output assembly. Domain modules own interpretation, normalization, -identity, validation, and contextual reference projections. Embedded assets remain -a content-only dependency. ReleaseKit owns native release mechanics. - -| Area inspected | Algorithmic assessment | -| --- | --- | -| Configuration, reference selection, resolution, and preflight | Predominantly linear walks, map lookups, and sorting for deterministic presentation. Nested loops over steps, lanes, slots, and kinds generally traverse different input dimensions, not repeated scans of one growing collection. No additional finding confirmed. | -| Source parsing and chunk planning/materialization | Document validation builds a position map; plan materialization retains resolved endpoints. Chunk copying is proportional to emitted material, including deliberately overlapping chunks. The numerical defects already in the correctness audit remain separate. | -| Pipeline scheduling, typed execution, and handoffs | Lazy ready-job dispatch avoids a goroutine per job. Generated outputs are indexed at the selected handoff boundary. Full assessment and detached ownership are deliberate costs, not optimization targets in this audit. | -| D&D extraction and citation validation | Whole-source index construction repeats per chunk; cited-text resolution scans uncited units for every record. Findings EFF-001 and EFF-002. | -| Domain normalization and identity | Exact duplicate grouping uses indexed identities. Some comparators repeatedly derive keys or recanonicalize evidence. Finding EFF-003. | -| Source-relatedness matching | Token-sequence matching uses a restart-at-each-position search. Finding EFF-004. | -| Semantic reconciliation and evidence output | Candidate/proposal membership uses maps; source windows and the evidence artifact use sorted/coalesced intervals. Request limits and fresh application to fixed originals are selected behavior and were not reconsidered. | -| Cache, diagnostics, file publication, and debug | Accepted results use direct keyed lookup; diagnostic identities are indexed and retained samples/groups are bounded. Incremental capture and atomic publication do not introduce another unbounded growing replay ledger. No additional algorithmic finding confirmed in these paths. | - -The review is risk-directed, not a proof of every possible composition. Four -efficiency opportunities and one collateral documentation inconsistency warrant -consideration. No additional executable correctness defect was confirmed; the -three findings in [01-correctness.md](01-correctness.md) still stand independently. - -## Findings - -### EFF-001 — Reuse The Full-Source Position Index Across Extraction Jobs - -**Priority:** P2 — transcript-size work is multiplied by chunk/lane count. - -**Evidence:** -[NewDocumentIndex](../../../internal/core/source/validation.go#L17) allocates and -fills a map by visiting every source unit. All ten D&D extractors construct this -full-source index per extraction invocation, directly or through -[NewSourceRefOrder](../../../internal/modules/dnd/shared/source_ref_order.go#L17). -Examples are [spells](../../../internal/modules/dnd/extract/spells/extractor.go#L119), -[item registry](../../../internal/modules/dnd/extract/itemregistry/extractor.go#L67), -and [scene descriptions](../../../internal/modules/dnd/extract/scenedescriptions/extractor.go#L81). -The construction precedes `RunProducer`, so an accepted-result cache hit does not -avoid it. Combat-gated extractors that return before construction are not counted. - -[runExtractJob](../../../internal/framework/pipeline/runner_concurrent.go#L268) -supplies the same source document to the jobs. The runner already has a run-local -lazy index for [cache decoding](../../../internal/framework/pipeline/runner_cache.go#L16), -but the extraction request does not expose that reusable snapshot. - -**Complexity:** Let `D` be the number of source units and `J` the number of -extraction invocations that build an index. Index construction alone takes -`Theta(J * D)` time and cumulative map storage allocation. With `L` applicable -lanes and `C` fixed-size chunks, `J = Theta(L * C)` and `C = Theta(D)`, giving -`Theta(L * D^2)` preprocessing despite linear total chunk content per lane. -Several concurrent jobs can also retain several identical `Theta(D)` maps. - -**Potential refactoring:** Prepare one immutable document-position snapshot per -run/source and make it available to extraction operations. Reuse it when forming -`SourceRefOrder`, retaining local construction for standalone callers that do not -receive one. `DocumentIndex` already hides its map and exposes read-only methods. -This reduces this preprocessing component to `O(D + J)`, with one shared `O(D)` -index rather than a full map per invocation. - -Preserve whole-document endpoint resolution, non-monotonic numeric IDs, -current-source cache checks, and standalone behavior. A chunk-only index would -not be an equivalent replacement. Do not remove assessment, source validation, -or required ownership copies, introduce a process-global document cache, or change -accepted-result identity to implement this improvement. - -**Follow-up verification:** Existing source-order, extractor endpoint-swap, -concurrent extraction, and current-source cache-hit tests should remain valid. -Check multiple source documents/runs and concurrent readers so an index cannot -leak across source identities. Validate the construction path by inspection or a -focused operation-count diagnostic; wall-clock production measurements are not -necessary to establish the improvement. - -### EFF-002 — Build Cited Text From Coalesced Ranges, Not A Document-Wide Bitmap - -**Priority:** P2 — sparse evidence still causes a full transcript scan per record. - -**Evidence:** -[CitationResolver.CitedText](../../../internal/modules/dnd/shared/citations.go#L26) -allocates a boolean slice of document length, marks every position of every -reference, allocates a parts slice with document-length capacity, and scans all -document units to select the marked text. Overlapping references mark the same -positions repeatedly. Even no references or a single-unit reference pay for the -full-document allocation and scan. - -The source-relatedness validators call this method for every artifact record; -see [item registry](../../../internal/modules/dnd/validate/itemregistry/source_relatedness/validator.go#L33) -and [spells](../../../internal/modules/dnd/validate/spells/source_relatedness/validator.go#L32). -This is separate from constructing the resolver's position index once per -validator invocation. - -**Complexity:** For one call, let `R` be the number of references, `S` the sum of -their inclusive span lengths counting overlap, and `B` the returned text size. -Current work is `O(D + R + S + B)`, with `Omega(D)` temporary allocation even for -sparse citations. For `A` records with one bounded citation each, resolution alone -is `Theta(A * D)`; `A = Theta(D)` makes this quadratic. Within one record, -`R` heavily overlapping document-wide ranges also cause `Theta(R * D)` marking -although the output includes each unit once. - -**Potential refactoring:** Validate and resolve endpoints through the existing -index, sort intervals by document position, coalesce their overlap/adjacency, -then join only the selected source-unit slices. After the resolver's one-time -index setup, this costs `O(R log R + U + B)` per record, where `U` is the number -of distinct cited units, and uses range/output-proportional temporary storage. -The [evidence-context builder](../../../internal/framework/evidencecontext/build.go#L17) -already demonstrates this approach. Share only a small pure interval operation -if useful; the text resolver need not construct a full evidence artifact. - -Preserve error handling, source-document order, one copy of each cited unit, -newline joining, and non-mutating inputs. Do not truncate citations, broaden the -cited context, or skip source-relatedness validation as an optimization. - -**Follow-up verification:** Retain -[citation resolver cases](../../../internal/modules/dnd/shared/citations_test.go) -for empty, invalid, disjoint, adjacent, overlapping, duplicate, and out-of-order -ranges. Add a sparse citation near the end of a large synthetic document and -non-monotonic unit IDs. Source-relatedness results should remain unchanged. - -### EFF-003 — Derive Invariant Sort Keys Once Per Normalized Record - -**Priority:** P3 — repeated citation scans and allocations inside comparators. - -**Evidence:** -[NPC occurrence ordering](../../../internal/modules/dnd/npcoccurrences/canonical.go#L29), -[location occurrence ordering](../../../internal/modules/dnd/normalize/locationoccurrences/normalizer.go#L245), -[item occurrence ordering](../../../internal/modules/dnd/itemoccurrences/itemoccurrences.go#L103), -and [enemy-event ordering](../../../internal/modules/dnd/enemyevents/enemyevents.go#L111) -call `EarliestValid` on both records for each comparison. That method scans every -reference. Their normalizers call these comparators while sorting the full merged -collection, even though a record's evidence does not change during the sort. - -Enemy events add another avoidable step: `normalizeEvent` canonicalizes evidence -once, but `Less` canonicalizes both slices again at its final tie-breaker. Thus -equal-chronology/name/kind comparisons allocate and sort already-canonical -evidence. The -[enemy invariant validator](../../../internal/modules/dnd/validate/enemyevents/invariants/validator.go#L90) -also uses that comparator after checking evidence order. The item occurrence -family already has canonical-input helpers from the previous audit; that completed -change is not being reopened here. Its remaining earliest-position scan can use -the same key preparation without changing those helpers' canonical-input premise. - -**Complexity:** For `N` records with `R` references each, deriving earliest -positions inside `O(N log N)` comparisons takes `O(N * R * log N)` work. That -factor is avoidable even when different earliest positions decide every -comparison. Enemy tie-breakers additionally repeat evidence canonicalization -and `Omega(R)` allocation per comparison; general canonicalization includes a -reference sort. Name normalization is likewise repeated when preceding keys tie. - -**Potential refactoring:** Decorate owned normalized records once with -`hasEvidence`, earliest position, and any needed normalized scalar name/kind -keys, then compare those keys. Use already-canonical evidence directly for the -remaining exact tie-breaker. The -[combat-turn normalizer](../../../internal/modules/dnd/normalize/combatturns/normalizer.go#L104) -already caches earliest positions in `normalizedRecord`. - -The earliest-key component becomes `O(N * R + N log N)` rather than -`O(N * R * log N)`, apart from the existing one-time evidence canonicalization. -Genuine lexicographic citation tie comparisons can still cost `O(R)`; this -recommendation does not claim every worst-case comparison becomes constant-time. -Keep defensive general-purpose comparison for arbitrary evidence where needed, -and use a canonical fast path only when the caller has established its premise. - -Preserve stable tie behavior, literal fallback ordering for invalid references, -nil/empty distinctions, kind order, exact deduplication, input-index diagnostics, -and all existing domain policies. This changes key preparation, not the expressly -selected canonical ordering algorithm or identity semantics. - -**Follow-up verification:** Compare normalization and invariant results on -permuted, tied, duplicate, and malformed evidence. Include many records with long -evidence lists and differing earliest positions, plus enemy records with equal -scalar keys but different evidence. Existing normalizer/model/invariant suites -are the primary behavioral protection. - -### EFF-004 — Avoid Restarting Token-Sequence Matching At Every Position - -**Priority:** P3 — low practical priority for ordinary short entity names. - -**Evidence:** -[ContainsTokenSequence](../../../internal/modules/dnd/shared/matching.go#L22) -normalizes/tokenizes both strings, then tests the entire query from each possible -start position. Most D&D source-relatedness validators use it to find contextual -names or actors in cited text. Those name fields do not impose a small fixed -token-count limit. - -**Complexity:** With `V` source tokens and `Q` query tokens, matching takes -`O(V * Q)` token comparisons in the worst case, in addition to normalization. -For example, a source consisting of repeated `a` tokens and a query containing -`Q - 1` copies of `a` followed by `b` forces a long failed match at every start. -Taking `Q` around `V / 2` makes this quadratic. Short fixed-length names -make the current matcher effectively linear, so this is a worst-case opportunity, -not evidence of a common production bottleneck. - -**Potential refactoring:** Keep `NormalizedTokens` and the chosen exact, -consecutive-token semantics. A prefix-function/KMP search over token strings -performs `O(V + Q)` token comparisons using `O(Q)` extra state. A small local -matcher is sufficient; fuzzy matching, an external search dependency, and a new -name-length restriction are unnecessary. Evaluate its small maintenance cost -after the higher-impact full-source repeated work is addressed. - -**Follow-up verification:** Retain Unicode normalization, punctuation, empty -query, exact token-boundary, and nonconsecutive-word tests. Include repeated -prefixes and near-matches; compare any replacement to a simple reference matcher -over a representative set of token sequences. - -## Collateral Documentation Correctness Finding - -### DOC-001 — Distribution Architecture Still Describes The Retired Source-Only Workflow - -**Priority:** P3 — contradictory current architecture guidance. - -[Architecture Policy / Platform And Distribution](../../policy/architecture.md#platform-and-distribution) -says that Notarius publishes no executable binaries or checksums. The adopted -[release policy](../../policy/release.md#release-model-and-completion), -[maintainer runbook](../../release.md), and -[ReleaseKit profile](../../../releasekit.json) instead select Linux/amd64 binary -and checksum delivery. This is stale wording, not an open distribution decision. - -Align the architecture summary with the implemented ReleaseKit-native release -model and link to the release policy for the publication/delivery contract. -Retain the existing Linux support and best-effort macOS development scope; -no additional targets, release gates, or distribution promises are needed. -No policy was edited during this code-audit pass. - -## Verification And Suggested Priority - -The default offline suite passed at the reviewed revision: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly ./... -``` - -Most package results reused Go's cache for unchanged code. Existing tests establish -current behavioral expectations; they do not prove the complexity bounds. Those -bounds come from the inspected loops, allocations, comparator call sites, and -scaling examples above. No new tests or production implementation were added. - -A fresh `-count=1` run also passed for D&D shared helpers/resolvers; enemy, NPC, -and location occurrence normalizers; the enemy validator packages; and spell/item -registry source-relatedness validators. Report link targets were checked locally; -the staged diff passed `git diff --check`. - -Address EFF-002 and EFF-001 first if this work is selected: they remove a full -transcript dimension from repeated operations. EFF-003 is a localized follow-up; -EFF-004 is lower priority because typical queries are short. DOC-001 is an -independent small documentation correction. The separately recorded numerical -correctness defects should not be treated as fixed by any of these optimizations. diff --git a/docs/roadmap/audit/03-complexity.md b/docs/roadmap/audit/03-complexity.md deleted file mode 100644 index 71a35fda..00000000 --- a/docs/roadmap/audit/03-complexity.md +++ /dev/null @@ -1,476 +0,0 @@ -# Complexity And Maintainability Audit - -## Baseline, Method, And Scope - -Reviewed revision `83352f78aea1e2dea23621688e83c7c0cf5ede7d` on 2026-11-24. -Production code is unchanged from -`3887d89b763b7040efc866d4a57eb910d8778730`; the subsequent commits contain the -[correctness](01-correctness.md) and [efficiency](02-efficiency.md) reports. -This pass changes only this report. - -A fresh full codebase-memory-mcp index, `notarius-complexity-audit`, provided -function length, branching, cognitive-complexity, call-site, and package-boundary -data. All indexed function/method pages were collected and their numeric metrics -ranked locally; 2,070 non-test Go symbols were available for production triage. -High-ranking test functions were examined separately. Source inspection and call -traces then distinguished actionable maintenance costs from necessary complexity. -The executable, excluded by the index, was inspected directly and remains a thin -native application entry point. - -No standalone `gocyclo`, `gocognit`, `golangci-lint`, or `staticcheck` executable -was found on PATH. No tool dependencies were installed. The graph's metrics are -heuristics, including nested callback bodies, not independent standardized scores -or proposed quality gates. Size and a high score alone do not justify refactoring. -No application tests, benchmarks, production runs, or empirical performance -measurements were conducted for this static audit. - -The review covered pipeline resolution/preparation/execution, native producer and -capture integration, CLI/configuration boundaries, D&D normalization and validation, -typed codecs, source metadata, semantic reconciliation, output/state helpers, -registrars, and representative high-complexity tests. It is risk-directed rather -than an exhaustive proof of every function. - -## Current Architecture - -Notarius retains the fixed typed pipeline: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -The composition root assembles native ConfigKit, PromptKit, and CommandKit -integration, registries, physical state, and reporting. The pipeline framework -owns typed preparation, complete candidate assessment, native producer coordination, -one bounded ready-job pool, ordered generated-reference handoffs, and accepted-result -reuse. Artifact families own domain interpretation, identity, normalization, -validators, codecs, and contextual projections. Assets remain content-only; -ReleaseKit owns release mechanics. - -The main maintenance pressure is concentrated in orchestration and repeated -adaptation code, not a need to replace these boundaries. The recommendations -retain native kit ownership, typed artifacts, domain-specific policies, fixed -stages, existing configuration choices, and current failure/ownership semantics. -They do not propose a new workflow engine, a general-purpose reflection layer, -new restrictions, or stronger release/security guarantees. - -## Measured Hotspots - -These are graph-reported source metrics at the reviewed revision. They guided -inspection; they are not acceptance thresholds. - -| Function | Source lines | Branch complexity | Cognitive estimate | Assessment | -| --- | ---: | ---: | ---: | --- | -| `pipeline.RunProducer` | 269 | 64 | 118 | Several stateful lifecycles in one function; CPLX-001. | -| `pipeline.validateGeneratedBindings` | 68 | 20 | 79 | Deeply nested orchestration plus per-binding rules; CPLX-002 and BUG-001. | -| `config.validatePipelineProfiles` | 89 | 26 | 74 | Repeated structural interpretation across packages; CPLX-003. | -| `cli.resolveCLIReferenceTargets` | 70 | 23 | 68 | Repeated scope-specific filtering and diagnostics; CPLX-003. | -| `source.cloneMetadataValue` | 82 | 25 | 67 | Mostly justified type-specific handling; a slice-identity defect is BUG-002. | -| `pipeline.ResolvePipeline` | 188 | 42 | 60 | Resolution orchestration mixed with structural checks; CPLX-002/003. | -| `pipeline.Run` | 252 | 43 | 51 | Stage execution mixed with debug/output envelopes; CPLX-005. | -| `pipeline.resolveReferenceTargetBindings` | 120 | 31 | 48 | Binding normalization, precedence, conflicts, and completeness together; CPLX-002. | -| `cli.selectedReferenceTargets` | 127 | 25 | 46 | Independently reconstructs selected composition; CPLX-003. | -| `cli.pipelineRunCommand` | 156 | 34 | 38 | Declaration, invocation lifecycle, and terminal presentation together; CPLX-006. | -| Registry `Normalize` methods | 127–133 each | 24–25 each | 27–28 each | Similar stateful lifecycle repeated in three packages; CPLX-004. | - -`pipeline/profile.go` is 1,635 lines and contains configuration/resolved types, -JSON handling, composition resolution, reference rules, validator selection, -copying, capability logic, and digest construction. `cli/reference_selectors.go` -is 588 lines. Their responsibilities, rather than those lengths alone, make -them useful consolidation/decomposition targets. - -## Findings Summary - -Priority below means relative value within a refactoring backlog, not a claim -that ordinary runs are failing. - -| ID | Priority | Scope | Opportunity | -| --- | --- | --- | --- | -| CPLX-001 | High | Within `framework/pipeline` | Make producer attempt state and execution phases explicit. | -| CPLX-002 | Medium | Within `framework/pipeline` | Separate resolution responsibilities and per-binding checks. | -| CPLX-003 | High | `core/config`, `framework/pipeline`, `cli` | Share structural pipeline interpretation and selected-target inventory. | -| CPLX-004 | High | Three D&D normalizer packages and shared helpers | Consolidate the common semantic-registry lifecycle. | -| CPLX-005 | Medium | Within `framework/pipeline` | Give runner stages cohesive private helpers. | -| CPLX-006 | Medium | Within `cli` | Separate native command declaration from invocation/capture lifecycle. | -| CPLX-007 | Medium | `core/config` and `framework/pipeline` | Give pipeline values one pure copying implementation, separate from normalization. | -| CPLX-008 | Low | CLI tests | Separate maintained-example checks by responsibility. | - -Two additional correctness defects are recorded after the refactoring findings. - -## Refactoring Findings - -### CPLX-001 — Producer Execution Has Too Much Coupled Mutable State - -**Evidence:** -[RunProducer](../../../internal/framework/pipeline/producer.go#L17) contains native -initial preparation/execution, accepted-result lookup, capture composition, -interpretation, assessment, continuation callbacks, terminal disposition, and cache -storage. Its local `evaluate` and native `Next` callbacks mutate `candidate`, -`guidance`, `failure`, `assessmentError`, and `accepted`; continuation adds pending -capture and recording-error state. Fourteen production callers across scene -planning, extraction, and normalization depend on this helper. - -**Maintenance cost:** Understanding one exit requires remembering which variables -were cleared by a previous callback, whether the response was delivered, whether -an error is fatal or permits fallback, and which capture remains unfinished. -Cache and capture branches obscure the central candidate lifecycle. Existing -comments protect important decisions, but the whole state must still be held in -the reader's head. - -**Potential refactoring:** Keep the public helper as the composition point and -introduce small private result/state values for a delivered candidate's -interpretation/assessment and an in-flight native attempt. Extract cohesive -initial/cache execution, candidate evaluation, and correction-request construction -functions or methods. Reuse the existing cache, capture, and terminal-disposition -helpers. A reader should be able to follow the top-level lifecycle without tracing -mutations across two large closures. - -Keep `Engine.Run`/`RunPrepared`/`Coordinate` native; do not introduce a replacement -completion interface or application retry/history engine. Preserve final-turn -assessment, candidate invalidation when another attempt begins, undelivered-result -handling, cancellation precedence, capture failures, cache-hit behavior, and -strict/permissive disposition. A private typed state object is useful only if it -makes these transitions clearer, not as a new extensibility framework. - -**Behavioral protection to inspect:** -[producer tests](../../../internal/framework/pipeline/producer_test.go), -[cache tests](../../../internal/framework/pipeline/producer_cache_test.go), -[native capture tests](../../../internal/framework/pipeline/native_capture_test.go), -and runner operation tests. Existing public behavior should survive internal -decomposition without tests of new private call sequences. - -### CPLX-002 — Pipeline Resolution Mixes Too Many Responsibilities In One File - -**Evidence:** -[profile.go](../../../internal/framework/pipeline/profile.go) combines public value -types and wire handling with resolution, reference precedence, generated dependency -validation, validator selection, profile application, cloning, capabilities, and -digesting. In -[validateGeneratedBindings](../../../internal/framework/pipeline/profile.go#L703), -five nested loops mix collection traversal with individual producer/slot/kind/media -checks. `resolveReferenceTargetBindings` contains a sizable captured `addBinding` -function as well as source normalization, overlay precedence, unbind handling, and -required-slot checks. - -**Maintenance cost:** Editing one concern requires navigating unrelated policy and -representation code. Deeply nested checks repeat scope formatting and hide which -facts have already been resolved. The delimiter-based producer-key defect below -is one concrete example of a local representation decision being easy to miss. - -**Potential refactoring:** Split cohesive types/copying, composition resolution, -reference resolution, and generated-binding validation into focused files in the -same package. Then extract per-binding validation from the traversal, passing a -small scope and already-indexed producers/slots. Separate pure reference-source -normalization from merging selected bindings. Keep the top-level resolver readable -as input/chunk selection, ordered lane resolution, dependency validation, effective -controls, and final digest construction. - -File splitting alone does not resolve the nested logic. Conversely, there is no -demonstrated need to split the package, add a generic stage interpreter, or replace -typed lookups with `any`. Preserve capability flow, exact Go-type compatibility, -configured validator order, generated-reference restrictions, required bindings, -and useful error context. Coordinate this work with CPLX-003 so it does not merely -create cleaner copies of duplicated structural logic. - -**Behavioral protection to inspect:** -[profile tests](../../../internal/framework/pipeline/profile_test.go), -[typed resolution tests](../../../internal/framework/pipeline/typed_resolution_test.go), -reference materialization and generated-handoff tests. - -### CPLX-003 — Three Packages Independently Interpret Pipeline Structure - -**Evidence:** -[config.validatePipelineProfiles](../../../internal/core/config/validation.go#L30), -[pipeline.ResolvePipeline](../../../internal/framework/pipeline/profile.go#L337), -and [cli.selectedReferenceTargets](../../../internal/cli/reference_selectors.go#L288) -each interpret flat artifacts versus explicit steps, trim/check identifiers, walk -lanes, and check selection constraints. The CLI additionally selects default -chunk/merge/normalize modules and performs kind-specific spec lookup independently -of framework resolution. Its scope matcher then repeats filtering for pipeline, -chunk, lane, and stage-qualified selectors. - -**Maintenance cost:** A change to pipeline structure, module defaults, or target -eligibility needs coordinated edits in loading validation, framework resolution, -and CLI reference expansion. These are legitimate callers with different jobs, -but maintaining separate interpretations makes drift more likely and explains -several of the highest complexity scores. - -**Potential refactoring:** Let the pipeline package own a small structural-layout -operation and a selected-target inventory built from that layout and the supplied -catalog. Reuse common identifier/step/lane rules in runtime-config validation and -resolution; let CLI selectors operate on the inventory rather than reconstructing -module selection. Keep CLI grammar, specificity/conflict presentation, and exact -override/unbind conversion in `cli`. - -The inventory must be usable before references are bound: CLI overrides can supply -otherwise-required slots. Calling full resolution first, or adding an -`allow_invalid_configuration` mode to bypass it, would recreate the dependency -problem. Keep separate source-aware ConfigKit presence/provenance validation and -catalog-dependent compatibility checks where they belong; do not force all -validation into one pass. ConfigKit still owns configuration mechanics. - -**Behavioral protection to inspect:** Runtime config validation/effective-config -tests, profile/typed-resolution tests, and CLI reference/override tests. Preserve -unselected-lane behavior, ordered-step restrictions, generated-binding protection, -pipeline-to-local precedence, and validation before reference-file reads. - -### CPLX-004 — Semantic Registry Normalizers Repeat A Stateful Lifecycle - -**Evidence:** The `Normalize` methods for -[NPCs](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go#L57), -[items](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go#L58), and -[locations](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go#L58) -repeat roughly 127–133 lines of similar control flow. Each retains merged input, -prepares fixed originals, records preparation/proposals, selects no-model or -bounded-model handling, runs the shared producer, replaces per-proposal findings, -constructs supported fallback, and attaches final diagnostics. Each also captures -mutable findings, omission details, and discarded-group state in nested callbacks. - -**Maintenance cost:** Fixes to final-candidate/fallback bookkeeping or evidence -recording need to be replicated in three packages. Domain differences are small -within this lifecycle but significant elsewhere: items guard currency and produce -advisories, while location identity includes evidence. A copy-and-edit pattern makes -it harder to see those actual differences. - -**Potential refactoring:** Add a small typed lifecycle helper in the D&D shared -layer, reusing `semanticreconcile` preparation/application and `pipeline.RunProducer`. -Pass domain-owned preparation/application/result functions and return explicit -per-proposal value, findings, guidance, and omission information instead of -updating unrelated captured variables. Centralize only the demonstrated common -execution/fallback/evidence bookkeeping. Keep domain preprocessing, identities, -compatibility guards, warning reason codes, and postconditions with the families. - -Do not build another reconciliation service, add another model loop, merge the -artifact types, or expose a universal JSON normalizer. If a proposed helper needs -many optional hooks for individual lines, extract smaller common phases instead. -Retain application of each proposal afresh to fixed originals and the separation -between a final safe proposal and the incoming merged-artifact fallback. - -**Behavioral protection to inspect:** The three normalizer packages' native -execution/fallback tests, typed reconciliation application tests, currency -compatibility cases, and final-proposal-only behavior. This complements CPLX-001; -it should call the producer helper rather than duplicate its state machine. - -### CPLX-005 — Runner Stages Are Obscured By Debug And Output Assembly - -**Evidence:** -[Runner.Run](../../../internal/framework/pipeline/runner.go#L90) spans 252 lines. -It validates input, wraps capture, parses and validates source, records source and -chunk envelopes, executes chunk production, builds the accepted chunk-map artifact, -runs steps, aggregates diagnostics, builds evidence context, invokes output, and -validates returned files. Stage operations alternate with large envelope literals, -cancellation checks, and failure wrapping. - -**Maintenance cost:** Readers must inspect the entire function to establish stage -ordering and what state can reach output. A change to capture representation or -auxiliary assembly takes place alongside core run-control decisions. - -**Potential refactoring:** Extract cohesive private parse-source, chunk/accepted-map, -and encode-output phases, with small typed phase results where helpful. Keep -`Run` as the ordered coordinator around those operations and the existing -`runPreparedSteps`. Let each helper own its applicable evidence envelopes and error -context. Avoid a generic string-named stage dispatcher or moving physical file -publication into the runner. - -Preserve cancellation boundaries, accepted/fallback eligibility, diagnostic -aggregation, no output after terminal stage failure, input/output ownership, and -requested-capture failure semantics. This is a local readability refactor, not a -change to the fixed pipeline or the ready-job algorithm. - -**Behavioral protection to inspect:** Runner operation, handoff, cache, concurrency, -metadata-isolation, evidence-output, and capture-failure tests. - -### CPLX-006 — The Run Command Owns Declaration And The Whole Invocation Lifecycle - -**Evidence:** -[pipelineRunCommand](../../../internal/cli/pipeline_run.go#L20) embeds a 156-line -native command construction/execution flow. It loads configuration, reports load -diagnostics, selects overrides, allocates identity/capture, constructs registries -and engine, preflights/materializes/prepares, reads input, selects session/cache, -runs the pipeline, publishes files, finalizes capture, and reports results. Its -`finish` closure reads and updates surrounding capture/publication/output state. - -**Maintenance cost:** Command wiring and lifecycle policy are difficult to review -independently. Every early return must use the right terminal path; understanding -that path requires inspecting several mutable variables captured from the handler. - -**Potential refactoring:** Keep the CommandKit declaration small and delegate to -an application-specific invocation function. Use a small private run-session value -for the actual shared terminal state—capture, optional observation group, useful -locations, publication state, and result summary—and an explicit finish operation. -Separate selection/preparation from execution/publication when it improves clarity. -Existing native loaders and upstream suites remain the configuration/CLI owners. - -Do not build a new command framework or universal result envelope. Preserve -supplied-value semantics, one selected configuration/engine, capture allocation -before native preparation, finalization before success reporting, retained causes, -and distinct execution/publication/report-delivery outcomes. This complements -CPLX-005 but remains a different owner: CLI placement/reporting is not runner work. - -**Behavioral protection to inspect:** -[native process tests](../../../internal/cli/native_process_test.go), run-command, -debug-capture, provider-accounting, and maintained-example tests. Keep assertions -about observable outcomes rather than private session helper calls. - -### CPLX-007 — Copying Pipeline Values Has Multiple Owners And Mixed Semantics - -**Evidence:** -[core/config/config.go](../../../internal/core/config/config.go#L44) independently -copies pipeline profiles, steps, lanes, module bindings, reference sources, -validator overrides, and options. The pipeline package owns those types but has -its own [binding/reference/override copies](../../../internal/framework/pipeline/validator_chain_registry.go#L84) -and [option copying](../../../internal/framework/pipeline/profile.go#L1445). -The pipeline helper called `cloneModuleBinding` also trims module/profile strings; -the configuration copy does not. Option-copy switches already differ: only the -pipeline version explicitly copies `[]string`, `[]byte`, and `json.RawMessage`. - -**Maintenance cost:** Adding a mutable field or supported option container requires -auditing multiple copying trees. Similar names conceal different copy-versus- -normalization behavior. This makes ownership reasoning harder even where current -loaded configurations behave correctly; the option differences alone are not -claimed here as a demonstrated production regression. - -**Potential refactoring:** Give pipeline-owned value types one pure copying -implementation usable by configuration conversion and framework callers, through -small clone functions or methods as appropriate. Keep trimming/default resolution -explicit and separate. Reuse only the copying operation across that boundary; -calling the current normalizing helper from configuration would change semantics. - -Preserve absence versus explicit empty controls/chains, independent mutable -containers, original configuration inspection, and supported option types. Do not -replace these copies with JSON round trips or merge them with source-metadata -validation, native evidence copying, or arbitrary deep reflection merely because -all of those operations copy data. They serve different contracts. - -**Behavioral protection to inspect:** -[effective-config ownership tests](../../../internal/core/config/effective_config_contract_test.go), -inheritance/inspection tests, validator-chain registry tests, and prepared-request -isolation tests. Verify the established option-container contract before unifying -the two switches rather than inventing a broader one. - -### CPLX-008 — Maintained-Example Testing Combines Several Independent Concerns - -**Evidence:** -[TestMaintainedExamplesLoadResolveAndList](../../../internal/cli/example_contract_test.go#L29) -has 117 lines and a graph cognitive estimate of 110. Nested example/pipeline loops -combine transcript parsing, configuration loading/materialization, complete lane -composition, generated references, development inheritance, and native list output. -A mutable `completePipelines` map makes the development comparison depend on the -parent having been processed earlier. - -**Maintenance cost:** Updating one example contract requires navigating checks for -several others. The fixture-processing order is mixed into assertion flow, which -adds context needed to understand failures. A high test score is not itself a -problem; this finding concerns these mixed responsibilities and shared setup state. - -**Potential refactoring:** Build clearly named resolved-example fixtures, then -separate loading/materialization, complete composition, development-vs-parent, and -listing checks into focused tests/subtests or short `t.Helper` assertions. Obtain -the explicit parent fixture for inheritance checks rather than depending on a -previous assertion loop iteration. Keep the example-specific expectations local. - -Retain the useful maintained-example integration coverage. Do not introduce a -general assertion DSL, duplicate every module's unit tests, or add snapshots and -new exact-default requirements to make this reorganization possible. - -## Additional Correctness Findings - -### BUG-001 — Generated-Producer Keys Can Collide - -**Priority:** P3 — unusual identifiers can select the wrong validation record. - -[validateGeneratedBindings](../../../internal/framework/pipeline/profile.go#L703) -indexes producer lanes by `step.ID + "\x00" + lane.ID`, then constructs the same -string for reference lookup. The mapping is not injective: - -```text -(step="a\x00b", lane="c") -> "a\x00b\x00c" -(step="a", lane="b\x00c") -> "a\x00b\x00c" -``` - -The step and lane identifiers remain individually distinct. Current structural -checks trim whitespace and enforce nonblank/unique identities; they do not reject -this embedded separator. Programmatic pipeline profiles can therefore reach this -case. JSON can represent the character as `\u0000` as well. - -The later producer overwrites the earlier one in the index. A reference to the -earlier producer then checks kind/media compatibility against the later producer. -For example, distinct artifact kinds can cause a valid earlier binding to be -rejected. This is a static counterexample derived from the actual key construction; -no runtime reproduction was performed. It is not a claim that runtime handoff -delivers the wrong artifact: that boundary already uses a struct key. - -**Potential correction:** Use the existing -[generatedOutputKey](../../../internal/framework/pipeline/handoff.go#L16) and -`generatedOutputKeyFor` for this resolver index too. Add a focused binding-validation -case with the two distinct pairs above and different producer kinds. No new -identifier-character prohibition is needed. This small correction can precede -CPLX-002/003. - -### BUG-002 — Cycle Detection Confuses A Slice View With A Cycle - -**Priority:** P3 — valid programmatically supplied metadata can be rejected. - -[CloneMetadata](../../../internal/core/source/metadata.go#L13) promises an owned -copy of JSON-shaped metadata while preserving concrete containers. Its recursion -tracker identifies maps/slices using only type and backing pointer in -[enterMetadataValue](../../../internal/core/source/metadata.go#L112). -For slices, the pointer is the first element's address, not the identity of the -visible slice view. Consider: - -```go -values := []any{"one", nil} -values[1] = values[:1] -metadata := map[string]any{"values": values} -``` - -The finite JSON value is `{"values":["one",["one"]]}`. During cloning, the -two-element outer slice is active when the one-element inner view is reached. -They have the same type and first-element pointer, so the tracker reports a cycle -even though the inner view cannot reach the outer slice's second element. -This follows directly from the recursion/key construction and the local standard -library documentation for `reflect.Value.Pointer`; it was not empirically tested. - -**Potential correction:** Make slice tracking distinguish the traversed view, -including its visible length, and handle empty views without treating backing -storage sharing as a cycle. Retain real cycle rejection, concrete types, detached -output, and path-specific errors. Add narrow source-package coverage for this -acyclic shared-prefix view, ordinary shared values, and actual map/slice cycles. -No ban on shared backing arrays or JSON round-trip replacement is needed. The -ordinary JSON transcript decoder does not itself construct this aliased view; -the affected boundary is programmatic metadata supplied by callers/extensions. - -## Areas Where A Rewrite Is Not Recommended - -- **Typed stage/validator registries:** Exact-type checks and stage-specific - variants serve real boundaries. Similar adapter signatures are not sufficient - reason to replace them with an untyped registry or reflection-driven dispatch. -- **Shape validators versus durable codecs:** Candidate diagnostics/correction and - intrinsic durable validity have different jobs. Share truly identical predicates - where helpful; do not merge the boundaries or make optional validation mandatory. -- **Metadata reflection:** Apart from BUG-002, the type switch has a cohesive - purpose and preserves representations that JSON round trips would lose. Small - comments explaining active-recursion tracking and slice-view identity after the - fix are more valuable than a generic visitor framework. -- **Default-chain/registration declarations:** Long declarative lists often have - little control flow. Splitting or generating them solely to reduce line counts - would add machinery without a demonstrated maintenance benefit. -- **Ready-job coordination, proposal safety, and catalog composition:** These own - genuine ordering, identity, and compatibility rules. Existing small state/helper - boundaries are useful; the audit found no basis for a wholesale replacement. - -## Suggested Order And Verification - -The two correctness corrections are small independent starting points. For a -refactoring work set, prioritize CPLX-001, CPLX-003, and CPLX-004: they reduce shared -state reasoning and cross-package drift. Coordinate CPLX-002/007 with structural -consolidation. Runner/CLI phase cleanup and example-test organization can follow -as separate focused work rather than one repository-wide rewrite. - -Each future change should preserve the existing observable contracts and use the -focused behavioral suites named above. Those are recommendations for implementation, -not tests run during this audit. There is no proposed complexity threshold, -benchmark gate, new interface requirement, or obligation to refactor every measured -hotspot. The findings do not retire or resolve issues in the earlier audit reports. - -Only report formatting, local link targets, and the final diff are checked for -this documentation-only deliverable. No code or policy changes are included. diff --git a/docs/roadmap/audit/04-concurrency.md b/docs/roadmap/audit/04-concurrency.md deleted file mode 100644 index e9855119..00000000 --- a/docs/roadmap/audit/04-concurrency.md +++ /dev/null @@ -1,229 +0,0 @@ -# Concurrency Audit - -## Baseline And Scope - -Reviewed revision `ef09060b5804ac0197df51bae2708fb0ab4d1053` on 2026-11-24. -Production code remains unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; -the intervening commits contain the earlier audit reports. The audit adds no -new tests or production changes. The accompanying release-policy wording -correction is separate from these findings. - -The review used the current code graph to find goroutines, channels, mutexes, -atomic operations, once-initialized state, and cancellation paths. It followed -their callers and shared data through preparation, extraction, validation, -continuation, state/capture, CLI invocation, and shutdown. Pinned CommandKit -v0.8.0, ckconfig v0.11.0, and PromptKit v0.25.0 sources were inspected where their -callback/context behavior determines Notarius's synchronization obligations. -This is not a general audit of those upstream repositories. - -The complete default suite passed with fresh race instrumentation, and the -copy-lock vet analysis passed. No data race, deadlock, unsafe channel close, or -goroutine leak was confirmed in the exercised production paths. Two narrower -integration weaknesses warrant consideration: process signals do not enter the -implemented cooperative-cancellation path, and concurrency obligations at extension -boundaries are insufficiently explicit. These are not race-detector failures. - -## Current Concurrency Architecture - -The fixed typed pipeline remains: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -Parsing/chunking and ordered-step barriers are sequential. Within a step, one -bounded worker pool executes ready extraction jobs and ready lane continuations. -The coordinator alone updates lane accounting, restores output order, and selects -terminal errors from reported failures. A continuation becomes ready after that -lane's extracts finish; workers do not hold slots while waiting for dependencies. - -Each prepared lane retains one extractor and one instance of each configured -extract validator; those instances are reused across chunk jobs. Typed codecs are -also reused. Current production implementations are stateless during operations or -protect mutable memoization. Request-local candidates, findings, and producer -continuation state remain local to their operation. - -One native PromptKit engine is shared across model roles. Native backend admission -is separate from worker accounting and is released before nested assessment. -Notarius delegates transport/retry/timer/history mechanics to PromptKit rather -than adding another scheduler. Candidate/context views are detached per validator; -the full parsed source is shared read-only by extraction jobs. - -Debug uses scoped operation paths, mutex-protected native/capture state, and a -serialized recorder. The CLI finalizes requested capture after runner workers -have joined. Cache files use unique temporary names and atomic replacement; -registry projections and compiled schemas use synchronized memoization. -Configuration loaders belong to one invocation, while registries are populated -before execution and then read rather than concurrently registered. - -## Findings - -### CONC-001 — Process Signals Bypass Cooperative Cancellation And Cleanup - -**Priority:** P3 — process shutdown integration weakness; not an in-process leak. - -**Relevant code:** -[main](../../../cmd/notarius/main.go#L13), -[RunWithOptions](../../../internal/cli/run.go#L16), -[run command finalization](../../../internal/cli/pipeline_run.go#L20), and -[worker cancellation/draining](../../../internal/framework/pipeline/runner_concurrent.go#L201). -The main executable calls `App.Execute(context.Background(), ...)`. There is no -OS-signal-to-context adapter in the executable or Notarius CLI. Inspection of the -pinned CommandKit `App.Execute` confirms that it uses the supplied context and does -not install such an adapter on Notarius's behalf. - -**Circumstances:** A terminal user interrupts a run, or a subprocess supervisor -sends SIGTERM while extraction or validation is in progress. Ordinary Unix signal -handling terminates the process; it does not cancel the context supplied to the -pipeline. In contrast, embedded callers using `App.Execute` with their own -cancellable context do reach the existing graceful path. - -**Consequences:** The worker drain/join, native cancellation, capture terminalization, -and normal failure/report handling cannot run to completion on that process-signal -path. A debug bundle can retain its running overview without a terminal outcome, -and a temporary file interrupted before rename can remain. This does not imply -that atomic cache replacement publishes partial JSON or that kernel resources -survive process exit. It also does not claim an existing promise of graceful -signal handling: the weakness is that ordinary process cancellation cannot use -cleanup already implemented for context cancellation. The subprocess guides ask -callers to propagate cancellation, so this distinction is operationally useful. - -**Potential remediation:** Connect supported process signals to a cancellable -root context at the executable boundary, using `signal.NotifyContext` or equivalent -idiomatic code, and pass that context to native execution. Retain normal context -ownership for embedded consumers. Deliberately choose how repeated signals restore -normal termination or escalate; avoid accidentally swallowing every subsequent -interrupt while waiting for cleanup. - -Do not add a separate shutdown worker pool, background cleanup service, automatic -artifact deletion, or a new hard shutdown deadline without a concrete requirement. -Graceful cancellation remains cooperative; SIGKILL cannot be handled, and a custom -collaborator that ignores context cannot acquire a termination guarantee merely -from this change. - -**Evidence and follow-up:** This is a static end-to-end context/signal finding, -not a signal-injection reproduction. Existing -[CLI cancellation coverage](../../../internal/cli/run_result_command_test.go#L167) -passes a cancellable context directly, so it does not cover the executable gap. -The existing worker cancellation/admission tests substantiate the downstream -cleanup path. A future correction should use a focused subprocess test with a -local fake backend, an ordinary supported signal, and retained capture evidence; -no real provider is needed. - -### CONC-002 — Extension And Explicit Capture Concurrency Obligations Are Implicit - -**Priority:** P3 — extension-contract documentation weakness; current default -implementations were not found to race. - -**Relevant code:** -[prepareLane](../../../internal/framework/pipeline/prepare.go#L209), -[worker execution](../../../internal/framework/pipeline/runner_concurrent.go#L157), -[runExtractJob](../../../internal/framework/pipeline/runner_concurrent.go#L268), -[candidate assessment](../../../internal/framework/pipeline/candidate_assessment.go#L79), -[typed interfaces](../../../internal/framework/contracts/typed_pipeline.go), and -[ExecutionOptions/EvidenceWriter](../../../internal/framework/contracts/producer.go#L62). -The [extension recipe](../../internal/modules.md) explains typed registration and -ownership but does not clearly state the overlapping-call pattern for retained -instances and collaborators. - -**Circumstances:** A new extractor or extract validator stores a per-call slice, -counter, or candidate in its instance fields without synchronization, assuming -that each chunk receives a fresh implementation. Preparation actually constructs -one instance for the selected binding, and different workers can call it at the -same time. Detaching request data does not isolate the receiver's fields. -Similarly, shared codec methods can be invoked by several extraction/assessment -jobs, and a shared injected client or preparation callback can be reached from -several native calls. - -There is a related capture distinction: `Runner.Run` serializes its `Debug` -recorder, but an explicit `RunInput.Execution.Capture` is selected directly by -[operationExecution](../../../internal/framework/pipeline/native_capture.go#L184) -and scoped without adding one shared writer lock. Separate `NativeCapture` -instances protect their own state; their mutexes do not serialize calls into a -shared underlying `EvidenceWriter`. An unsynchronized map/buffer writer supplied -through that route can therefore receive overlapping writes. The current CLI -recorder and concurrent native-capture test writer are synchronized. - -**Consequences:** Extensions or direct framework integrations can introduce data -races, mixed candidate state, or lost evidence despite using the typed interfaces -and detached request views correctly. Existing tests can remain green because -they use stateless implementations or explicitly synchronized test writers. -No current default implementation is accused of this defect; the missing signal -to implementers is the weakness. - -**Potential remediation:** Document the current call/ownership model in the -canonical module-internals guide and add concise interface comments or links at -the relevant boundary: - -- Prepared extractors and their extract validators can receive concurrent calls - within one run; keep per-call state local or synchronize retained mutable state. -- Codecs are shared collaborators, while merge/normalize for one lane follow its - completed extraction; do not imply universal concurrent invocation for every - module method. -- Parsed source used by extractors is shared read-only; detached validator views - do not make arbitrary shared module fields safe. -- Explicit capture writers and shared callbacks must account for the actual - parallel call pattern. Link to native client/observer contracts where the - requirement belongs upstream rather than duplicating library documentation. -- The runner waits for operation methods it dispatched, not arbitrary background - goroutines an extension might start. Any added asynchronous work needs an - explicit lifetime relative to its operation and borrowed collaborators. - -For explicit capture, prefer making the existing caller-side concurrency -obligation clear and pointing to the safe recorder. If support for serial-only -writers is desired, select that separately and wrap the shared writer once per -run. A different mutex in every operation wrapper would not solve the race. -Do not silently promise thread safety for all callbacks, add locks to every -stateless module, serialize all extraction, or broaden live-registration support. - -**Evidence and follow-up:** -[Concurrent native capture coverage](../../../internal/framework/pipeline/native_capture_test.go#L318) -uses a mutex-protected writer and atomic callback counters. Existing resolver, -schema-cache, source/metadata isolation, and concurrent-runner tests exercise the -safe implementations. Documentation clarification alone needs no new runtime test; -future mutable extensions should test their own shared-instance behavior where -the risk warrants it. - -## Reviewed Paths Without A Confirmed Defect - -| Area | Evidence and assessment | -| --- | --- | -| Goroutine ownership and channels | `laneEngine.startWorkers`, `collect`, and `run` form one ownership chain: add workers before starting, stop dispatch on observed cancellation, drain each dispatched job's result, close jobs, then wait. The result channel need not be closed because its lifetime ends with the engine and no receiver ranges over it. No separate goroutine is launched per chunk or waiting continuation. | -| Lane state and ordering | Coordinator-only `remaining`, results, diagnostics, pending continuations, and completed outputs are not concurrently mutated by workers. Continuations are dispatched only after all lane results arrive, providing a channel synchronization boundary for the finalized data. Outputs are restored to configured order; error selection is among reported failures, not all hypothetical failures canceled work might otherwise have produced. | -| Cancellation, continuation, and fallback | Native work uses the job context; delivered candidates are assessed sequentially within that operation. Failed/undelivered responses do not revive earlier candidates. Cancellation does not initiate fallback. After sibling cancellation, started jobs are drained before the runner returns. | -| Nested LLM validation/admission | Worker ownership is not reacquired for nested validation. Producer/native admission is released before assessment; tests with one shared backend slot successfully execute nested validators. There is no observed worker/admission lock cycle. | -| Shared module data | Registry resolver caches and generic schema compilation are mutex-protected; cached views are immutable and public projections copy mutable data. Spell catalog initialization uses `sync.Once`; case folding is created per call. Production extraction/normalization state is local to each invocation rather than retained candidate state on the module. | -| Validator/request isolation | Candidate bytes are encoded once, then decoded separately for typed validators. Source/chunk/metadata/reference views are detached at validator boundaries; chunks and metadata handed to extraction are owned. Atomic assessment numbers avoid concurrent capture-name reuse. | -| Native callbacks and capture locks | Native observer composition/coordination are synchronous along each execution. `NativeCapture` guards its own counters/prepared snapshot/error, normal recorder calls are serialized, and the CLI finalizes after workers join. No production lock-order cycle or write-after-finalization path was confirmed. CONC-002 describes explicit external writer obligations. | -| Cache and filesystem concurrency | Stores retain immutable roots; unique temporary files and atomic rename publish whole entries under concurrent replacement. Current-source cache indices use a run-local `sync.OnceValue`. Concurrent `latest` updates retain real bundles and a valid relative link; no monotonic timestamp-order promise is inferred from simultaneous starts. | -| Configuration/registry lifetime | Native loaders are fresh per invocation. Pinned ckconfig comparison loads its two sides sequentially, so the invocation-owned selection slice is not concurrently mutated by those callbacks. Domain registries are constructed before worker execution; no hot-registration guarantee or additional lock requirement is inferred. | -| Reporting/observation | The CLI's debug execution group uses native synchronized observation and is snapshotted after worker completion. Diagnostics are local or coordinator-owned before final aggregation; normal process output is published/reported after the runner returns. | - -## Validation - -Both commands completed successfully at the reviewed revision: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -race -count=1 ./... -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly -copylocks ./... -``` - -The fresh race run included existing coverage for worker limits and ready -continuations, cancellation/draining and admission release, nested validators, -concurrent capture, registry reuse, schema compilation, atomic cache replacement, -debug allocation/finalization, and CLI cancellation. Test source was inspected to -understand what these checks actually exercise. No real credentials, live provider -calls, or new test cases were used. - -Passing race detection covers executed interleavings, not every possible schedule -or extension. Executable subprocess tests build their child with ordinary -`go build`, so parent `go test -race` does not automatically instrument that child. -No process-signal or forced-shutdown experiment was performed. No claim is made -about arbitrary custom modules/writers that ignore context or mutate shared inputs, -or about recovery from SIGKILL, machine failure, or hostile filesystem mutation. - -The review supports retaining the current coordinator, worker/admission separation, -and synchronization structure. Address the process-signal boundary and clarify -extension ownership proportionately; no repository-wide concurrency framework is -indicated. Earlier audit findings remain independent and are not resolved by -this report. Local report links and the final documentation diff were checked. diff --git a/docs/roadmap/audit/05-resources.md b/docs/roadmap/audit/05-resources.md deleted file mode 100644 index 55088963..00000000 --- a/docs/roadmap/audit/05-resources.md +++ /dev/null @@ -1,265 +0,0 @@ -# Resource Management Audit - -## Baseline And Scope - -Reviewed revision `65ce8f7fe55b91244c4114ea95fb87494a1449b9` on 2026-11-24. -Production code is unchanged from the preceding audits. This pass adds only -this report; it adds no tests, production changes, or benchmarks. - -The review followed resource acquisition, ownership, bounds, and release across -CLI/configuration composition, reference reads, source/chunk materialization, -worker execution, native production and assessment, caches, capture, output -encoding, and publication. Code-graph searches located resource operations and -their callers. Relevant pinned PromptKit v0.25.0 internals were inspected only -where they determine Notarius's handle, admission, HTTP, or timer lifecycle. -This is not a general audit of upstream libraries. - -No file-descriptor, response-body, timer, or goroutine leak was confirmed in the -reviewed default execution paths. Three resource-efficiency weaknesses warrant -consideration: - -| Finding | Priority | Affected resource | -| --- | --- | --- | -| RES-001: Disabled capture still constructs large evidence payloads | P2 | Transient heap, buffers, and unnecessary encoding work in ordinary runs | -| RES-002: Intermediate results outlive their consumers | P2 | Retained heap during slow sibling work and in returned run values | -| RES-003: Enabled capture repeats the full source for every extraction job | P3 | Debug disk space, write volume, and serialization buffers | - -These are scaling/lifetime weaknesses, not claims that a small ordinary run must -exhaust resources. Bounds and numerical examples below come from source analysis, -not measured production memory or throughput. - -## Current Resource Architecture - -The CLI owns one invocation's loaded configuration, optional shared native engine, -prepared modules, input bytes, cache collaborator, requested debug recorder, and -publication directory. Configuration/engine selections are invocation-local. -Input is read into memory; parsing, source units, materialized chunks, typed -artifacts, and serialized output are batch-oriented rather than streaming. - -After serial chunking, one bounded pool runs ready extraction and lane-completion -jobs. The coordinator dispatches lazily, cancels siblings on failure, drains -started jobs, closes its job channel, and joins workers. PromptKit independently -owns backend admission, provider transport, operation deadlines, transient retry -waits, structural repair, and conversation state. Admission is released before -nested validators run. Prepared cache executions are consumed or discarded. - -Registry/schema memoization belongs to prepared module instances; the spell -catalog is a finite process-level initialization. The debug recorder writes -incrementally and retains lifecycle/error state, not whole-run payloads. Native -capture releases its prepared snapshot at the operation boundary. Individual -cache/output/debug writes close temporary files and atomically rename them; -normal error paths remove unpublished temporary siblings. Output, cache, and -requested debug bundles have distinct, operator-owned retention policies. - -## Findings - -### RES-001 — Disabled Capture Still Constructs Large Evidence Payloads - -**Relevant code:** -[writeDebugTimed and envelope builders](../../../internal/framework/pipeline/debug.go#L100), -[Runner.Run](../../../internal/framework/pipeline/runner.go#L138), -[runChunkPlan's deferred evidence](../../../internal/framework/pipeline/runner_chunk_plan.go#L28), -[continueLane](../../../internal/framework/pipeline/runner_concurrent.go#L349), -[merge/normalize evidence](../../../internal/framework/pipeline/runner_typed.go#L138), -and [RecordEvidence](../../../internal/framework/contracts/producer.go#L79). - -**Circumstances:** Run with debug disabled, including ordinary deterministic or -cache-reuse workloads. Arguments are evaluated before `writeDebugTimed` checks -`Enabled()` or `RecordEvidence` checks whether a writer exists. Thus the no-op -path is reached only after building the payload. Examples include: - -- raw source content converted to text and base64 at source/chunk boundaries; -- every materialized chunk converted to a debug envelope in the deferred chunk - outcome, even when `Execution.Capture` is nil; -- all chunks and extraction artifacts converted again when each lane continues; -- normalized artifacts and final output files converted before disabled output - capture calls. - -`debugContentEnvelope` creates base64 content even for valid UTF-8 data and also -retains its text representation; chunk builders copy unit slices/annotations. -These are not cheap references to an already serialized object. For a byte slice -of length B, base64 alone produces approximately 4B/3 bytes, in addition to the -text, container, and annotation allocations. Concurrent continuations can build -separate all-chunk payloads for several lanes. - -**Consequences:** Explicitly disabling evidence does not eliminate substantial -debug-only allocation and hashing work. Large transcripts or artifact sets can -create avoidable heap pressure and garbage-collection work, and contribute to -an out-of-memory failure under concurrent lane completion. No debug file needs -to be written for this to occur. This is transient allocation, not a permanent -retained-object leak. - -**Potential remediation:** Check enablement before constructing expensive debug -payloads. Simple guards at stage-owned boundaries are sufficient; a small lazy -payload helper is also viable if it makes the repeated pattern clearer. Apply -the same rule to the deferred chunk outcome, not only `writeDebugTimed` callers. -Keep ordinary artifact encoding/validation outside the guard when execution -actually requires it. Do not change requested-capture failure semantics or add -a new diagnostic scheduler, buffer pool, or input-size restriction. - -**Verification:** The call sites and helper bodies establish eager evaluation. -Existing debug, capture, cache-hit, deterministic-run, and failure tests passed. -They protect evidence content and execution behavior, not allocation absence; -passing them does not refute this finding. A correction should preserve enabled -capture while keeping expensive payload builders off the disabled path. - -### RES-002 — Intermediate Results Outlive Their Consumers - -**Relevant code:** -[laneExtractState](../../../internal/framework/pipeline/runner_concurrent.go#L19), -[handleCompletion](../../../internal/framework/pipeline/runner_concurrent.go#L254), -[finalizeLaneExtract](../../../internal/framework/pipeline/runner_concurrent.go#L334), -[typed lane completion](../../../internal/framework/pipeline/runner_typed.go#L54), -[RunOutput and final return](../../../internal/framework/pipeline/runner.go#L73), -[diagnostic finalization](../../../internal/framework/pipeline/diagnostics.go#L78), -and [JSON output encoding](../../../internal/modules/generic/output/json/encoder.go#L229). - -**Circumstances:** A step contains many chunks, voluminous artifacts, or lanes -with different completion times. A fast lane finishes merging/normalizing while -another lane is still executing or correcting model output. Two lifetime gaps -exist: - -1. Each lane's `results` map retains every extracted typed value, serialized - artifact, and diagnostic result. `finalizeLaneExtract` appends those results - into ordered `values`/`diagnostics` without dropping the map. After continuation - completes, `handleCompletion` stores the normalized output but leaves all - extraction references in the lane state. The engine retains every lane state - until the whole step returns, so completed lanes' extraction data remains live - while unrelated sibling work proceeds. -2. After output encoding, `Runner.Run` returns the same `RunOutput` that still - contains private `normalizeOutputs`, reuse-eligibility data, and the original - diagnostic-group accumulator. The public `OutputFiles` and finalized - `Diagnostics` have already been assembled. In particular, encoded output bytes - are separate from the retained normalized artifact bytes. Callers keeping the - completed result also keep internal intermediates they cannot directly release. - `failOutput` similarly finalizes diagnostics without retiring private state. - -Copying a result into the ordered slice does not itself duplicate every payload: -many references point at the same values. The problem is that these references -keep the underlying objects/buffers reachable after their final consumer, alongside -the separately constructed merged, normalized, and encoded forms. - -**Consequences:** Worker count bounds active operations but not the total live -extraction data. Peak heap can include all lanes' original typed/serialized -extractions plus their later-stage outputs, even after most lanes finish. Slow -provider responses prolong this retention. Retaining several completed run -results in an embedding compounds the unnecessary normalized-byte/diagnostic -retention. This is not an indefinitely growing process-global cache: the memory -is collectible when the containing engine/result becomes unreachable. - -**Potential remediation:** Release references at their actual ownership boundaries: - -- retire the reordering map once ordered values/diagnostics own what continuation - needs; -- after a continuation returns, have its coordinator retire the completed lane's - extraction values/diagnostics and remaining reorder state; -- at the outer `Runner.Run` return boundary, preserve public files, finalized - diagnostics, and fallback count while retiring private execution accumulators - on success and failure. - -Do not discard normalized artifacts before ordered-step handoffs, evidence -projection, or final output encoding finish. Do not clear the contents of shared -objects or backing arrays that downstream artifacts still reference; dropping -the owner's references is the intended operation. No forced garbage collection, -new global memory cap, or pipeline streaming redesign is required for this cleanup. - -**Verification:** The state fields and absence of release in finalization/completion -and return paths substantiate retention. Existing ready-continuation, -ordering/cancellation, handoff, output, and retained-diagnostic tests passed; they -do not measure heap reachability. Recheck those behaviors when shortening lifetimes, -especially slow sibling completion and failures after accepted predecessor work. - -### RES-003 — Enabled Capture Repeats The Full Source For Every Extraction Job - -**Relevant code:** -[captureOperationInputs](../../../internal/framework/pipeline/operation_capture.go#L9), -[per-chunk extraction call](../../../internal/framework/pipeline/runner_concurrent.go#L289), -[full-source debug projection](../../../internal/framework/pipeline/debug.go#L130), -[capture serialization](../../../internal/framework/debug/recorder.go#L87), and -[atomic JSON writing](../../../internal/core/fileio/fileio.go#L90). - -**Circumstances:** Enable debug for a large multi-chunk, multi-lane pipeline. -Every extraction job calls `captureOperationInputs`, which includes the complete -parsed `target.source`, not just the chunk. It also includes reference payloads -and the chunk/source-input representations. A full source snapshot is already -recorded at run scope. Each operation then serializes another copy into its own -`inputs.json`. This applies before extractor execution and also on cache hits. - -For C chunks, L extraction lanes, and S bytes in the serialized full-source -projection, those source fields alone contribute approximately C × L × S bytes. -For illustration, 80 chunks × 8 lanes × a 4 MiB source projection is 2.5 GiB, -before references, chunk representations, native evidence, or other stage files. -This is arithmetic from the write pattern, not a measured bundle. Where chunk -count grows with transcript size, this repeated component grows quadratically -with the input rather than with only the useful chunk data. - -**Consequences:** A single requested debug run can consume disproportionately -large disk space and serialization buffers. Disk exhaustion can fail required -capture, and therefore the invocation, after substantial model work has already -completed. Atomic temporary files protect publication but do not remove this -capacity risk. Incremental recorder writes avoid a whole-run memory ledger; -they do not bound disk usage or the size of each individual JSON serialization. - -**Potential remediation:** Consider capturing immutable source/reference material -once per bundle and using bundle-local references plus operation-specific -source ranges/selection metadata. Keep actual inputs recoverable and preserve -native prepared/result/exchange evidence; removing selected evidence or truncating -it silently is not the recommendation. The CLI's already captured run-level source -is a natural reuse point. A bundle-aware representation must account for direct -`EvidenceWriter` users rather than assuming every writer has a CLI filesystem root. - -This is an explicit convenience/capacity tradeoff, not a violation of a selected -size guarantee. [ADR-0024](../../adr/0024-publish-artifacts-with-native-reports-and-debug-evidence.md) -permits evidence duplication, and the -[operation-input test](../../../internal/framework/pipeline/operation_capture_test.go#L17) -currently expects self-contained inputs. Review that choice deliberately before -changing it. Retain complete available bundle evidence, exact secret omissions, -and required-capture failure behavior. Do not add automatic bundle deletion, -quotas, a retention daemon, or new operator restrictions as an incidental fix. - -## Reviewed Lifecycles Without A Confirmed Leak - -| Area | Evidence and assessment | -| --- | --- | -| File descriptors | Reference materialization closes each opened file before proceeding to the next binding, including read/size failures. `os.ReadFile`/embedded `fs.ReadFile` own their handles. Atomic writers close on success and write/chmod errors. Debug latest-link allocation closes its temporary file before replacing it with a link. No defer-inside-a-large-file-loop descriptor accumulation was found. | -| Temporary publication files | Ordinary write, chmod, close, and rename failures remove the writer's own unpublished temporary sibling. Existing failed-publication tests check the directory for leftovers. Cleanup cannot be guaranteed when removal itself fails, the process is killed, or the machine stops; no stronger filesystem guarantee is inferred. | -| Worker goroutines/channels | Dispatch is lazy rather than allocating one goroutine per chunk. The coordinator drains started work before closing jobs and waiting. Existing tests verify zero remaining active jobs and reusable native capacity after cancellation. Arbitrary extensions ignoring context cannot be forcibly stopped by that mechanism. | -| Prepared executions | `RunProducer` defers `Discard` immediately after successful preparation, covering hits, lookup/capture failures, and early returns. Pinned native `RunPrepared` claims the payload and defers clearing execution-only references. Preparation does not start an idle operation timer or occupy admission. | -| Timers/retry waits | The local worker cancellation function is deferred. Native operation scopes and request timeouts defer cancellation; native retry wait timers defer `Stop`. The lost-cancel analysis passed. Notarius creates no separate timer/retry service around those APIs. | -| HTTP bodies/connections | Provider calls belong to the shared native engine. Inspected built-in transport code defers response-body closure on successful HTTP dispatch before status/decoding exits and bounds response decoding. Standard transport idle connection reuse is intentional; Notarius should not close a caller-supplied shared transport after every operation. No missing Notarius engine-close obligation was found in the pinned API. | -| Registry/schema caches | Mutable caches live on prepared module/resolver instances. The ordinary CLI constructs that set per run; stable stage references mean chunk count does not create one distinct registry view per chunk. These are not process-global histories. Long-lived direct reuse with arbitrarily many changing references/schemas can grow instance caches; that different usage needs an explicit lifetime/cache policy rather than an assumed CLI leak. | -| Diagnostic/observation buffers | Producer diagnostics and final aggregation enforce group/sample bounds. Private pre-aggregation storage is covered by RES-002. Native debug observation retains member IDs/terminal facts, not full exchanges; the recorder itself retains only lifecycle/error state, and `NativeCapture.Finish` clears its prepared snapshot. | -| Output/cache/debug retention | Preserving published output, available partial failure directories, accepted cache entries, and requested evidence is selected behavior. Operator-owned cleanup is documented in [Operations](../../operations.md#cleanup). Absence of automatic eviction/deletion is not itself a leak or authorization to add it. | - -## Validation And Limits - -The following completed successfully at the reviewed revision: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 ./... -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly -lostcancel ./... -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 go.maximumdirect.net/promptkit -run '^(TestPreparedExecutionDiscardAndFormattingDoNotExposePrivateState|TestPreparedExecutionRetainsTimeoutWithoutIdleTimer|TestCoordinateReleasesCapacityBeforeCallback|TestOperationBudgetInterruptsRetryAndRepair)$' -``` - -Existing test source was inspected to identify the protection actually provided: -worker/native admission release, cancellation, prepared-handle disposal, bounded -reference reads, failed cache publication cleanup, recorder failure/finalization, -partial output retention, and native deadline/retry lifecycle. The focused upstream -tests use fake clients/transports and synthetic time. No credentials, live provider, -benchmarks, new tests, or heap-exhaustion experiments were used. Passing functional -checks does not prove bounded peak memory or debug size; the findings are supported -by retained references, eager construction, and repeated write sites. - -Whole-input loading and detached mutable validator views are deliberate parts of -the current batch-oriented design, not newly discovered leaks. The earlier -[efficiency audit](02-efficiency.md) covers repeated full-source indexing/text -scans and their allocation cost. The -[concurrency audit](04-concurrency.md) already records the missing process-signal -adapter and implicit extension concurrency obligations. Those findings remain -separate; this report does not imply they have been corrected. - -Prioritize keeping disabled capture cheap, then shortening intermediate lifetimes. -Evaluate bundle-local evidence reuse as a separate capacity/convenience choice. -Retain the existing worker/admission separation and ordinary standard-library -cleanup; no repository-wide resource manager is indicated. Report links and the -final documentation diff were checked locally. diff --git a/docs/roadmap/audit/06-error-handling.md b/docs/roadmap/audit/06-error-handling.md deleted file mode 100644 index 1566074c..00000000 --- a/docs/roadmap/audit/06-error-handling.md +++ /dev/null @@ -1,259 +0,0 @@ -# Error-Handling Audit - -## Baseline And Scope - -Reviewed revision `67116c42e20b83f584c67f221420960ecfd2bee9` on 2026-11-24. -Production code is unchanged from the preceding audits. This pass adds only this -report, without production changes or new tests. - -The review followed errors through configuration/preflight, source/reference -loading, typed codecs, producers, assessment, native continuation, worker -cancellation, cache reuse, capture, output publication, and native presentation. -Code-graph searches and caller tracing were used to inspect error construction, -wrapping, ignored results, fallback branches, and failure-return paths. Relevant -pinned PromptKit v0.25.0, CommandKit v0.8.0, and ckconfig v0.11.0 APIs were inspected -where their contracts determine the meaning of local error handling. - -Three diagnostic/classification weaknesses warrant consideration. No new path -was confirmed that turns a terminal pipeline failure into unqualified successful -publication. Existing correctness/concurrency findings remain independent. - -| Finding | Priority | Main effect | -| --- | --- | --- | -| ERR-001: Completed native validation failures lose detail and acquire an operational error category | P3 | Misleading classification and less actionable failure/fallback explanations | -| ERR-002: Successful extraction diagnostics disappear when the lane never continues | P3 | Failure-path visibility depends on whether unrelated work completed | -| ERR-003: Failure-output finalization suppresses aggregation errors | P3 | Aggregation failure and previously collected diagnostics can both disappear | - -## Current Error-Handling Architecture - -The CLI is the composition/publication boundary. It maps identifiable invalid -configuration to native usage outcomes, retains operational causes, and keeps -operation failures distinct from report/diagnostic delivery failures. The pipeline -returns logical files only after successful stage execution; the CLI publishes -them before finalizing requested capture and submitting the completion report. - -Modules own interpretation, correction guidance, and supported fallbacks. The -framework assesses complete candidates through the configured validator chain, -distinguishing approval, rejection, failure, and unavailable judgment. PromptKit -owns transport, structural repair, deadlines, and conversation iteration. Native -execution success is not domain acceptance. Strict nonacceptance fails; explicitly -selected permissive mode can construct a checked, disclosed, reuse-ineligible -fallback. Caller cancellation and undelivered responses do not initiate fallback. - -The coordinator cancels siblings, drains started work, and chooses a scoped error -by stable ordering rather than arrival time. Parent cancellation takes precedence. -Cache I/O is deliberately best effort with diagnostics; encoding and requested -capture are required boundaries. File publication is individually atomic, not an -all-files transaction, and available output/debug data is intentionally retained -after later failures. - -## Findings - -### ERR-001 — Completed Native Validation Failures Lose Detail And Acquire An Operational Error Category - -**Relevant code:** -[RunProducer.evaluate](../../../internal/framework/pipeline/producer.go#L67), -[combat-semantics validation](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go#L70), -and [terminal fallback handling](../../../internal/framework/pipeline/producer_outcome.go#L13). -The pinned native contracts are defined in PromptKit's -[error declarations](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/engine.go#L89) -and [ValidationResult](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/types.go#L544). - -**Failure condition:** Native structural validation completes with a failed -result and nil Go error, after whatever repair allowance was selected. This is -a supported PromptKit outcome, exercised by existing tests. `Validation.Errors` -contains the native content-check diagnostics. - -**Expected behavior:** Refuse to interpret/accept that result, retain useful -content-check details in the application failure or fallback explanation, and -preserve the native distinction between a completed failed check and an -operational inability to perform validation. PromptKit reserves `ErrValidation` -for the latter; a completed `ValidationFailed` result is not that Go error. - -**Actual behavior:** The producer replaces the result's explanation with -`producer output did not satisfy its native contract`, wrapping a newly supplied -`promptkit.ErrValidation`. The LLM validator similarly substitutes a generic -`native output contract failed` message and that sentinel before marking its -assessment unavailable. Neither path includes `result.Validation.Errors`. - -The safety decision is correct: failed output is not interpreted as usable. -However, `errors.Is(..., promptkit.ErrValidation)` now also matches an -application-converted content failure, making it indistinguishable from the -upstream operational category. Without debug, an operator cannot see the supplied -reason for failure; permissive fallback diagnostics inherit the generic text. -With debug enabled, the recorded native result still contains the details, so -this is not complete destruction of evidence. - -**Potential remediation:** Use a small application-owned nonacceptance error or -descriptive error construction for completed failed validation, carrying the -available native diagnostic details without copying the whole response into the -error. Keep genuine native Go errors and their causes unchanged. Apply the same -distinction to producer and LLM-validator boundaries; keep the validator's -unavailable-assessment classification. - -Distinguish the defensive nil-result case from a present failed result, since it -has no native validation details to report. Preserve strict/permissive outcomes -and `ValidationFailed` checks. Do not send these operational/content diagnostics -through an extra application semantic retry, extend native repair budgets, or -turn internal codes into model-facing guidance. Reuse native result types rather -than adding a replacement validation protocol. - -**Evidence and follow-up:** -[Failed-native-validation tests](../../../internal/framework/pipeline/producer_test.go#L162) -exercise both initial and correction responses and prove they are not interpreted -or reassessed. They assert safe fallback and call counts, not retained diagnostic -detail or the operational/content-category distinction. A future fix should -cover those distinctions with controlled native failures and preserve the -existing no-extra-retry behavior. No new test was added during this audit. - -### ERR-002 — Successful Extraction Diagnostics Disappear When The Lane Never Continues - -**Relevant code:** -[runExtractJob and ordered finalization](../../../internal/framework/pipeline/runner_concurrent.go#L268), -[handleExtractResult](../../../internal/framework/pipeline/runner_concurrent.go#L235), -[continueLane](../../../internal/framework/pipeline/runner_concurrent.go#L349), -[runLanes](../../../internal/framework/pipeline/runner_concurrent.go#L66), and -[CLI diagnostic reporting](../../../internal/cli/pipeline_run.go#L160). - -**Failure condition:** One or more chunks finish successfully and return process -diagnostics, such as cache degradation or a qualified-fallback warning. A later -chunk in that lane fails, or a sibling lane fails before its continuation starts. -This also occurs with one worker: finish chunk A, then fail chunk B before the -lane becomes ready. No unusual concurrent interleaving is required. - -**Expected behavior:** Stop the failed work and prevent publication as today, -while retaining diagnostics from operations that already completed. The runner's -failure-output helper explicitly aims to preserve already accepted diagnostics, -and the CLI reports the returned diagnostic collection even on runner error. -Not every failed or canceled operation needs a synthetic warning. - -**Actual behavior:** Successful results and their diagnostics remain in -`laneExtractState.results`. They enter the lane's ordered diagnostic slice only -when every extraction finishes successfully. That slice reaches a returned -`RunOutput` through continuation. If failure/cancellation prevents continuation, -the coordinator returns only `completedOutputs`; it never folds the successful -partial-lane diagnostics into that result. `failOutput` cannot recover information -that never reached the run's accumulator. - -**Consequences:** Operators can lose genuine earlier cache/fallback context on a -failed run. Diagnostic visibility depends on whether the lane happened to reach -continuation, rather than whether the originating operation completed. Ordinary -pipeline failure still propagates, failed lanes do not publish, and native/debug -operation evidence can remain available when enabled. This is diagnostic loss, -not acceptance of partial lane artifacts. - -**Potential remediation:** After draining started work, preserve already completed -operations' diagnostics independently of lane continuation eligibility. Fold them -in canonical lane/chunk order and ensure completed-lane diagnostics are not added -twice. Keep artifact merging, normalization, generated handoffs, and publication -disabled for incomplete lanes. - -Successful partial results form a sparse map after failures. Do not call the -current dense `finalizeLaneExtract` loop unchanged: iterating only to `len(results)` -can miss higher chunk indices. Iterate known chunk positions with presence checks -or sort actual result keys. Preserve existing cancellation/error precedence; -do not resurrect output returned after cancellation or invent findings for work -that never completed. - -**Evidence and follow-up:** The coordinator's storage/continuation branches -establish the loss. Existing -[reverse-completion tests](../../../internal/framework/pipeline/runner_concurrency_test.go#L317) -check successful diagnostic ordering, and -[ordered-step failure tests](../../../internal/framework/pipeline/runner_concurrency_test.go#L266) -check preservation of completed predecessor outputs and suppression of later work. -Those tests do not combine a completed warning-bearing chunk with a later -same-lane failure. That is the focused regression scenario for a future fix. - -### ERR-003 — Failure-Output Finalization Suppresses Aggregation Errors - -**Relevant code:** -[failOutput](../../../internal/framework/pipeline/runner.go#L446), -[finalizeDiagnostics](../../../internal/framework/pipeline/diagnostics.go#L78), -[Aggregator.Add](../../../internal/framework/diagnostics/aggregator.go#L30), -and the [success-path finalization call](../../../internal/framework/pipeline/runner.go#L263). - -**Failure condition:** Individually valid groups accumulated from multiple -operations exceed a final aggregate constraint, and the runner is returning a -stage/cancellation error. A concrete case is more than 128 distinct warning -groups across a sufficiently large configured pipeline. Checked occurrence-total -overflow is another aggregation failure. Per-producer/group validation does not -prove either aggregate constraint. - -**Expected behavior:** Keep the primary failure and make a genuine aggregation -failure inspectable, preserving available bounded diagnostic information where -possible. Existing warning bounds and their failure behavior remain in force; -there is no requirement to publish every warning beyond those bounds. - -**Actual behavior:** `failOutput` discards the result of `finalizeDiagnostics`. -Its comment incorrectly assumes that validating each diagnostic makes finalization -infallible. `finalizeDiagnostics` returns on `Aggregator.Add` failure before -assigning the locally collected prefix to `output.Diagnostics`. On an earlier -stage failure, the caller consequently receives only that primary error and -typically an empty diagnostic collection, with no aggregation error. - -The nominal success path correctly returns an aggregation error, but its call to -`failOutput` repeats the same failed aggregation and still loses the prefix. -This is separate from ERR-002: it affects groups that did reach the accumulator. - -**Potential remediation:** Make failure finalization explicitly return/propagate -its error, joining it with the primary cause rather than replacing that cause. -Consider returning the valid bounded prefix alongside the error, clearly as -incomplete failed-run information. Avoid reaggregating an identical failed set. -A small shared failure-return helper or outer finalization boundary can keep -the many return sites consistent. - -Retain stable diagnostic ordering, warning-limit failure, non-warning truncation -metadata, and cause identities. Do not silently raise limits, truncate actionable -warnings into apparent success, or introduce an unbounded fallback collector. - -**Evidence and follow-up:** -[Aggregator boundary tests](../../../internal/framework/diagnostics/aggregator_test.go#L43) -already prove that valid individual groups can encounter aggregate failures. -[Pipeline diagnostic tests](../../../internal/framework/pipeline/diagnostics_test.go#L20) -cover successful finalization, not a primary failure combined with overflow. -The defect follows from composing these existing branches. A future correction -should retain both causes and bounded available diagnostics on that combined path. - -## Reviewed Behavior That Is Deliberate Or Already Protected - -| Area | Assessment | -| --- | --- | -| Configuration and preflight | Native loading/inspection failures retain causes and scoped pipeline/module/profile context. CLI classification distinguishes identifiable invalid selections from operational or mixed joined failures. Preflight intentionally does not prove provider readiness, read execution input, or invent defaults for dynamic selections. | -| Complete assessment | Validators continue after rejection/failure/unavailability; caller cancellation and framework/capture failures interrupt. Missing/invalid correction guidance becomes a failed contract, not invented instructions. Rejection text is distinct from operator errors and internal reason codes. | -| Strict/permissive disposition | Explicit permissive recovery may cover native operational failure or exhausted nonacceptance when a module supports a checked fallback. This is selected policy, not suppressed failure by accident. Fallback construction errors retain the original cause, and fallback is disclosed/reuse-ineligible. | -| Native continuation | Undelivered responses and result-less failures do not recover an earlier candidate. Initial/final usable candidates receive assessment once. Exhausted structural repair is not extended by an outer application retry. ERR-001 concerns classification/details, not this safe control flow. | -| Cancellation and timeouts | Caller cancellation takes precedence, prevents fallback/publication, stops dispatch, and drains started jobs. A native operation timeout does not become caller cancellation while the caller remains active. Stable error selection intentionally returns one scoped terminal failure rather than every sibling cancellation. | -| Cache errors | Read/malformed/unusable entries become diagnostic misses, and store I/O failures warn without failing otherwise successful work. Artifact encoding and capture errors remain fatal. This best-effort split is explicit; it should not be changed to universal failure or silent suppression. Failed refresh preserves prior accepted data. | -| Capture errors | Recording errors are sticky and surfaced at returnable boundaries. Ignoring the immediate `executions.json` write result is safe here because the recorder retains it and `Finalize` joins it with the primary cause. Capture failure cannot become model feedback/fallback or trigger another model call. | -| Native reporter calls | Ignored progress/deferred-diagnostic return values do not erase delivery evidence: the native reporter records it, and finalization returns failure with separate presentation causes. Existing tests cover failed stdout/stderr, partial report writes, quiet mode, and retained publication. `AdaptDiagnostics`'s second result is an explanation, not an ignored error. | -| File writes and partial publication | Individual write/close/chmod/rename failures propagate; unpublished temporary siblings are removed on ordinary error paths. Secondary close/remove errors during cleanup are intentionally best effort while preserving the primary write error. Partial output/new debug directories are retained for inspection, not rolled back or automatically deleted. No all-files transaction, power-loss, or hostile-filesystem guarantee is inferred. | -| Domain helpers and panics | Ignored index-presence booleans follow successful reference validation. Identity-key marshal panics operate on fixed string/integer/reference structures whose current encoding cannot fail normally. No new general panic-recovery requirement is inferred for programming errors or unsupported custom collaborators. Earlier correctness findings retain their own reports. | - -## Validation And Limits - -Both commands completed successfully at the reviewed revision: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 ./... -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly ./... -``` - -Existing test source was inspected for actual coverage, including producer -structural failures, unavailable judgments, assessment-contract failure, -continuation failures, cancellation/timeouts, cache degradation and recovery, -codec failures, aggregate bounds, capture/primary-cause joins, output collisions/ -partial publication, and native report/diagnostic delivery failure. The findings -are supported by current control flow and pinned API definitions; no new composed -fault-injection test was implemented for the uncovered combinations. - -No real credentials, live provider calls, or production filesystem fault injection -were used. Passing tests/vet do not prove the absence of every exceptional path. -The earlier [concurrency audit](04-concurrency.md) covers the executable's missing -OS-signal adapter; that issue is not reclassified as a newly discovered context -handling defect here. [Resource](05-resources.md) and -[correctness](01-correctness.md) findings are likewise separate. - -The current ownership/fallback architecture should be retained. Address the -specific classification and diagnostic-retention gaps without blanket retries, -new mandatory sidecars, automatic destructive recovery, or broader guarantees. -Local report link targets and the final documentation diff were checked. diff --git a/docs/roadmap/audit/08-testing.md b/docs/roadmap/audit/08-testing.md deleted file mode 100644 index 196baa73..00000000 --- a/docs/roadmap/audit/08-testing.md +++ /dev/null @@ -1,418 +0,0 @@ -# Test Coverage And Effectiveness Audit - -## Baseline And Scope - -Reviewed revision `7569dd78e4efda2303c0d9f57c369ef597b64e14` on 2026-11-24 -against the [testing policy](../../policy/testing.md). Production code is -unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; intervening commits -record the preceding audits and a documentation correction. This pass changes -only this report. It adds no tests and changes no production code. - -The review combined a fresh repository-wide coverage run with code-graph -discovery and risk-directed inspection of tests, production branches, fixtures, -and their callers. It considered both missing protection and tests whose -maintenance cost exceeds their behavioral value. Earlier audit counterexamples -were checked against the current tests rather than treating a passing suite as -proof that those defects are covered. - -Inspected areas include source parsing and ownership, configuration/resolution, -chunk planning, producer assessment and continuation, workers/cancellation, -generated references, semantic reconciliation, D&D extraction/normalization, -schemas and prompt assets, accepted-result reuse, diagnostics, publication, -capture, and assembled CLI/subprocess workflows. This is not a claim that every -test assertion or possible pipeline composition was exhaustively reviewed. - -## Current Architecture And Test Shape - -The application retains its fixed typed pipeline: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -The CLI assembles configuration, registries, native kit integration, state, and -reporting. The framework owns preparation, candidate assessment, one bounded -ready-job pool, generated-reference handoffs, and accepted-result reuse. Artifact -families own domain transformations, identity, validators, codecs, and reference -projections. PromptKit owns model transport and native repair/continuation -mechanics. Embedded assets remain content-only. - -The suite generally follows the requested classical style: real internal -collaborators, temporary filesystems, native engines with controlled provider -clients, and local HTTP servers or subprocesses at external boundaries. Useful -assembled tests exercise actual configuration, registrars, codecs, publication, -qualified fallback, cache eligibility, and native reporting rather than merely -checking a mocked orchestration sequence. - -Examples worth preserving include -[assembled recovery](../../../internal/cli/recovery_contract_test.go), -[executable workflows](../../../internal/cli/native_process_test.go), -[mixed extraction/continuation admission](../../../internal/framework/pipeline/ready_jobs_test.go), -[producer transitions](../../../internal/framework/pipeline/producer_test.go), -[native capture](../../../internal/framework/pipeline/native_capture_test.go), and -[concrete metadata isolation](../../../internal/core/source/chunk_plan_test.go#L226). -The weaknesses below call for focused additions and subtraction, not a new test -framework or a blanket increase in test volume. - -## Measured Coverage - -The fresh default suite passed in 124 packages: 1,352 top-level tests and 1,518 -subtest pass events, with no failed events or skipped individual tests. The D&D -declarations package reported no test files; that is not a skipped behavioral -test. - -Combined statement coverage was **89.2%: 13,961 of 15,652 instrumented -statements**. Cross-package instrumentation was enabled so coverage from -integration callers contributes to the packages they exercise. Selected totals: - -| Package | Combined statement coverage | -| --- | ---: | -| `internal/framework/semanticreconcile` | 95.6% | -| `internal/preflight` | 94.2% | -| `internal/modules/seriatim/input/transcript` | 90.5% | -| `internal/core/source` | 89.7% | -| `internal/cli` | 88.8% | -| `internal/modules/generic/chunk/units` | 88.6% | -| `internal/core/config` | 88.5% | -| `internal/framework/artifactcache` | 87.5% | -| `internal/framework/pipeline` | 86.7% | -| `internal/framework/diagnostics` | 83.0% | -| `internal/framework/evidencecontext` | 81.3% | - -Coverage guided inspection, not a pass/fail threshold. These are statement -measurements, not branch, assertion, mutation, or semantic-quality measurements. -Several concrete defects below execute already-covered statements with values -the suite never supplies. - -The profile reports `cmd/notarius/main.go` at 0%, but -[executable tests](../../../internal/cli/native_process_test.go#L21) build their -child with ordinary `go build`, without child coverage instrumentation. The -executable is exercised; its missing coverage contribution is a measurement -boundary, not sufficient evidence for adding tests. Similarly, `assets` reaches -100% by executing its one production statement; this says nothing about the -quality of its prompt instructions. Low coverage in small generic validators, -trivial accessors, or unused adapters was not promoted into a finding solely -because of the percentage. - -## Findings Summary - -Priorities indicate relative remediation value, not that ordinary runs or the -whole suite are unusable. Existing production defects are cross-referenced; -their test gaps are not additional independent runtime defects. - -| ID | Priority | Deficiency | Proposed test work | -| --- | --- | --- | --- | -| TEST-001 | P2 | Accepted numeric boundaries lack regression cases | Add small package-level boundary cases with the associated fixes. | -| TEST-002 | P3 | Identity/alias fixtures omit valid representational edge cases | Extend resolver and metadata tests without restricting accepted inputs. | -| TEST-003 | P2 | Native-failure assertions accept unrelated errors or encode the wrong category | Tighten the outcome oracle and correct the category assertion with ERR-001. | -| TEST-004 | P3 | Diagnostics tests cover constituent behaviors but not combined failure paths | Add focused runner-level partial-success and finalization regressions. | -| TEST-005 | P3 | Prompt tests pin English wording and repeat asset checks | Remove prose change detectors; retain distinct composition/schema behavior. | -| TEST-006 | P3 | Run-ID test freezes an incidental private representation | Remove the format regex, retaining uniqueness and path-safety checks. | -| TEST-007 | P3 | A worker test relies on wall-clock overlap; related waits diagnose poorly | Use controlled overlap and bounded, cleanup-safe handshakes. | - -## Findings - -### TEST-001 — Accepted Numeric Boundaries Lack Regression Cases - -**Functionality and existing coverage:** -[generic chunk planning](../../../internal/modules/generic/chunk/units/chunker_test.go#L59) -covers ordinary sizes, exact partitions, overlap, invalid options, and the -ConfigKit integer representation. -[Transcript parser tests](../../../internal/modules/seriatim/input/transcript/adapter_test.go#L164) -cover malformed input, ordinary negative/non-finite timestamps, and ordering -beyond floating-point integer precision. -[Reconciliation preparation tests](../../../internal/framework/semanticreconcile/preparation_test.go) -cover small context radii, candidate bounds, invalid limits, and exact material -byte boundaries. These are valuable tests, but their representative numbers do -not protect all accepted arithmetic. - -**Unverified behavior:** The three reproducible defects in the -[correctness audit](01-correctness.md) remain outside those fixtures: - -- A small source with accepted `max_units = math.MaxInt` should produce one - complete chunk, but ceiling-division preallocation overflows and panics. -- A timestamp such as `-1e-1000` should be rejected as negative, but its float - conversion underflows to negative zero before the exact rational is checked. -- A small cited source with `ContextRadius = math.MaxInt` should clamp to the - source bounds, but interval expansion overflows and returns empty evidence - windows as ready material. This last case is an internal API boundary, not the - current production default. - -**Improvement:** With the respective fixes, add narrow tests at `Chunker.Plan` -through supported option decoding, `Adapter.Parse`, and `semanticreconcile.Prepare`. -Use tiny inputs, assert exact coverage/evidence and ordinary return outcomes, -and include zero/tiny-positive/negative-zero timestamp controls. Test accepted -large values against source size rather than copying production defaults. -These cases need no huge allocation, live model, or broad fuzz harness. - -The tests should fail on the current defective results and pass after correction. -Do not make them pass by introducing arbitrary maximum sizes or new timestamp -magnitude restrictions. Additional fuzz/property coverage is optional if it -provides distinct protection; its absence alone is not a finding. - -### TEST-002 — Identity And Metadata Fixtures Omit Valid Representational Edge Cases - -**Functionality and existing coverage:** -[generated-binding resolution tests](../../../internal/framework/pipeline/profile_test.go) -check ordering, kinds, and references using ordinary identifiers. -[Metadata tests](../../../internal/core/source/chunk_plan_test.go#L210) check -deep detachment, concrete container preservation, genuine cycles, unsupported -types, and non-finite numbers. They do not distinguish all valid representations -from the invalid cases that superficially resemble them. - -**Unverified behavior:** The -[complexity audit's BUG-001 and BUG-002](03-complexity.md#additional-correctness-findings) -identify two separate gaps: - -1. `(step="a\x00b", lane="c")` and `(step="a", lane="b\x00c")` are distinct - accepted identity pairs. Concatenating them with a NUL separator aliases the - resolver's producer records. Existing tests never supply the separator inside - an identifier or distinguish the producers using different artifact kinds. -2. A finite metadata value can contain a slice and its shorter prefix view: - `values := []any{"one", nil}; values[1] = values[:1]`. Existing fixtures test - actual cycles, but not this acyclic shared-backing representation. The current - tracker rejects it as a cycle. - -These are programmatic boundary cases; ordinary transcript JSON decoding does -not construct the aliased Go slice. Neither counterexample was newly executed -in this testing pass; the production constructions and current test omissions -were inspected directly. - -**Improvement:** Add a resolver case with the two accepted pairs and different -producer kinds, asserting correct reference compatibility. Add a narrow -`source.CloneMetadata` case that accepts/clones the prefix view, preserves its -finite value, and detaches the result. Retain controls for actual map/slice -cycles and shared non-cyclic values. Keep the metadata rule in the source package -rather than repeating its representation matrix in every validator. - -Do not add an identifier-character ban or reject shared backing arrays to -satisfy the tests. These cases should accompany BUG-001/002, not become a second -implementation of their fixes in test helpers. - -### TEST-003 — Native-Failure Assertions Have An Incomplete Or Incorrect Oracle - -**Functionality and deficiency:** -[TestNativeStructuralFailureIsNotAReconciliationRetry](../../../internal/framework/semanticreconcile/engine_test.go#L109) -controls a provider response of `{"duplicate_groups":null}` and selects zero -native repairs. It checks the failed native result only when `err == nil`: - -```go -if err == nil && (result == nil || result.Validation.Status != promptkit.ValidationFailed || result.Validation.IsValid) { - // fail -} -``` - -Consequently, any unexpected error after the one generation call also satisfies -the test. The fixture can pass without demonstrating the completed failed-check -outcome it is intended to protect. Counting provider calls is appropriate here -because the budget is contractual; it does not replace an outcome assertion. - -At the application boundary, -[TestNativeProducerDoesNotInterpretFailedNativeValidation](../../../internal/framework/pipeline/producer_test.go#L162) -correctly checks safe fallback and absence of interpretation/reassessment, but -does not assert retained native validation details. More significantly, -[TestNilErrorFailedNativeValidationCannotBecomeApproval](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go#L60) -explicitly requires `errors.Is(err, promptkit.ErrValidation)` for a completed -failed content check. That assertion entrenches the category conflation recorded -in [ERR-001](06-error-handling.md#err-001--completed-native-validation-failures-lose-detail-and-acquire-an-operational-error-category). - -**Unverified behavior:** A completed structural check that rejects content must -remain non-usable, retain meaningful diagnostics, and stay distinguishable from -an operational inability to validate. Current assertions can miss the distinction -or actively reject its correction. - -**Improvement:** For the pinned native fixture, require the expected nil Go error, -present result, failed validation status, invalid flag, useful validation details, -and the test-selected call bound. At Notarius's producer/validator boundary, use -controlled native failures to verify content diagnostics and genuine operational -cause preservation separately. Remove the incorrect sentinel expectation when -addressing ERR-001; retain unavailable-validator classification, no approval, -no fabricated semantic guidance, and existing retry/fallback protections. - -Assert structured categories, cause identities, and only the smallest useful -diagnostic fragments. Do not pin the upstream validator's complete English error, -duplicate PromptKit's whole test suite, or add another retry layer. - -### TEST-004 — Diagnostics Tests Miss Failure-Path Composition - -**Functionality and existing coverage:** -[reverse-completion coverage](../../../internal/framework/pipeline/runner_concurrency_test.go#L317) -proves canonical diagnostic ordering when all chunks succeed. -[Ordered-step failure coverage](../../../internal/framework/pipeline/runner_concurrency_test.go#L266) -protects completed predecessor output and suppression of later steps. -[Aggregator tests](../../../internal/framework/diagnostics/aggregator_test.go#L43) -exercise warning bounds and occurrence overflow, while -[pipeline diagnostic tests](../../../internal/framework/pipeline/diagnostics_test.go#L20) -exercise successful finalization. These constituent tests do not cover their -important combinations. - -**Unverified behavior:** - -- A warning-bearing chunk completes, then another chunk fails before its lane - can continue. Diagnostics from completed work should survive without accepting - an incomplete lane's artifacts. ERR-002 shows that they currently disappear. -- A primary execution failure coincides with aggregate diagnostic failure. The - caller should retain the primary cause and discover the aggregation failure; - ERR-003 shows that finalization suppresses that second error and loses the - collected prefix. - -See [ERR-002/003](06-error-handling.md#err-002--successful-extraction-diagnostics-disappear-when-the-lane-never-continues) -for the production branches. The green full suite does not contradict those -findings; it never supplies the necessary combined state. - -**Improvement:** Add a deterministic runner regression with one worker, one -completed diagnostic-bearing chunk, and a later failing chunk in the same lane. -Assert the returned diagnostics, terminal cause, and absence of incomplete-lane -publication. If the correction introduces sparse-result collection, add a -controlled out-of-order case with a higher completed chunk index, checking -canonical ordering and no duplication from completed lanes. - -Separately combine a primary failure with otherwise valid groups that trigger an -existing aggregate bound, or exercise the narrow shared finalization boundary -if the fix introduces one. Assert both inspectable causes and the selected -bounded/incomplete diagnostic outcome. These tests belong to orchestration; -repeating the aggregator's full matrix in the CLI is unnecessary. Do not raise -limits, demand warnings for unfinished work, or convert best-effort cache I/O -into mandatory failure as a side effect. - -### TEST-005 — Prompt Tests Contain Prose Change Detectors - -**Relevant tests:** -[registry prompt pairs](../../../assets/registry_extraction_test.go#L15), -[scene prompt pairs](../../../assets/scene_descriptions_test.go#L75), -[combat prompt pairs](../../../assets/combat_turns_test.go#L15), -[registry normalization prompts](../../../assets/package_test.go#L149), -[generic reconciliation prompts](../../../internal/framework/semanticreconcile/assets_test.go#L12), -and [spell prompt pairs](../../../internal/modules/dnd/extract/spells/prompt_assets_test.go#L12). - -**Deficiency:** These tests mix useful native-contract/input assertions with -literal fragments of authored English, such as `proper name or a stable, -individually distinguishing`, `must not invent a proper noun`, `same physical -place`, and `canonical spelling exactly`. Equivalent instruction wording can -fail the test; contradictory instructions can pass as long as those fragments -remain. String containment does not prove the semantic behavior of the model. - -[TestExtractionPromptComposition](../../../assets/prompt_composition_test.go#L11) -also uses production prose as message-location sentinels. Its test-generated -transcript/reference sentinels provide a stable way to observe input placement, -but its evidence/endpoint/combat-policy phrases couple ordering checks to text -editing. The issue is the oracle, not the importance of those domain policies. - -**Improvement/removal candidates:** Remove assertions that freeze non-contractual -English, including their now-unused rule tables. Narrow mixed tests to the distinct -behavior they protect: actual native preparation, declared schemas/default -selection, fixed input binding/cache hints, and correction guidance without -regenerating source material. Use test-controlled sentinels for supplied content. -Where two tests then protect exactly the same composition behavior, consolidate -at the assets owner; preserve module tests that exercise different routing or -execution behavior. Shared assets and focused prompt review keep authored -instructions coherent without pretending that word matches measure extraction -quality. Do not replace these checks with prompt hashes or whole-prompt snapshots. - -Retain [automatic embedded-prompt preparation](../../../assets/package_test.go#L61), -which discovers actual declarations and verifies loaded schemas, and -[required-property compatibility checks](../../../assets/schema_compatibility_test.go#L14). -Field names, enums, opaque-ID exclusions, selected public defaults, and the -established follow-up-message contract are genuine contracts even when exact -values/counts are involved. This finding is not a blanket ban on string assertions -or a recommendation to remove all prompt tests. Optional live semantic evaluation -may complement review, but belongs outside the deterministic default suite. - -### TEST-006 — Run-ID Test Freezes An Incidental Private Format - -**Functionality and deficiency:** -[TestDefaultRunIDGeneratorProducesUniqueSafeIDs](../../../internal/cli/run_id_test.go#L14) -generates 256 IDs for the same timestamp and checks uniqueness and path safety. -It additionally requires the exact regex `^run-123456789-[0-9a-f]{32}$`. - -The current [operations guide](../../operations.md) describes isolated run state, -not a consumer contract for timestamp formatting or random hexadecimal width. -A correct change to the private representation could therefore fail this test -despite preserving its meaningful guarantees. Conversely, the regex itself does -not prove independent run allocation or collision handling. - -**Improvement/removal candidate:** Remove the exact private-format assertion, -retaining controlled-timestamp uniqueness and the existing path-safety validation. -Retain separate output allocation/collision and partial-write tests in the same -file. This is a small narrowing, not a reason to delete the whole test. - -Distinguish this from the -[versioned session-ID vector](../../../internal/cli/session_test.go#L5): stable -cross-run routing is an explicitly selected behavior, so its versioned identity -test has contractual value. Do not remove exact expectations indiscriminately. - -### TEST-007 — Concurrency Tests Need Controlled Overlap And Better Failure Bounds - -**Functionality and deficiency:** -[TestRunnerBoundsConcurrentLaneContinuations](../../../internal/framework/pipeline/runner_concurrency_test.go#L394) -sleeps for five milliseconds inside each merge, then requires observed peak -concurrency to equal two. The sleep encourages overlap but does not establish it: -a delayed runnable worker can miss the window even when the runner is correct. -The test can therefore fail because of scheduling rather than a worker-limit -defect. This is a static reliability risk; the focused repeated run did not -exhibit a failure. - -The related -[reverse-completion test](../../../internal/framework/pipeline/runner_concurrency_test.go#L317) -uses unconditional receives from `started` and `done`. A scheduling regression -or early runner error can leave the test waiting until the global Go test timeout, -instead of reporting the missing event locally. Its existing handshakes are more -useful than sleeps, but their failure/cleanup path is incomplete. - -**Unverified behavior and improvement:** Explicitly hold started continuation -jobs at release gates and observe the test-selected limit before releasing them. -Then verify completion and zero retained activity, without relying on elapsed -wall time to make overlap happen. Use test-scoped cancellation/deadlines or -`testing/synctest` as appropriate, release gates on failure, and join started work. -The existing -[mixed-ready-jobs test](../../../internal/framework/pipeline/ready_jobs_test.go#L34) -provides a local example of controlled scheduling. - -Keep the runtime worker-limit protection; rewriting these tests is preferable to -deleting them. A local test watchdog diagnoses a regression and does not establish -a new production timeout or performance guarantee. No general deadline helper -framework is necessary. - -## Validation And Limits - -The complete suite was run with fresh, cross-package atomic coverage using the -available Go 1.27.0 toolchain and cached declared dependencies. Equivalent -reproduction commands are: - -```sh -testing_audit_dir=$(mktemp -d) -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - -coverpkg=./... -covermode=atomic \ - -coverprofile="$testing_audit_dir/coverage.out" -json ./... \ - > "$testing_audit_dir/tests.jsonl" -GOTOOLCHAIN=go1.27.0 go tool cover -func="$testing_audit_dir/coverage.out" -``` - -The coverage profile's repeated block locations were unioned for package totals; -per-test-package percentages under `-coverpkg=./...` were not mistaken for each -package's local coverage. JSON test events supplied the test/package counts. -Generated profiles and logs remained outside the repository. - -Three relevant scheduling tests also passed 20 shuffled repetitions: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly \ - -shuffle=on -count=20 ./internal/framework/pipeline \ - -run '^(TestRunnerBoundsConcurrentLaneContinuations|TestRunnerBoundsExtractJobsAndStabilizesReverseCompletion|TestRunnerSharesWorkerLimitBetweenExtractionAndReadyContinuation)$' -``` - -No mutation-testing tool was run and no deliberate production/test mutations -were made. The counterexamples from earlier audits provide concrete evidence -of inadequate input/assertion protection, not a measured mutation score. The -[earlier concurrency audit](04-concurrency.md#validation) already records a fresh -full race run at unchanged production code; this pass did not repeat that run. -No credentials, production transcripts, live providers, or paid inference calls -were used. Passing fake-provider tests establishes application behavior for the -supplied responses, not real-model extraction quality. - -The review does not recommend 100% coverage, a mandatory fuzz inventory, new -live-provider release gates, or tests for every trivial helper. Test additions -should accompany concrete behavior fixes; removal/narrowing should target the -incidental assertions identified above. Earlier audit findings remain open and -are not resolved by this report. Report links and the final documentation diff -are checked before committing. diff --git a/docs/roadmap/audit/10-equivalence.md b/docs/roadmap/audit/10-equivalence.md deleted file mode 100644 index 0fcaf2d0..00000000 --- a/docs/roadmap/audit/10-equivalence.md +++ /dev/null @@ -1,461 +0,0 @@ -# Behavioral Equivalence And Shared Abstraction Audit - -## Baseline And Method - -Reviewed revision `ee94d7902571117e9dea654b6c207544a19c979b` on 2026-11-24. -Production code and tests are unchanged from the preceding audits. This pass -adds only this report; it changes no production code or tests. - -The review started with tests: direct comparisons, round trips, mutation/isolation -checks, and separate assertions of the same transformations or failure rules. -Code-graph discovery, source inspection, and caller tracing then established -whether the corresponding implementations independently own a common mechanism. -Matching names, similar interfaces, and repeated test setup were not sufficient -evidence for a finding. Existing shared implementations were checked before -recommending another abstraction. - -The review applied the [testing](../../policy/testing.md), -[architecture](../../policy/architecture.md), and -[agent](../../policy/agents.md) policies. In particular, tests are evidence of -behavior, not independent authority to invent a requirement. The accepted -[reconciliation boundary](../../adr/0013-use-request-local-candidate-handles-for-semantic-reconciliation.md), -[native producer/assessment boundary](../../adr/0022-use-native-continuation-and-application-assessment.md), -and [configuration ownership](../../adr/0020-delegate-configuration-mechanics-to-configkit.md) -decisions support the shared responsibilities described below. - -Scope included configuration/runtime conversion, pipeline and CLI reference -selection, prepared-input ownership, native result handling, registry resolution, -registry reconciliation, deterministic normalization, codecs, source-reference -helpers, and representative assembled workflows. This is a risk-directed audit, -not an exhaustive proof of equivalence across every package or configuration. - -## Current Architecture - -Notarius retains its fixed typed pipeline: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -The CLI owns application composition and physical publication. The framework owns -typed preparation, complete assessment, native producer coordination, ready-job -scheduling, generated handoffs, and accepted-result reuse. Artifact families own -identity, interpretation, domain validation, normalization policy, and durable -codecs. ConfigKit, PromptKit, CommandKit, and ReleaseKit retain their selected -native responsibilities; assets remain content-only. - -Several important abstractions already exist: `RunProducer`, `AssessProducer`, -`FinishProducerFailure`, source indexes/reference ordering, typed reconciliation -preparation/application, candidate JSON encoding, diagnostic collection, and the -immutable registry resolver. The remaining opportunities concern common work -around those boundaries, not replacement of the architecture. - -## Findings Summary - -Priority expresses relative refactoring value, not a new runtime severity score. -Five opportunities have supporting tests and corresponding duplicated logic. - -| ID | Priority | Common responsibility | Recommended boundary | -| --- | --- | --- | --- | -| EQ-001 | High | Registry reconciliation operation lifecycle | Small typed lifecycle support beside the existing reconciliation core. | -| EQ-002 | Medium | Stable exact-duplicate group bookkeeping | Pure D&D helper; family-owned eligibility, identity, ordering, and output. | -| EQ-003 | Medium | Detached copies of pipeline-owned values | Pure copying in the package owning those values, separate from normalization. | -| EQ-004 | High | Structural pipeline interpretation and selected target inventory | Pipeline-owned layout/selection helpers used by configuration and CLI callers. | -| EQ-005 | Low | Native-result usability before interpretation | One small framework check, retaining separate caller outcomes. | - -EQ-001, EQ-003, and EQ-004 substantiate CPLX-004, CPLX-007, and CPLX-003 in the -[complexity audit](03-complexity.md) with test-level evidence. They are the same -work opportunities, not additional independent defects. EQ-005 is best considered -alongside ERR-001 from the [error-handling audit](06-error-handling.md). - -## EQ-001 — Registry Normalizers Repeat One Reconciliation Lifecycle - -### Evidence - -The NPC and location -[`TestNativeCorrectionPreservesFixedHistoryAndAssessesEachRevision`](../../../internal/modules/dnd/normalize/npcregistry/native_execution_test.go#L33) -[tests](../../../internal/modules/dnd/normalize/locationregistry/native_execution_test.go#L33), -and item -[`TestNativeNormalizationReassessesRevisionsAndUsesOnlyTheFinalProposal`](../../../internal/modules/dnd/normalize/itemregistry/native_execution_test.go#L84) -independently establish the same lifecycle: - -- Retain original records and fixed evidence across revisions. -- Apply each complete proposal afresh; do not accumulate earlier safe groups. -- Reassess each usable revision, including unchanged candidates. -- Preserve explicit native model/profile/session selections and conversation. -- Disclose permissive fallback and exclude it from reuse. - -The [location native-failure matrix](../../../internal/modules/dnd/normalize/locationregistry/native_execution_test.go#L115) -and corresponding NPC/item native execution suites additionally prohibit -recovering an earlier proposal after a failed response. Preparation-limit tests -for [NPCs](../../../internal/modules/dnd/normalize/npcregistry/semantic_normalizer_test.go#L254), -[locations](../../../internal/modules/dnd/normalize/locationregistry/normalizer_test.go#L176), -and [items](../../../internal/modules/dnd/normalize/itemregistry/normalizer_test.go#L313) -all require zero model/ordinary-assessment calls for preparation-limit failure -and the same strict/permissive terminal decision. Cancellation tests in those -suites require cancellation rather than fallback. - -These requirements are also explicit in ADRs 0013 and 0022. This is not an -inference that similarly named entities have the same identity rules. - -### Implementation - -The `Normalize` methods for -[NPCs](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go#L57), -[locations](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go#L58), -and [items](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go#L58) -are near-identical 127–133-line operation bodies. Each independently retains -merged versus deterministic originals, tracks current findings/omissions, builds -fallback and finish closures, handles no-model/preparation dispositions, records -the same evidence envelopes, decodes/assesses proposals, builds correction -requests, and delegates execution to `pipeline.RunProducer`. - -The existing `semanticreconcile` core already shares proposal safety and typed -application, while `RunProducer` already shares native iteration. The duplication -is the reconciliation-specific operation glue between those abstractions. - -### Opportunity And Remediation Approach - -Factor that operation glue into a small typed helper beside the existing -reconciliation mechanism. Give one owner to fixed preparation, native request and -proposal bookkeeping, evidence recording, current-proposal replacement, and -disposition handoff. Continue using `RunProducer`, `AssessProducer`, and -`FinishProducerFailure`; introduce no additional execution or retry engine. - -Family adapters should supply preprocessing, cloning, typed proposal application, -fallback validity, prompt selection, and domain diagnostic construction. Return -current-proposal omission/application information explicitly rather than making -three modules maintain parallel mutable closure state. Keep domain diagnostic -types out of the domain-neutral framework; a D&D-local adapter may translate the -neutral result into existing findings. - -This is a useful extraction of a demonstrated repeated lifecycle, not a reason -to design a general normalization plugin framework. A few typed callbacks or a -small operation value are sufficient if they make the call sites clearer. - -### Tradeoffs And Test Independence - -Item reconciliation has additional currency-denomination compatibility, rejected -group accounting, guidance, and advisory findings. Locations retain same-name -places at distinct evidence anchors; NPCs have their own canonical-name policy. -Those differences remain in family code. Shared mechanics must not make all -domains collapse equal labels or use one fallback-validity rule. - -The main risk is replacing three readable procedures with an overly configurable -callback framework. Extract the proven common lifecycle, not all record logic. -Keep representative tests in each family using literal expected domain values, -including item currency and same-name location cases. Common lifecycle tests can -own the transition matrix, but family tests must still prove correct adaptation; -do not compute expected artifacts with the helper being tested. - -## EQ-002 — Exact-Duplicate Collapse Repeats Stable Group Bookkeeping - -### Evidence - -[`TestNormalizeOrdersAndCollapsesExactDuplicatesOnly`](../../../internal/modules/dnd/normalize/npcoccurrences/normalizer_test.go#L86), -[`TestNormalizeKeepsSameNamedIDsAndDistinctEvidence`](../../../internal/modules/dnd/normalize/locationoccurrences/normalizer_test.go#L47), -and the [combat normalizer tests](../../../internal/modules/dnd/normalize/combatturns/normalizer_test.go) -establish the same mechanical requirement: collapse eligible exact duplicates, -retain distinct identity/evidence/kind values, preserve ineligible references, -and report removed original input indices. The -[spell duplicate-group test](../../../internal/modules/dnd/normalize/spells/normalizer_test.go#L289) -also requires retaining the first representative after canonicalization and -accounting for removed groups without rewriting the retained caster text. - -These tests do not establish one common definition of entity/event identity or -one global sort order. For example, -[`TestNormalizePreservesStableOrderForEqualEvidencePositions`](../../../internal/modules/dnd/normalize/combatturns/normalizer_test.go#L177) -protects combat's stable ties, while occurrence tests exercise category-specific -ordering. They support sharing grouping mechanics after family preparation. - -### Implementation - -`collapseDuplicates` in -[NPC occurrences](../../../internal/modules/dnd/normalize/npcoccurrences/normalizer.go#L168), -[location occurrences](../../../internal/modules/dnd/normalize/locationoccurrences/normalizer.go#L172), -and [combat turns](../../../internal/modules/dnd/normalize/combatturns/normalizer.go#L208) -repeats the same keep mask, key-to-group index, first representative, removed-index -list, output traversal, and diagnostic-group traversal. The spell -[`collapseDuplicateSpellCasts`](../../../internal/modules/dnd/normalize/spells/normalizer.go#L158) -adds a no-removal fast path around essentially the same grouping. - -[Item occurrences](../../../internal/modules/dnd/normalize/itemoccurrences/normalizer.go#L194) -have related bookkeeping but deliberately use key buckets plus -`CanonicalExactEqual`, rather than trusting a key alone. The -[item model equality tests](../../../internal/modules/dnd/itemoccurrences/itemoccurrences_test.go#L85) -distinguish canonicalization-aware versus already-canonical comparison and -preserve optional quantity/evidence differences. - -### Opportunity And Remediation Approach - -Introduce one pure helper under the existing D&D shared area that computes kept -record positions and duplicate groups from caller-supplied eligibility/keys. -Keep it unaware of domain structs, diagnostic prose, source parsing, and model -execution. Callers retain their preprocessing, ordering, record cloning, and -mapping from record positions to original input indices. - -Start with NPC occurrences, location occurrences, and combat turns, where the -grouping loops match directly. Include spells if its allocation/nil behavior can -remain outside the helper. Item occurrences should participate only if the -helper preserves the explicit equality check within each key bucket; leaving -that one variant local is preferable to weakening equality or overcomplicating -all callers. - -### Tradeoffs And Test Independence - -A generic grouping helper reduces repeated index-accounting code but must not -grow into one universal event normalizer. Preserve the domain-owned eligibility -and exact keys, nil versus present-empty representations, original-index -diagnostics, and each family's output cloning. Do not merge overlapping or -adjacent evidence merely because it is convenient for deduplication. - -There are intentional pre-grouping differences: NPC occurrences reject unknown -or mismatched registry identities, while location occurrences retain unknown -values with advisories and canonicalize known names. Combat and spells have -different matching and ordering policies. Preserve these differences. - -Keep the existing package-level output tests and independent expected records; -test the shared grouping helper with small controlled keys/eligibility, not domain -normalizers as its oracle. A wholesale replacement of all family tests by one -parameterized conformance harness would lose useful independent protection. - -## EQ-003 — Configuration And Pipeline Boundaries Independently Copy The Same Values - -### Evidence - -[`TestEffectiveConfigAndResolutionInputsDoNotAliasSource`](../../../internal/core/config/effective_config_contract_test.go#L268) -mutates both effective configuration and resolved pipeline options/references and -requires the source configuration to remain unchanged. -[`TestLoadedConfigOwnsRuntimeValuesAndKeepsFrozenInspection`](../../../internal/core/config/loaded_config_test.go#L92) -requires independent runtime copies and unchanged frozen inspection. - -At framework boundaries, -[`TestValidatorChainRegistryReturnsDefensiveCopies`](../../../internal/framework/pipeline/validator_chain_registry_test.go#L55) -and [`TestOutputProfileValidationReceivesOwnedOptionsAndLaneIDs`](../../../internal/framework/pipeline/output_registry_test.go#L65) -require the same ownership property for module bindings and nested options. -These tests establish a common detached-value requirement for the pipeline-owned -data, rather than merely similar function signatures. - -### Implementation - -[Configuration copying](../../../internal/core/config/config.go#L44) implements -its own recursive pipeline/step/lane/binding/reference/validator-option tree. -Framework copying in -[validator_chain_registry.go](../../../internal/framework/pipeline/validator_chain_registry.go#L84), -[profile.go](../../../internal/framework/pipeline/profile.go#L1445), and prepared -value construction independently traverses the same types and mutable fields. - -The implementations are not interchangeable today: framework -`cloneModuleBinding` also trims module/profile names, while configuration copying -preserves them. Option switches differ too: framework copying explicitly handles -`[]string`, `[]byte`, and `json.RawMessage`; configuration copying handles maps -and `[]any`. The inspected ownership tests establish the overlapping nested-value -contract, not that every extra container is already guaranteed at every boundary. - -### Opportunity And Remediation Approach - -Give pipeline-owned values one pure copying implementation in `pipeline`, usable -by configuration conversion and framework callers. Small clone methods/functions -for the existing types are sufficient. Separate identifier normalization from -copying and make existing trimming explicit where resolution requires it. -Keep configuration-only scalar/root copying in `config`. - -Inventory the currently supported mutable option representations before unifying -the two switches. Preserve established representations and omission/explicit-zero -controls; do not turn the extraction into an arbitrary reflection deep copier or -silently expand/restrict the option contract. This factors runtime value ownership, -not ConfigKit's frozen-result/provenance machinery. - -### Tradeoffs And Test Independence - -Exporting a small internal-package copy API adds a dependency surface, but -`config` already imports the package that owns these types. This is preferable -to moving pipeline types into configuration or creating another generic data -model. Calling the current normalizing clone directly would be an incorrect -shortcut because inspection/source values can change under apparent copying. -Source profiles and resolved pipelines remain different types; share their common -binding/reference/options subtrees rather than converting one model into another. - -Retain mutation-based tests at both runtime conversion and framework boundaries, -with independently constructed source values. Sharing implementation does not -make those boundary tests redundant. Keep source-metadata validation, native -evidence copying, and domain record cloning separate: their accepted values and -failure semantics differ. - -## EQ-004 — Configuration, Runtime Resolution, And CLI Reference Selection Reinterpret Composition - -### Evidence - -[`TestValidateIdentifiersAfterTrimming`](../../../internal/core/config/validation_contract_test.go#L40) -requires canonical nonblank/unique lane and reference identities. -[Runtime resolver tests](../../../internal/framework/pipeline/profile_test.go) -independently require normalized identity handling, deterministic lane selection, -ordered-step interpretation, and selected-lane reference completeness. - -[`TestReferenceSelectorsRejectInvalidOrUnselectedScopesBeforeMaterialization`](../../../internal/cli/reference_contract_test.go#L89) -requires CLI selectors to operate on that same selected composition before file -access. [`TestReferenceTargetLookupUsesArtifactVariantsAndReportsMissingContext`](../../../internal/cli/reference_contract_test.go#L321) -requires lane-kind-specific merger/normalizer slots; framework -[`TestResolveTypedHeterogeneousLanes`](../../../internal/framework/pipeline/typed_resolution_test.go#L143) -and [`TestResolveTypedLaneRejectsIncompatibleComposition`](../../../internal/framework/pipeline/typed_resolution_test.go#L203) -require the corresponding artifact-kind-specific module selection and failures. - -Together these tests imply that reference expansion and execution must select -the same application composition. They do not imply identical diagnostic strings -or equal validation depth at loading, selection, and full runtime resolution. - -### Implementation - -[`config.validatePipelineProfiles`](../../../internal/core/config/validation.go#L30) -constructs implicit steps and checks step/lane identities. -[`pipeline.ResolvePipeline`](../../../internal/framework/pipeline/profile.go#L337) -does those operations again, selects lanes, applies module defaults, and resolves -kind-specific variants. [`cli.selectedReferenceTargets`](../../../internal/cli/reference_selectors.go#L288) -again flattens/selects lanes, applies defaults, and looks up extractor/merger/ -normalizer variants solely to discover reference slots. - -There are already smaller helpers such as `selectedArtifactLanes`, but the CLI -does not consume one authoritative selected-target inventory. Changing a module -default or layout rule still requires coordinated edits to separate traversals. - -### Opportunity And Remediation Approach - -Extract a pure pipeline-layout operation for the common runtime-value structural -rules, and a separate catalog-aware selected-target inventory for module choices, -artifact kinds, and reference slots. Let runtime resolution and CLI expansion -consume these results rather than independently reconstruct them. Configuration -validation can reuse the catalog-independent portion and add its own path context. - -Keep CLI selector parsing, specificity, bind/unbind actions, and invocation-relative -paths in the CLI. Keep capability flow, complete typed compatibility, required -reference satisfaction, validator resolution, and generated dependency validation -at their existing later boundaries. Share choices, not every validation phase. - -### Tradeoffs And Test Independence - -The CLI needs the inventory before its reference overrides have satisfied required -slots. Calling the complete resolver there would be circular or reject a -legitimate invocation too early. Likewise, configuration loading need not acquire -a full production catalog merely to validate structural fields. - -Raw-document presence and source-path diagnostics remain distinct. For example, -[document shape tests](../../../internal/core/config/pipeline_document_test.go#L120) -can distinguish an explicitly present empty `artifacts` field from absence; a -decoded value alone cannot recover all those facts. Do not replace ConfigKit -composition/presence handling with a new application loader, erase useful source -diagnostics, add identifier restrictions, or change supported selection behavior. - -Retain independent CLI mapping and framework resolution tests. A small differential -test using a test catalog may check that CLI expansion and execution select the -same targets, but each owner still needs literal expected examples; comparing two -callers of one helper is not an independent correctness oracle. This refactor has -high value but needs more care than the local grouping extraction. - -## EQ-005 — Producers And An LLM Validator Duplicate The Native Usability Gate - -### Evidence - -[`TestNativeProducerDoesNotInterpretFailedNativeValidation`](../../../internal/framework/pipeline/producer_test.go#L162) -requires both initial and correction responses with failed native validation to -remain uninterpreted and unassessed. The combat validator's -[`TestNilErrorFailedNativeValidationCannotBecomeApproval`](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go#L60) -explicitly constructs a failed native validation result with nil Go error and -requires no semantic approval or corrective guidance. - -These tests support the common rule that native call completion alone does not -make its output usable. They do not equate producer fallback with validator -unavailability. The validator test's current `ErrValidation` sentinel assertion -is the category problem already identified in ERR-001/TEST-003, not a requirement -to preserve during consolidation. - -### Implementation - -[`RunProducer`'s evaluator](../../../internal/framework/pipeline/producer.go#L67) -and [`combat_semantics.Validator.Validate`](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go#L70) -independently check nil result, `ValidationFailed`, and `IsValid` before interpreting -native content. Both substitute generic text and `promptkit.ErrValidation` for a -completed failed check, losing available content-check details and conflating -that outcome with the native operational category. - -### Opportunity And Remediation Approach - -When addressing ERR-001, give the usability check and descriptive nonacceptance -construction one small framework owner beside the existing native helpers. -Keep the native `RunResult` and validation details as the input; distinguish an -absent result from a present failed check and preserve actual native Go causes. -Callers retain their contextual wrapping and terminal behavior. A new execution -interface or package is unnecessary for this small shared check. - -### Tradeoffs And Test Independence - -This is a low-cost adjunct to the known diagnostic fix, not justification for -another native adapter layer. Do not put semantic acceptance, capture -terminalization, cancellation precedence, or continuation policy into the helper. -In particular, do not route the validator through producer semantic retries: -validators still execute once per assessment and report unavailability separately. - -Keep producer and validator tests asserting their distinct outcomes. Shared -helper tests can cover native result states and retained details, while each -caller test proves that failed output never reaches its domain interpreter. -Do not make both tests derive expected categories/messages by calling the helper. - -## Scope Limits And Existing Abstractions - -No further abstraction is recommended merely because multiple codecs round-trip, -multiple validators reject malformed input, or command aliases accept the same -arguments. Inspected candidate JSON and registry caching mechanics already use -shared helpers. Shared source ordering/matching and diagnostics also have real -owners; their use by several families is not missing consolidation. - -The review specifically avoids unifying all normalizers, registry identity rules, -schema and semantic validation, source metadata and option copying, or producer -and validator outcomes. Native kit ownership and typed stage boundaries remain -unchanged. Shared test fixtures are useful only where they reduce setup without -making expected results depend on the same implementation as actual results. - -No new runtime defect is claimed by this report. Existing findings remain open; -the opportunities above should be coordinated with their remediation rather than -implemented as competing abstractions. The strongest next candidates are the -registry lifecycle and composition inventory, with pure copying/grouping offering -smaller independent refactors. - -## Validation - -The following fresh offline checks passed with Go 1.27.0 and cached declared -dependencies: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/core/config ./internal/framework/pipeline \ - ./internal/framework/semanticreconcile ./internal/modules/dnd/normalize/... \ - ./internal/modules/dnd/shared/... \ - ./internal/modules/dnd/validate/scenedescriptions/combat_semantics \ - ./internal/modules/integration - -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/cli \ - -run '^(TestReference|TestPipelineScopedCLIReference|TestCLIReference|TestNativeConfiguration)' - -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/modules/dnd/itemoccurrences ./internal/modules/dnd/npcoccurrences \ - ./internal/modules/dnd/codec/candidatejson \ - ./internal/modules/dnd/npcs/registry ./internal/modules/dnd/items/registry \ - ./internal/modules/dnd/locations/registry \ - ./internal/modules/dnd/scenedescriptions/registry - -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/cli \ - -run '^(TestCompleteDNDSharedCLIReferencesExpandAcrossCompatibleTargets|TestExecutableRunRoutesDeclareTheSameRequiredInputs)$' -``` - -The `npcoccurrences` model package has no separate test files; its consumers' -tests provide the relevant exercised behavior. No credentials, live providers, -paid calls, new tests, or production modifications were used. Test success confirms -the inspected baseline expectations, not a proof that proposed refactors are -equivalent. Future changes should retain those independent output/state assertions -and add focused helper coverage where it provides distinct confidence. - -The previous [testing audit](08-testing.md) records the fresh full coverage suite -at unchanged code; another coverage measurement was unnecessary for this audit's -architectural question. Local report links and the final diff are checked before -committing. diff --git a/docs/roadmap/audit/11-boundaries.md b/docs/roadmap/audit/11-boundaries.md deleted file mode 100644 index d101a639..00000000 --- a/docs/roadmap/audit/11-boundaries.md +++ /dev/null @@ -1,357 +0,0 @@ -# Package Cohesion And Architectural Boundaries Audit - -## Baseline And Method - -Reviewed revision `7a14a43677626e7faa7bc60f5d8d4cfbdd835d45` on 2026-11-24. -Production code and tests are unchanged from the preceding audits. This pass adds -only this report, without changing production code or tests. - -The review followed the [architecture](../../policy/architecture.md), -[agent](../../policy/agents.md), and [testing](../../policy/testing.md) policies -and compared actual responsibilities with the -[implemented component map](../../internal/overview.md). Code-graph searches and -caller tracing located likely ownership seams; Go's package/import inventory and -source inspection established the actual dependency directions. Name-based call -graph associations were not treated as proof of Go imports. - -The default-build inventory contains 125 repository packages, including 123 under -`internal/` and packages containing only tests. Review scope was repository-owned -packages only. Third-party implementations were not audited; their imported types -were considered only to distinguish intentional native integration from local -ownership decisions. The import inventory reflects the current Linux build; -the existing import-boundary test additionally scans repository Go files rather -than only the files selected for that build. - -The review covered composition/configuration, framework contracts and execution, -preflight, source and auxiliary artifacts, cache/debug/file placement, domain -models, registries, codecs, stage implementations, validators, shared helpers, -and registrars. It is a responsibility-directed review, not a proof of every -supported configuration or hypothetical extension. - -## Architecture Assessment - -The central architecture remains coherent: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -- The CLI composes native kits and family registrars, selects run inputs/state, - publishes logical output, and submits reports. -- Configuration owns application fields and runtime conversion; the pipeline - framework owns typed resolution/preparation, assessment, producer coordination, - ready-job execution, generated handoffs, and reuse eligibility. -- Artifact families own domain identity, interpretation, transformations, codecs, - contextual projections, validator policy, and prompts. Registrars compose their - implementations without owning process execution. -- Source, filesystem helpers, accepted-result storage, and debug recording have - focused responsibilities. Embedded assets remain a content-only leaf. - -The actual production imports show no core/framework dependency on concrete -module implementations, no production extension dependency on the CLI, and no -CLI dependency on concrete stage implementations instead of family registrars. -Generic production modules do not import D&D or Seriatim implementations. -`core/source` remains independent of the framework, and `assets` imports no -internal package. The existing production import-boundary tests pass. - -The `core/config -> framework/pipeline` dependency is intentional: configuration -uses pipeline-owned values and domain resolution. It is not a cycle or a policy -violation merely because the broad directory names suggest layers. Likewise, -native PromptKit types at the execution boundary are an accepted architectural -choice, not leakage that needs another adapter. - -The findings concern more local ownership overlap and cohesion. None establishes -a new runtime correctness defect or a breach of the checked import-direction -rules. Package size and fan-in alone were not used to justify package splitting. - -## Findings Summary - -Priority is relative refactoring value, not a runtime severity classification. - -| ID | Priority | Category | Responsibility needing a clearer owner | -| --- | --- | --- | --- | -| BND-001 | High | Overlapping/fragmented | Pipeline layout and selected-module/reference inventory across configuration, CLI, and resolver. | -| BND-002 | Medium | Overlapping | Pure copying of pipeline-owned values across configuration and framework code. | -| BND-003 | Medium | Misplaced/mixed | Reusable scene shape rules housed in a selectable validator adapter. | -| BND-004 | Low | Mixed cohesion | Native request capture housed with pipeline-specific operation scoping. | -| BND-005 | Medium | Overlapping | Reconciliation operation lifecycle repeated by three registry normalizers. | - -BND-001, BND-002, and BND-005 reinforce EQ-004, EQ-003, and EQ-001 in the -[equivalence audit](10-equivalence.md), respectively, and their related complexity -findings. They are not additional independent remediation projects. BND-003 and -BND-004 identify narrower package-placement concerns. - -## BND-001 — Pipeline Composition Meaning Has Three Partial Owners - -**Relevant implementation:** -[`config.validatePipelineProfiles`](../../../internal/core/config/validation.go#L30), -[`pipeline.ResolvePipeline`](../../../internal/framework/pipeline/profile.go#L337), -[`selectedArtifactLanes`](../../../internal/framework/pipeline/profile.go#L1478), -and [`cli.selectedReferenceTargets`](../../../internal/cli/reference_selectors.go#L288). - -**Basis:** Configuration independently interprets flat artifacts versus ordered -steps, constructs implicit steps, and checks normalized step/lane identities. -The runtime resolver repeats that structural interpretation, then selects -modules/defaults and artifact-kind-specific variants. CLI reference expansion -again flattens/selects lanes and resolves the same module/default/variant choices -to discover reference slots. - -Loading, CLI mapping, and runtime resolution are valid separate boundaries. -However, application composition choices shared by those boundaries lack one -reusable representation/owner. A module default or layout change needs coordinated -edits to three traversals. The existing -[CLI reference tests](../../../internal/cli/reference_contract_test.go#L321), -[typed resolution tests](../../../internal/framework/pipeline/typed_resolution_test.go#L143), -and [configuration structural tests](../../../internal/core/config/validation_contract_test.go#L40) -substantiate the overlapping responsibility. - -**Potential remediation:** Let `pipeline`, which already owns the profile and -resolved types, own two small operations: catalog-independent runtime-value -layout interpretation, and catalog-aware selected-target inventory. Reuse their -results in configuration validation, reference expansion, and full resolution. -Keep configuration source/presence diagnostics and CLI selector grammar, -specificity, bind/unbind conversion, and invocation-path handling with their -current owners. Keep capabilities, complete type compatibility, required -reference satisfaction, validator selection, and generated dependencies in full -resolution/preparation. - -The CLI needs selected targets before its overrides satisfy required references; -calling the full resolver there is not a substitute for the smaller inventory. -Configuration-only structural checks also need not construct a production -catalog. Raw-document presence cannot always be reconstructed from decoded Go -values, so its existing ConfigKit-backed checks remain separate. This is a -consolidation of application meaning, not an application replacement for ConfigKit -loading/composition. Preserve phase-specific error context and existing accepted -identifiers rather than introducing stricter validation to simplify the sharing. - -## BND-002 — Pipeline Value Ownership Is Implemented Outside Its Type Owner - -**Relevant implementation:** -[configuration clone tree](../../../internal/core/config/config.go#L44), -[framework binding/reference copies](../../../internal/framework/pipeline/validator_chain_registry.go#L84), -and [framework option copies](../../../internal/framework/pipeline/profile.go#L1445). - -**Basis:** `core/config` maintains its own pipeline/step/lane/binding/reference/ -validator copying functions even though the copied types belong to `pipeline`. -Framework construction, registry, and prepared-value paths maintain another -copying subtree for bindings, controls, references, overrides, and options. The -ownership requirement is shared, as demonstrated by -[effective-config mutation tests](../../../internal/core/config/effective_config_contract_test.go#L268) -and [framework defensive-copy tests](../../../internal/framework/pipeline/validator_chain_registry_test.go#L55). -Adding a mutable field requires auditing several traversals instead of its type -owner providing the copying operation. - -The helpers also mix responsibilities inconsistently: framework -`cloneModuleBinding` trims module/profile identifiers, while the configuration -copy preserves them. The option switches support different concrete containers. -Those differences mean the functions should not simply be substituted for one -another under their current names. - -**Potential remediation:** Provide small pure clone functions/methods for -pipeline-owned values in `pipeline`; keep root configuration copying in `config`. -Make trimming/defaulting explicit at resolution sites rather than a side effect -of copying. Share common binding/reference/options subtrees; source profiles and -resolved pipelines remain different types. - -Inventory supported option representations before unifying the switches. The -existing nested-map ownership tests do not by themselves establish a universal -contract for every mutable Go value. Preserve omission versus explicit controls -and source/frozen inspection. Avoid a generic reflection copier, JSON round trips, -or combining this with source-metadata validation, which has different accepted -representations and error behavior. Existing mutation-based tests should continue -to cover both conversion and framework boundaries independently. - -## BND-003 — Scene Domain Rules Live Inside A Selectable Validator Package - -**Relevant implementation:** -[`validate/scenedescriptions/shape`](../../../internal/modules/dnd/validate/scenedescriptions/shape/validator.go#L45), -[`normalize/scenedescriptions.normalizeList`](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer.go#L66), -other scene validator packages, and -[the scene codec](../../../internal/modules/dnd/codec/scenedescriptions/codec.go#L82). - -**Basis:** The shape package combines three responsibilities: reusable field/kind -checks (`Validate`, `ValidateForStage`, `ValidKind`), extraction cardinality and -validator adaptation, and model-facing corrective prose. The normalizer imports -this selectable validator package to call `shape.Validate` after trimming prose. -Sibling validators import it for shape preconditions. This works and is permitted -by the current same-family import rules, but a reusable family-domain rule is -owned by one stage-adapter implementation. - -The coupling is more than naming: `Validate` invokes `assess`, which constructs -correction guidance that non-validator callers discard. Changing the adapter's -assessment/guidance implementation therefore also affects an ordinary domain -validity call. The codec separately owns its intrinsic checks, including another -supported-kind predicate. - -The [normalizer's invalid/conflict tests](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer_test.go#L77) -and [shape validator tests](../../../internal/modules/dnd/validate/scenedescriptions/shape/validator_test.go#L13) -show the distinct consumers. The latter deliberately requires exactly one record -only for extraction; the [normalizer tests](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer_test.go#L16) -accept, trim, order, and combine a multi-scene list. - -**Potential remediation:** Move the genuinely reusable scene predicates/checks -into a small family-domain owner, following the existing pure `itemoccurrences`, -`npcoccurrences`, and `enemyevents` pattern. A scene-family helper package is a -reasonable home; tiny predicates can remain with the domain model if that is -clearer. Have the normalizer and validators depend on that owner. Keep native -registration, extraction-only cardinality, assessment classification, and -model-guidance rendering in the validator adapter. - -Start with scenes, where there is an actual cross-stage consumer. Other shape -packages expose similar helpers to sibling validators, but that alone does not -justify moving every check or generating a universal validation package. Extract -additional rules only where they have the same concrete ownership problem. - -Keep intrinsic codec acceptance separate from selectable validation. The codec -and shape validator currently differ, including trimmedness requirements; reusing -the entire strict checklist in the codec would strengthen its contract. Share -identical primitives, such as supported scene kinds, while retaining those -intentional boundary differences. Preserve early shape preconditions used by -other validators and all current validator-override behavior. This is a placement -and cohesion improvement, not a proposal to make optional validators mandatory. - -## BND-004 — Native Capture And Pipeline Scoping Share One Implementation Home - -**Relevant implementation:** -[`pipeline.NativeCapture` and `CaptureNativeRequest`](../../../internal/framework/pipeline/native_capture.go#L19), -[`operationExecution`](../../../internal/framework/pipeline/native_capture.go#L180), -[the producer](../../../internal/framework/pipeline/producer.go), -[the combat semantic validator](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go), -and [the debug recorder](../../../internal/framework/debug/recorder.go#L17). - -**Basis:** Most of `native_capture.go` implements one request's native evidence -lifecycle: hook composition, prepared snapshot ownership, event writes, -result/exchange rendering, and retained capture errors. It requires a native -request and an `EvidenceWriter`, not a runner, lane, or artifact type. Both the -shared producer and an independently executed LLM validator use that API. - -The same file also implements `operationExecution`, which does know `RunInput`, -diagnostic origins, step/lane/chunk identifiers, and the pipeline's evidence path -layout. Request-level capture and pipeline-level operation placement are therefore -mixed inside the orchestration package. The separate `framework/debug` package -owns recording/storage lifecycle, so contributors must find model evidence -behavior under `pipeline` rather than beside its recording concerns. - -**Potential remediation:** Consider extracting the sink-neutral native-capture -component into a focused framework package, retaining pipeline-specific scope -construction in `pipeline`. Alternatively, extend the existing debug package if -native capture can remain cleanly separated from its filesystem recorder and -bundle allocator. Prefer one coherent owner over creating parallel capture APIs. - -This is a low-priority package-cohesion opportunity, not a forbidden import or a -demonstrated runtime failure. Merely moving code into another file in `pipeline` -would clarify the internal seam but not its reusable package ownership. The -extraction is worthwhile only if the resulting API is small and direct; do not -introduce a replacement execution interface or generic telemetry service. - -Keep `contracts.EvidenceWriter` as the supplied sink, physical allocation and run -finalization with the CLI/recorder, and step/lane paths with the pipeline. Preserve -no-I/O-under-admission handling, prepared-value ownership, cause retention, -cancellation, cache-hit evidence, and no duplicate preparation/model calls. Existing -[capture tests](../../../internal/framework/pipeline/native_capture_test.go) and -[validator execution tests](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go) -protect these behaviors. Do not merge capture with invocation accounting or turn -private evidence layout into a durable consumer contract during the move. - -## BND-005 — Registry Reconciliation Lifecycle Ownership Is Repeated By Family Adapters - -**Relevant implementation:** The `Normalize` methods for -[NPC registries](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go#L57), -[item registries](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go#L58), -and [location registries](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go#L58), -together with `framework/semanticreconcile` and `pipeline.RunProducer`. - -**Basis:** The domain-neutral core owns candidate preparation, request-local -mapping, proposal safety, and typed application. The producer owns native -execution and acceptance. Each family normalizer nevertheless independently -implements the same intermediate lifecycle: fixed originals, preparation -dispositions, evidence envelopes, proposal decoding/assessment, current-proposal -bookkeeping, correction construction, and terminal fallback plumbing. - -Domain-specific adapters are appropriate, but this repeated lifecycle has no -single implementation owner. Its genuinely shared responsibilities are mixed -with each family's preprocessing, identity rules, typed consolidation, and -diagnostics. The [equivalence audit's EQ-001](10-equivalence.md#eq-001--registry-normalizers-repeat-one-reconciliation-lifecycle) -provides the supporting family tests and detailed implementation comparison. - -**Potential remediation:** Assign the shared reconciliation lifecycle to a small -typed helper at the existing reconciliation/producer boundary. Continue delegating -native execution and terminal mode handling to the existing producer helpers. -Keep family preprocessing/application/cloning, fallback validity, prompt selection, -and diagnostic policy in the adapters. A neutral result can carry proposal issue -and omission information for family-owned presentation. - -Avoid transferring currency compatibility, NPC canonical-name decisions, -same-name location distinctions, or D&D diagnostic types into the generic core. -Keep every response applied afresh to fixed originals, not accumulated plans. -Choose a dependency direction that keeps the core free of concrete family -imports; a new orchestration framework or record reflection layer is unnecessary. -Retain independent family output tests rather than treating shared lifecycle -coverage as proof that all typed adapters are correct. - -## Boundaries Worth Retaining - -- **Typed contracts versus orchestration:** The contracts package is a useful - shared vocabulary. Framework erasure and registries belong with execution/ - construction, while pure source types remain independent. Do not move all - behavior into `contracts` simply because many packages import it. -- **ConfigKit result versus application semantics:** Native loading, presence, - composition, provenance, and inspection retain their selected owner. Application - normalization and pipeline compatibility are legitimate local responsibilities. -- **Domain family versus stage adapters:** Family-specific packages already share - identities, immutable registry resolution, and occurrence/event helpers across - stages. The stage-oriented directory layout does not itself violate family - ownership or justify wholesale moves to another tree. -- **Shared D&D versus generic framework:** Family-only support may remain under - D&D even if a function looks mechanically generic. Its current consumers and - policy determine a useful boundary, not hypothetical reuse by another domain. -- **Source auxiliaries versus output publication:** `chunkmap` and - `evidencecontext` own logical domain-neutral artifacts; the runner assembles - values, output encoders return logical files, and the CLI publishes them. -- **Storage versus lifetime policy:** `fileio`, `debugbundle`, the debug recorder, - and `artifactcache` have different cohesive roles. Shared atomic writes do not - justify merging cache, output, and requested debug lifecycles or permissions. -- **Native integration versus pure domain logic:** The selected execution APIs - remain native. No private transport, scheduler, configuration parser, or kit - compatibility layer is indicated by these findings. - -The existing `shared` and registrar packages have demonstrated consumers and -bounded roles. This review does not recommend flattening all small packages, -splitting `pipeline` by file count, or reorganizing the entire repository. The -highest-value work is clearer ownership of composition meaning and reusable -family rules, coordinated with the earlier consolidation findings. - -## Validation And Limits - -The production package inventory was obtained offline with: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go list -mod=readonly -json ./... -``` - -Repository-owned import edges were selected from `Imports`, separately from -`TestImports`/`XTestImports`, and checked against the boundaries summarized above. -Generated inventory data remained outside the repository. The inventory and -successful compilation do not by themselves establish conceptual cohesion. - -The following fresh offline tests passed: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/modules ./internal/core/config ./internal/framework/pipeline \ - ./internal/framework/debug ./internal/core/debugbundle ./internal/preflight \ - ./internal/modules/dnd/normalize/scenedescriptions \ - ./internal/modules/dnd/validate/... ./internal/modules/integration -``` - -These include the production AST import guard and its rule fixtures, typed -resolution/preparation, scene shape/normalization, native capture, configurable -validators, debug lifetime, preflight, and assembled handoffs. Successful tests -show that the inspected baseline respects its checked contracts; the ownership -findings do not depend on inventing a test failure. The preceding equivalence -audit also records registry-normalizer tests at unchanged code. - -No third-party source audit, live provider calls, credentials, new tests, production -changes, or architecture-policy changes were required. Broader build-tag/platform -matrices and every possible extension remain outside the claim. Local report links -and the final documentation diff are checked before committing. diff --git a/docs/roadmap/audit/12-deadcode.md b/docs/roadmap/audit/12-deadcode.md deleted file mode 100644 index 87c0faf6..00000000 --- a/docs/roadmap/audit/12-deadcode.md +++ /dev/null @@ -1,225 +0,0 @@ -# Dead Code And Obsolete Functionality Audit - -## Baseline And Method - -Reviewed revision `17a73ca762d0ad3cae36bb314d2a753bd626f62b` on 2026-11-24. -This pass changes only this report. No production code, tests, dependencies, or -configuration were changed or removed. - -The review followed executable/composition-root reachability, registered module -and validator construction, typed interface dispatch, configuration selection, -native producer/cache paths, and retained compatibility behavior. The -[architecture policy](../../policy/architecture.md), -[implemented package map](../../internal/overview.md), current documentation, -tests, and accepted decisions supplied context for distinguishing obsolete code -from optional or intentionally retained behavior. - -Code-graph discovery collected all 4,216 indexed function/method records and -triaged zero-inbound candidates. Repository-wide reference searches and source -inspection then checked actual uses, including function values and generic -instantiations that the graph did not connect. An additional temporary Go -`go/parser`/`go/ast` inventory counted identifiers by package directory, including -test files, and identified private function/type/variable/constant declarations -with only their declaration occurrence. It scanned Go files across build -constraints, excluding `.git`, vendor material, and test fixtures under -`testdata`. The analysis program and its output remained outside the repository. - -This is a conservative source/reachability audit, not whole-program SSA analysis. -Name counts can miss unused declarations when unrelated identifiers share a name; -zero graph callers are particularly unreliable for callbacks and methods. -Candidates were not reported solely on either heuristic. Exported symbols, -reflection/serialization hooks, registration paths, tests, build constraints, -and documented consumer purposes were considered before recommending removal. - -No `deadcode`, `staticcheck`, or `golangci-lint` executable was found on PATH. -Available standard Go tooling was used; no analysis dependency was installed. - -## Current Architecture And Overall Assessment - -The fixed typed workflow remains: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -The CLI composes native libraries, registrars, configuration, physical state, -publication, and reporting. The framework owns preparation, complete assessment, -native producer coordination, ready-job execution, generated handoffs, and -accepted-result reuse. Domain families own transformations, identity, validators, -codecs, references, and prompts. Embedded assets remain content-only. - -The large superseded subsystems described by historical ADRs are not still -running alongside their replacements. Current production paths use native kit -loading/execution/presentation and the unified accepted-result cache rather than -a second configuration parser, private retry engine, checkpoint resume workflow, -or source-only plan cache. The review did not substantiate an entire production -package or supported feature that should be removed. - -Two focused cleanup findings remain. Their impact is maintenance clarity rather -than a measured performance improvement: the uncalled functions and unused -constants already perform no work during a run. - -## DEAD-001 — Three Private Helpers Have No References - -**Priority:** Low. These are confirmed unused declarations, not merely unexecuted -branches in the coverage profile. - -| Declaration | Location | Evidence and current replacement | -| --- | --- | --- | -| `cloneStringMap` | [core/config/config.go:99](../../../internal/core/config/config.go#L99) | Its name occurs only at its declaration in this package, including tests. Runtime configuration now copies pipeline profiles, reference-source maps, and option maps through other helpers; this string-map copier is disconnected. The spell catalog has a separate live helper with the same name and is not included in this finding. | -| `laneReferencesReuseEligible` | [pipeline/handoff.go:50](../../../internal/framework/pipeline/handoff.go#L50) | Its name occurs only at its declaration repository-wide. Current extraction, merge, normalization, and initial lane accounting call `referenceTargetReuseEligible` for the relevant operation, not this aggregate conjunction. | -| `sortValidatorSpecs` | [pipeline/validator_registry.go:342](../../../internal/framework/pipeline/validator_registry.go#L342) | Its name occurs only at its declaration repository-wide. `RegisteredSpecs` traverses already sorted `RegisteredKeys`, so listing does not call or need this extra sorting helper. | - -These are unexported package functions. They are not interface methods, registered -callbacks, generic instantiation targets, or serialization hooks. Searches found -no `go:linkname` use or documented retention requirement for them. The package-local -identifier inventory independently confirmed their declaration-only status. - -**Potential removal:** Delete the three functions and remove an import only if it -then becomes unused. In particular, do not blindly remove `sort` from the validator -registry: other live sorting there must remain. Keep `referenceTargetReuseEligible` -and its operation-specific callers; wiring the dead aggregate back in could change -dependency/reuse granularity rather than simply clean up dead code. - -No replacement abstraction or new test is needed for declaration-only deletion. -Run focused configuration/pipeline tests, retaining existing sorted registry -listing, fallback lineage, and cache-reuse coverage. This work can be combined -with the earlier configuration-copy consolidation, but does not depend on it. - -## DEAD-002 — Obsolete Private Policy Labels Remain Disconnected - -**Priority:** Medium for clarity; no current runtime defect is claimed. - -**Relevant declarations:** The source inventory found 48 private constants with -no identifier use beyond their declarations: - -- 44 constants named `policy` in deterministic D&D validator packages. -- Three `correctionPolicy` constants in the NPC/item/location registry identity - validators. -- `normalizerPolicy` in the scene-description normalizer. - -The complete validator inventory below identifies the affected -`internal/modules/dnd/validate///validator.go` files: - -| Family | Checks containing the unused `policy` constant | -| --- | --- | -| `combatturns` | `invariants`, `shape`, `source_refs`, `source_relatedness` | -| `enemyevents` | `engagements`, `invariants`, `shape`, `source_refs`, `source_relatedness` | -| `itemoccurrences` | `invariants`, `registry`, `shape`, `source_refs`, `source_relatedness` | -| `itemregistry` | `identity`, `shape`, `source_refs`, `source_relatedness` | -| `locationoccurrences` | `invariants`, `registry`, `shape`, `source_refs`, `source_relatedness` | -| `locationregistry` | `identity`, `shape`, `source_refs`, `source_relatedness` | -| `npcoccurrences` | `invariants`, `registry`, `shape`, `source_refs`, `source_relatedness` | -| `npcregistry` | `identity`, `shape`, `source_refs`, `source_relatedness` | -| `scenedescriptions` | `invariants`, `shape`, `source_refs`, `source_relatedness` | -| `spells` | `catalog`, `shape`, `source_refs`, `source_relatedness` | - -Examples include -[combat shape](../../../internal/modules/dnd/validate/combatturns/shape/validator.go#L17), -[item identity and its correction label](../../../internal/modules/dnd/validate/itemregistry/identity/validator.go#L19), -[location identity](../../../internal/modules/dnd/validate/locationregistry/identity/validator.go#L19), -[NPC identity](../../../internal/modules/dnd/validate/npcregistry/identity/validator.go#L19), -and [scene normalization](../../../internal/modules/dnd/normalize/scenedescriptions/normalizer.go#L20). - -**Evidence and obsolescence:** These constants are not returned by current specs, -included in results, used in execution decisions, or consulted by the cache. -Validator registration still uses the live key, execution class, builder, and -option validator; deleting the private labels does not unregister a validator. -The old policy-fingerprint responsibility is superseded by -[ADR-0023](../../adr/0023-unify-accepted-artifact-and-plan-caching.md). -[Current cache construction](../../../internal/framework/pipeline/runner_cache.go) -and [state documentation](../../internal/state.md#prepared-result-reuse) -use the native initial message-content key without policy/version dimensions. - -Keeping these unused version strings suggests that bumping them changes execution, -validation, or reuse. It does not. There is no current documentation describing a -retention purpose for these particular private labels. - -**Potential removal:** Delete the 48 private constants. Retain validator keys, -reason codes, corrective guidance, enums, prompt IDs, schema versions, and actual -domain identity policy constants. In particular, -[`items/identity.Policy`](../../../internal/modules/dnd/items/identity/identity.go#L17) -is included in the hashed identity bytes by `DeriveID`; removing or changing it -would change durable IDs. The unused validator alias to that constant is not the -same thing as the live identity policy itself. - -Do not restore fingerprint interfaces or add policy labels to cache keys merely -to give these constants a use. That would reverse an accepted architecture -decision. Existing validator/normalizer and asset tests are appropriate validation -for the deletion; new tests asserting the absence or count of these labels would -be change detectors, not useful behavioral protection. - -**Related exported surface, not part of the confirmed private deletion:** Six -normalizers (`spells`, `combatturns`, `enemyevents`, `itemoccurrences`, -`npcoccurrences`, `locationoccurrences`) expose `NormalizationPolicy` aliases with -no repository references beyond their declarations. Their private -`normalizationPolicy` strings feed only those aliases. This suggests additional -obsolete metadata surface, but exported declaration-only status is not by itself -proof that an intended integration has no purpose. Review any intended internal -consumer contract before removing those pairs; the confirmed 48-constant cleanup -can proceed independently. Do not include identity-package aliases or live ID -derivation constants in a broad name-based deletion. - -## Candidates Investigated And Retained - -- **Registration callbacks and generic functions:** Option validators, - `parseRequiredRunValue`, `parseConfigurationOverride`, `checkPipelineRunInput`, - `typedCandidateAssessor`, and `exactTypedValue` have real function-value or - generic call sites despite missing incoming graph edges. They are not dead. -- **Once-initialized schema compilation:** `loadAndCompileSchema` in `chunkmap` - and `evidencecontext` is passed as a function value to `sync.Once.Do`. Removing - it on zero direct-call evidence would break codec/schema behavior. -- **Interface and serialization methods:** Codec methods, `ReferenceSlots`, - validator methods, error `Unwrap`, and `MarshalJSON` are used through typed - registrations, interfaces, standard serialization, or error inspection. No - finding follows from a missing named direct call. -- **Explicitly retained compatibility:** The `roster` reference fallback to the - `party` prompt input remains implemented and covered by - [compatibility tests](../../../internal/modules/dnd/chunk/scenes/chunker_test.go#L265). - It is not obsolete merely because the identifier is described as legacy. - Conversely, tests proving rejection of retired controls or ignoring old cache - records do not imply that a legacy loader/cache implementation remains live. -- **Optional modules and paths:** Generic no-op/append modules, explicit - accept/reject validators, semantic scene validation, debug capture, cache modes, - auxiliary artifacts, and operation-time references are supported extension or - configured paths. Default-example selection and low coverage do not determine - their liveness. -- **Exported convenience APIs:** `ValidID`, typed convenience constructors, - registry views, and `SynchronizedDebugRecorder` were not recommended for removal - solely for lacking production call sites. The synchronization implementation - itself is live in `Runner.Run`; its exported wrapper describes use with shared - injected clients/recorders. Narrow API redundancy is not sufficient proof of - obsolescence without checking intended consumers. -- **Earlier duplication findings:** Repeated copying, reconciliation lifecycle, - and duplicate grouping are active code, not dead implementations. The - [equivalence](10-equivalence.md) and [boundary](11-boundaries.md) reports own - their consolidation recommendations; they are not counted again here. - -No additional obsolete configuration option, entire unused package, abandoned -compatibility engine, or unconditional unreachable production branch was confirmed -in the inspected paths. Defensive error handling was not treated as dead merely -because the available tests did not execute it. These are bounded conclusions, -not a claim that every possible unused symbol has been proven absent. - -## Validation And Limits - -Both commands completed successfully with cached dependencies and no live services: - -```sh -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly ./... - -GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ - ./internal/core/config ./internal/framework/pipeline \ - ./internal/modules/dnd/normalize/... ./internal/modules/dnd/validate/... \ - ./internal/modules ./assets -``` - -Vet success does not prove absence of unused private declarations. The temporary -AST inventory is a triage aid rather than an installed static analyzer or a new -repository maintenance tool. References were checked in actual source and tests -before classifying the confirmed findings. No reachability experiment deleted -code or altered a condition, and no API credentials or production inputs were -used. No speedup, binary-size reduction, or exhaustive cross-platform dead-code -result is claimed. - -Report links and the staged documentation diff are checked before committing. diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md deleted file mode 100644 index 007f424a..00000000 --- a/docs/roadmap/audit/catalog.md +++ /dev/null @@ -1,792 +0,0 @@ -# Consolidated Audit Findings - -## Purpose And Baseline - -This catalog consolidates every finding in the ten audit reports in this -directory, reviewed on 2026-11-24 at -`6e98a4e36eb17ce27b682bd7a0ad4b4fa8fdee37`. Their production-code baseline is -`3887d89b763b7040efc866d4a57eb910d8778730`; subsequent commits added the reports -and corrected distribution-policy documentation. The original reports remain -the owners of detailed evidence, counterexamples, qualifications, and validation -results. This document adds prioritization and cross-report consolidation, not -another code audit or an implementation plan. - -The companion [remediation discussion](discussion.md) collects review -recommendations and open choices in discussion order. Accepted decisions there -qualify proposed remediation; finding statuses here track implementation. -The completed Audit Remediation Roadmap and implementation plan are retained in -Git history; they consolidated the accepted target with CAT-033 deferred. -The [Core And Integration API Roadmap](../core-integration-api.md) established -the core/integration boundary. The reassessment below distinguishes its completed -work from the remaining audit remediation. - -The **45 original finding entries** reduce to **19 outstanding catalog entries -and fifteen resolved entries**. Repeated responsibility findings are -merged. Regression gaps are attached to the defects they protect rather than -counted as additional runtime bugs. In particular, TEST-001, TEST-002, and -TEST-004 each cover several distinct defects; TEST-003's native-fixture oracle -and application-boundary assertions are included together in CAT-007. - -The inventory below includes every audit report present. No reports numbered -07 or 09 exist in this directory; this catalog makes no claim about omitted -audit topics. - -## Architecture Assessment - -The reports consistently describe a coherent typed pipeline: - -```text -input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output -``` - -The CLI composes native kits, registrars, physical state, publication, and -reporting. The framework owns typed preparation, complete candidate assessment, -native producer coordination, a bounded ready-job pool, generated handoffs, and -accepted-result reuse. Artifact families own interpretation, identity, -transformations, validation, codecs, and prompts. Assets remain content-only. -ConfigKit, PromptKit, CommandKit, and ReleaseKit retain their selected native -responsibilities. See the [architecture policy](../../policy/architecture.md) -and [internal overview](../../internal/overview.md) for canonical boundaries. - -The audits found no checked import-direction violation, confirmed data race, -deadlock, or ordinary resource-handle leak. They did find numerical edge defects, -failure-path diagnostic loss, avoidable transcript-scale work and retention, -and repeated application-level responsibilities. Passing tests and those bounded -conclusions do not prove every composition correct. No replacement workflow, -configuration, retry, or resource-management framework is indicated. - -## Priority And Status - -Entries below are ordered by recommended attention: accepted-input correctness -and high-impact ordinary-run efficiency first; failure visibility and narrow -boundary defects next; high-leverage consolidation before smaller cleanup. -Ordering considers reachability and practical impact, not just ease of fixing. -Original P2/P3 ratings and relative refactoring priorities are retained for -context; they are not one universal severity scale. No audit establishes a P1 -incident or a measured end-to-end production speedup. - -CAT-001, CAT-002, CAT-003, CAT-004, CAT-005, CAT-007, CAT-011, CAT-012, CAT-013, CAT-015, -CAT-016, CAT-024, CAT-027, CAT-032, and CAT-034 are resolved; -the other entries remain outstanding. The original reports and their baseline -observations are historical. -"Refactoring" denotes a maintenance opportunity, not a confirmed runtime -failure. Related entries -may share files without representing the same underlying issue; they should be -coordinated rather than silently treated as duplicates. - -**Migration overlap:** Lazy [operation evidence](../../../internal/framework/pipeline/operation.go) -and guarded run-wide projections resolve CAT-003. Core operation -ownership and the [internal guides](../../internal/modules.md) clarify portions -of CAT-014/017/018/022/025, without completing their broader layout, -copying, runner, writer-obligation, or package-cohesion work. CAT-006/008/009 -and CAT-023 remain separate lifetime, failure-diagnostic, and CLI concerns. - -## Prioritized Findings - -### CAT-001 — Overflow In An Accepted Generic Chunk Size - -**Assessment:** Reproduced correctness defect; original P2. - -**Status:** Resolved. Chunk planning uses overflow-safe capacity and endpoint -arithmetic; option-decoding and planning regressions cover maximum size and -ordinary overlap. - -**Sources:** [Correctness / Finding 1](01-correctness.md#finding-1-a-valid-large-generic-chunk-size-causes-a-panic), -[TEST-001](08-testing.md#test-001--accepted-numeric-boundaries-lack-regression-cases). - -A valid small document with `max_units = math.MaxInt` passes option decoding but -panics in ceiling-division preallocation. Use overflow-safe arithmetic or omit -the optional preallocation; inspect endpoint addition at the same boundary. -Add small supported-option regressions for the extreme value and normal overlap. -Preserve the accepted option domain rather than adding an arbitrary maximum. - -### CAT-002 — Tiny Negative Timestamps Pass Input Validation - -**Assessment:** Reproduced input-contract defect; original P2, extreme-value case. - -**Status:** Resolved. Validation checks the exact rational sign, and parser -regressions cover both endpoints, tiny positive values, zero, and exact ordering. - -**Sources:** [Correctness / Finding 2](01-correctness.md#finding-2-negative-timestamp-underflow-bypasses-non-negativity-validation), -[TEST-001](08-testing.md#test-001--accepted-numeric-boundaries-lack-regression-cases). - -A timestamp such as `-1e-1000` underflows to floating-point negative zero and -bypasses the sign check; the subsequently parsed exact rational is negative. -Check its exact sign while retaining current finiteness and precision handling. -Cover tiny negative/positive values, zero/negative zero, and precise ordering. -No new timestamp-magnitude restriction is needed. - -### CAT-003 — Disabled Capture Still Builds Expensive Evidence - -**Assessment:** Source-established resource-efficiency weakness; original P2. - -**Status:** Resolved. Guards precede source, input, chunk-plan and deferred chunk -outcome, lane, merge, normalize, output, and evidence-summary projections. The -operation input/result, candidate assessment, cache observation, and native -evaluation capture paths were inspected and already guard their projections. -Mandatory artifact encoding remains unconditional; focused tests cover lazy -evaluation and enabled, cached, fallback, and failing capture paths. - -**Source:** [RES-001](05-resources.md#res-001--disabled-capture-still-constructs-large-evidence-payloads). - -Ordinary runs construct text/base64, chunk, artifact, and output envelopes before -the disabled writer returns. Some continuations construct all-chunk payloads -concurrently. Guard expensive debug-only construction at its owning boundary, -including deferred chunk outcomes. Keep required artifact encoding outside those -guards and preserve enabled-capture content and failure behavior. This addresses -unnecessary transient allocation, not a proven permanent leak. - -### CAT-004 — Sparse Citation Resolution Scans The Whole Transcript Per Record - -**Assessment:** Source-established algorithmic opportunity; original P2. - -**Status:** Resolved. Position intervals are validated, sorted, and coalesced -before only their union is visited, with literal source-order regression cases. - -**Source:** [EFF-002](02-efficiency.md#eff-002--build-cited-text-from-coalesced-ranges-not-a-document-wide-bitmap). - -`CitationResolver.CitedText` allocates document-sized buffers and scans every -unit even for empty or single-unit citations. Resolve, sort, and coalesce ranges, -then visit only the selected units. Preserve errors, source order, single inclusion -of overlapping evidence, and newline joining. Protect empty/invalid, overlapping, -disjoint, sparse, and non-monotonic-ID cases. The improvement removes the document -dimension from each sparse lookup; it is not a measured overall runtime claim. - -### CAT-005 — Every Extraction Job Rebuilds The Whole-Source Index - -**Assessment:** Source-established algorithmic opportunity; original P2. - -**Status:** Resolved. A run-owned index is shared by extraction and cache -decoding; all ten D&D extraction paths use it, with local fallback for standalone -calls. Tests cover run isolation, changed source layouts, cache reuse, and -representative supplied-index extraction. No production speedup was measured. - -**Source:** [EFF-001](02-efficiency.md#eff-001--reuse-the-full-source-position-index-across-extraction-jobs). - -Ten D&D extractors build the same document-position map per applicable chunk -invocation, even before accepted-result lookup. Share one immutable run/source -index, retaining local construction for standalone callers. This reduces the -indexing component from `Theta(J * D)` to `O(D + J)` for J jobs and D units. -Preserve whole-document resolution, current-source cache checks, and isolation -between sources/runs; a chunk-only or process-global index is not equivalent. - -### CAT-006 — Completed Intermediate Values Remain Reachable Too Long - -**Assessment:** Source-established resource-lifetime weakness; original P2. - -**Status:** Resolved. Returned results retain no private working state. Ordered -assembly releases extraction reorder maps, completed continuations release lane -values while siblings run, and drained failures drop undeliverable values after -diagnostics are retained. Normalized artifacts remain through their consumers. -Controlled lifetime, integration, and pipeline race checks pass. - -**Source:** [RES-002](05-resources.md#res-002--intermediate-results-outlive-their-consumers). - -Lane reorder maps and extraction values survive completed continuation while -slow siblings run. Returned `RunOutput` also retains private normalized bytes, -reuse state, and diagnostic accumulators after public results are assembled. -Drop owner references after their final consumers, on success and failure. -Do not mutate shared backing storage or retire values before handoff, evidence, -and output encoding finish. Coordinate diagnostic lifetime changes with CAT-008 -and CAT-009 so cleanup does not erase completed-work information. - -### CAT-007 — Native Failed-Validation Handling Loses Meaning And Its Tests Miss It - -**Status:** Resolved. [Core usability checking](../../../internal/framework/pipeline/native_result.go) -retains completed-validation details and upstream causes; the [producer tests](../../../internal/framework/pipeline/producer_test.go), -[combat validator tests](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go), -and [reconciliation fixture](../../../internal/framework/semanticreconcile/engine_test.go) -exercise the respective boundaries. The original observation below is historical. - -**Assessment:** Static classification/detail defect with duplicated handling; -original ERR-001 P3, TEST-003 P2, EQ-005 low refactoring priority. - -**Sources:** [ERR-001](06-error-handling.md#err-001--completed-native-validation-failures-lose-detail-and-acquire-an-operational-error-category), -[EQ-005](10-equivalence.md#eq-005--producers-and-an-llm-validator-duplicate-the-native-usability-gate), -[TEST-003](08-testing.md#test-003--native-failure-assertions-have-an-incomplete-or-incorrect-oracle). - -At the audit baseline the producer and combat semantic validator refused unusable content, -but discarded native validation details and manufactured `promptkit.ErrValidation`, -conflating a completed failed content check with an operational validation error. -Give the small usability check one framework owner; distinguish missing results, -failed checks, and actual native Go errors. Preserve producer disposition and -validator unavailability as separate caller outcomes. - -Correct the validator test that pins the wrong sentinel and cover retained -details at both boundaries. Also tighten the separate reconciliation fixture -that currently accepts any error after one provider call: require its intended -nil-error/failed-result outcome. These are related test obligations, not proof -that changing the runtime helper alone fixes the suite's oracle. Do not add -semantic retries or enlarge native repair budgets. - -### CAT-008 — Completed Chunk Diagnostics Disappear On Later Lane Failure - -**Status:** Resolved. Coordinator-owned completed groups survive lane failure -and cancellation, including sparse out-of-order results and available diagnostics -returned with errors. Ordered assembly avoids duplicate extraction publication; -regressions also cover merge diagnostics on normalize failure and incomplete-lane -publication boundaries. Focused pipeline and race checks pass. - -**Assessment:** Static composed failure-path defect; original P3. - -**Sources:** [ERR-002](06-error-handling.md#err-002--successful-extraction-diagnostics-disappear-when-the-lane-never-continues), -[TEST-004](08-testing.md#test-004--diagnostics-tests-miss-failure-path-composition). - -Successful chunk diagnostics reach output only through completed continuation. -A later failure can therefore erase earlier genuine warnings, even with one -worker. After draining started work, gather completed diagnostics independently -of artifact eligibility in canonical lane/chunk order, without double counting. -Handle sparse result indices explicitly. Add same-lane failure and controlled -out-of-order coverage; incomplete lanes must still produce no artifacts/handoffs. - -### CAT-009 — Failure Finalization Hides Diagnostic Aggregation Errors - -**Status:** Resolved. Diagnostic finalization runs once, retains the valid prefix, -and joins aggregation errors with execution, cancellation, or capture causes. -Regressions exercise genuine occurrence overflow on failure and success paths, -including prevention of output encoding. The prescribed package checks pass. - -**Assessment:** Static composed failure-path defect; original P3. - -**Sources:** [ERR-003](06-error-handling.md#err-003--failure-output-finalization-suppresses-aggregation-errors), -[TEST-004](08-testing.md#test-004--diagnostics-tests-miss-failure-path-composition). - -Individually valid groups can exceed aggregate bounds, but `failOutput` ignores -finalization errors and loses the available prefix. The nominal success path can -repeat the failed aggregation. Retain the primary and aggregation causes, expose -bounded available diagnostics as incomplete failure information, and avoid the -duplicate pass. Test the combined failure, preserving existing warning bounds -and failure semantics rather than silently truncating warnings into success. - -**Subsequent decision:** [Discussion Item 1](discussion.md#1-diagnostic-capacity-and-pipeline-success) -selects removal of diagnostic group-count caps while retaining per-group sampling -and genuine failure causes. That accepted design replaces the warning-bound -preservation recommendation above. Group caps and truncation are removed, and -the selected single failure-finalization boundary preserves genuine causes. - -### CAT-010 — Process Signals Do Not Reach Cooperative Cancellation - -**Status:** Resolved. The executable routes the first SIGINT/SIGTERM to its -application context and restores ordinary signal handling during cleanup. -Offline subprocess tests observe provider cancellation, joined work, terminal -evidence, no retry/fallback, and subsequent-signal termination with held delivery. -Embedded callers retain their contexts; no cleanup deadline is introduced. - -**Assessment:** Static executable integration weakness; original P3. - -**Source:** [CONC-001](04-concurrency.md#conc-001--process-signals-bypass-cooperative-cancellation-and-cleanup). - -The executable supplies `context.Background`; supported process signals terminate -it without entering existing cancellation/drain/capture-finalization paths. -Connect signals at the executable boundary with idiomatic context handling and -deliberately choose repeated-signal behavior. Preserve caller-owned contexts for -embedded use. A local fake-backend subprocess regression can protect the path; -there was no signal-injection reproduction in the audit. Cooperative cleanup -does not imply SIGKILL handling or a new shutdown deadline guarantee. - -**Subsequent decision:** [Discussion Item 3](discussion.md#3-process-signals-and-cooperative-cancellation) -selects cooperative cancellation on the first SIGINT/SIGTERM and ordinary -termination on a subsequent signal, with no application shutdown deadline. -Signal handling stays at the executable boundary. - -### CAT-011 — Extreme Accepted Context Radius Can Empty Evidence - -**Assessment:** Reproduced latent internal-API defect; original P3. - -**Status:** Resolved. Context expansion is bounded by source distance before -arithmetic; regressions cover the maximum radius, cited flags, and material limit. - -**Sources:** [Correctness / Finding 3](01-correctness.md#finding-3-context-radius-addition-can-overflow-and-omit-all-evidence), -[TEST-001](08-testing.md#test-001--accepted-numeric-boundaries-lack-regression-cases). - -`semanticreconcile.Prepare` accepts a maximum integer radius but overflows while -expanding an interval, returning ready material with empty windows. Current -production normalizers use radius 2, so deployed defaults do not reach this case. -Clamp by remaining source distance before adding; retain non-negative radii and -the existing material byte budget. Test extreme/normal radii on tiny sources. - -### CAT-012 — Delimiter-Based Generated-Producer Keys Can Collide - -**Assessment:** Static correctness counterexample, not executed; original P3. - -**Status:** Resolved. Resolution uses structured producer keys, with real -resolution tests for colliding identifiers and both matching and mismatched kinds. - -**Sources:** [BUG-001](03-complexity.md#bug-001--generated-producer-keys-can-collide), -[TEST-002](08-testing.md#test-002--identity-and-metadata-fixtures-omit-valid-representational-edge-cases). - -Resolver keys made from `step + NUL + lane` alias distinct accepted identifier -pairs containing NUL. Validation can then check a generated reference against -the wrong producer's kind. Reuse the struct-key representation already used by -runtime handoff. Test colliding string encodings with different producer kinds; -do not introduce an identifier-character prohibition. No wrong runtime handoff -was demonstrated. - -### CAT-013 — Metadata Cycle Detection Rejects An Acyclic Slice View - -**Assessment:** Static correctness counterexample, not executed; original P3. - -**Status:** Resolved. Slice view length participates in active recursion identity; -tests cover finite shared views, detached copies, and genuine cycles. - -**Sources:** [BUG-002](03-complexity.md#bug-002--cycle-detection-confuses-a-slice-view-with-a-cycle), -[TEST-002](08-testing.md#test-002--identity-and-metadata-fixtures-omit-valid-representational-edge-cases). - -Tracking slice recursion by type/backing pointer confuses a shorter shared-prefix -view with the active outer slice. Include the traversed visible view in tracking, -handling empty views appropriately. Retain real cycle rejection, detached concrete -containers, and useful paths. Cover finite prefix sharing and true cycles. This -affects programmatic metadata, not ordinary decoded JSON; banning shared backing -arrays or replacing copying with a JSON round trip would change the contract. - -### CAT-014 — Pipeline Composition Has Three Independent Interpreters - -**Status:** Resolved. Configuration validation, resolution, and CLI reference -expansion share pipeline-owned layout and target selection. Independent tests -cover CLI-only required references, variants, precedence, generated protection, -selection errors before reads, and configuration/resolver structure. Full -resolution decomposition remains separately tracked under CAT-018. - -**Assessment:** High-leverage ownership/refactoring opportunity; original high. - -**Sources:** [CPLX-003](03-complexity.md#cplx-003--three-packages-independently-interpret-pipeline-structure), -[EQ-004](10-equivalence.md#eq-004--configuration-runtime-resolution-and-cli-reference-selection-reinterpret-composition), -[BND-001](11-boundaries.md#bnd-001--pipeline-composition-meaning-has-three-partial-owners). - -Configuration validation, runtime resolution, and CLI reference expansion repeat -step/lane layout and selected-module/default/variant interpretation. Give pure -layout and catalog-aware selected-target inventory a pipeline owner. Keep raw -ConfigKit presence/provenance checks, CLI grammar/precedence, and full compatibility -checks at their distinct boundaries. Inventory must work before CLI bindings -satisfy required references; calling full resolution early is not a substitute. -Retain independent expected selections in config, resolver, and CLI tests. - -**Subsequent decision:** [Discussion Item 4](discussion.md#4-one-owner-for-pipeline-interpretation-and-pure-copying) -accepts shared layout/selection operations and pure copying in the existing -pipeline package, with loading, CLI binding, and complete resolution remaining -distinct phases. This also governs CAT-017/CAT-018; resolution decomposition -remains pending under CAT-018. - -### CAT-015 — Producer Lifecycle Depends On Coupled Closure State - -**Status:** Resolved for the selected operation lifecycle. [Core execution](../../../internal/framework/pipeline/operation.go) -and [native continuation](../../../internal/framework/pipeline/operation_native.go) -own evaluation replacement and disposition; [operation tests](../../../internal/framework/pipeline/operation_native_test.go) -cover current-candidate invalidation. The former `RunProducer` path is removed. - -**Assessment:** High-leverage local maintainability opportunity; original high. - -**Source:** [CPLX-001](03-complexity.md#cplx-001--producer-execution-has-too-much-coupled-mutable-state). - -At the audit baseline, preparation, cache lookup, capture, candidate interpretation/ -assessment, native continuation, and disposition shared mutable closure state in `RunProducer`. -Use small private phase/state results to make candidate invalidation and exits -explicit. Preserve native execution/history ownership, final-turn assessment, -cache hits, cancellation precedence, capture errors, and strict/permissive -outcomes. Coordinate CAT-007's usability fix, but do not conflate that small -defect with the wider readability refactor or create a new retry engine. - -### CAT-016 — Three Registry Normalizers Repeat Reconciliation Lifecycle Glue - -**Status:** Resolved for the shared reconciliation lifecycle. The neutral -[operation facility](../../../internal/framework/semanticreconcile/operation.go) -and its [lifecycle tests](../../../internal/framework/semanticreconcile/operation_test.go) -own fixed preparation and final evaluation; the [NPC](../../../internal/modules/dnd/normalize/npcregistry/normalizer.go), -[item](../../../internal/modules/dnd/normalize/itemregistry/normalizer.go), and -[location](../../../internal/modules/dnd/normalize/locationregistry/normalizer.go) -adapters retain independent family policy. The former duplication is historical. - -**Assessment:** Shared lifecycle/refactoring opportunity; original high/medium. - -**Sources:** [CPLX-004](03-complexity.md#cplx-004--semantic-registry-normalizers-repeat-a-stateful-lifecycle), -[EQ-001](10-equivalence.md#eq-001--registry-normalizers-repeat-one-reconciliation-lifecycle), -[BND-005](11-boundaries.md#bnd-005--registry-reconciliation-lifecycle-ownership-is-repeated-by-family-adapters). - -At the audit baseline, NPC, item, and location normalizers duplicated fixed-original preparation, -proposal/evidence bookkeeping, correction, and fallback glue around the shared -core and producer. Share only that demonstrated typed lifecycle, returning current -proposal/omission information explicitly. Keep domain identity, currency guards, -same-name location distinctions, prompts, and diagnostics with families. The core -must not import concrete families; D&D-local adaptation can translate neutral -results. Preserve fresh application of each proposal and independent family tests. - -### CAT-017 — Pipeline Value Copying Has Multiple Owners And Mixed Semantics - -**Status:** Resolved. Pipeline-owned pure profile and binding copies are reused -by configuration and framework callers; trimming remains explicit in decoding -and resolution. Mutation tests cover supported nested containers, references, -validators, control pointers, whitespace, and nil/empty values, including -effective configuration isolation. The prescribed package checks pass. - -**Assessment:** Ownership/refactoring opportunity; original medium. - -**Sources:** [CPLX-007](03-complexity.md#cplx-007--copying-pipeline-values-has-multiple-owners-and-mixed-semantics), -[EQ-003](10-equivalence.md#eq-003--configuration-and-pipeline-boundaries-independently-copy-the-same-values), -[BND-002](11-boundaries.md#bnd-002--pipeline-value-ownership-is-implemented-outside-its-type-owner). - -Configuration and framework code separately clone pipeline-owned trees, while -one clone also trims names and option switches support different containers. -Provide pure copying at the type owner and make normalization explicit. Inventory -supported representations before unifying behavior; retain omission/empty/zero -distinctions and mutation-isolation tests at both boundaries. Do not build an -arbitrary reflection copier or merge this with source-metadata validation. - -### CAT-018 — Pipeline Resolution Mixes Unrelated Responsibilities - -**Status:** Resolved. Pipeline values/wire handling, shared copies, effective -binding selection, reference resolution, and generated dependencies have -cohesive owners. Per-binding generated checks use structured producer keys; -source normalization is separate from overlay precedence. Existing independent -composition, type, reference, and digest checks and full verification pass. - -**Assessment:** Local decomposition opportunity; original medium. - -**Source:** [CPLX-002](03-complexity.md#cplx-002--pipeline-resolution-mixes-too-many-responsibilities-in-one-file). - -Profile types, wire handling, reference normalization/precedence, generated -dependencies, validator selection, copying, and digesting share a large file and -nested routines. Extract cohesive same-package helpers/files and per-binding -checks, not merely shorter files. Coordinate CAT-014/CAT-017 to avoid neater -duplicate implementations. Preserve typed compatibility, capabilities, configured -order, generated restrictions, and useful error context; no new package split -or stage interpreter is established by this finding. - -### CAT-019 — Sorting Recomputes Invariant Evidence Keys - -**Status:** Resolved. NPC, location, item, and enemy-event normalizers prepare -invariant sort keys once per owned record. Enemy invariant checks use canonical -comparisons only after evidence-order validation; defensive comparators and -genuine evidence tie comparisons remain. Literal non-monotonic, tied, invalid, -duplicate, and validator tests pass across the affected families. - -**Assessment:** Local algorithmic opportunity; original P3. - -**Source:** [EFF-003](02-efficiency.md#eff-003--derive-invariant-sort-keys-once-per-normalized-record). - -Occurrence/enemy comparators repeatedly scan evidence for earliest position; -enemy tie-breakers also recanonicalize already-canonical evidence. Prepare stable -scalar/evidence keys once per owned normalized record, following the combat -normalizer's existing pattern. Preserve exact tie/invalid-reference order and -general defensive comparators for unproven inputs. The earliest-key component -can lose a repeated reference-scan factor; genuine citation tie comparison may -still be linear. Protect literal domain outputs, not comparator call counts. - -### CAT-020 — Reusable Scene Rules Are Owned By A Selectable Validator Adapter - -**Status:** Resolved. Family-owned checks report field facts for normalization -and sibling validators; the shape adapter retains cardinality, classification, -and guidance. The codec shares only the identical kind predicate. Literal tests -cover nil/empty, kind, whitespace, references, and cardinality, and the specified -scene family, codec, normalizer, and validator suites pass. - -**Assessment:** Family cohesion/refactoring opportunity; original medium. - -**Source:** [BND-003](11-boundaries.md#bnd-003--scene-domain-rules-live-inside-a-selectable-validator-package). - -Scene normalization imports shape validation that also builds unused corrective -prose; sibling validators and the codec need some of the same pure predicates. -Move genuinely reusable scene checks to a small family-domain owner, leaving -adapter registration, extraction-only cardinality, assessment, and guidance in -the validator. Share only identical codec primitives: codec acceptance currently -differs from strict selectable validation. Do not make optional checks mandatory -or move every family's checks without a demonstrated cross-stage need. - -### CAT-021 — Exact-Duplicate Group Bookkeeping Is Reimplemented - -**Status:** Resolved. NPC/location occurrences, combat turns, and spell casts -share pure position grouping while retaining family-owned identity, eligibility, -output, and original-index diagnostics. Spell no-change and empty representations -remain local; item occurrences deliberately retain their bucket-plus-exact-equality -implementation. Independent normalizer and grouping tests pass. - -**Assessment:** Pure shared-helper opportunity; original medium. - -**Source:** [EQ-002](10-equivalence.md#eq-002--exact-duplicate-collapse-repeats-stable-group-bookkeeping). - -NPC/location occurrences and combat turns repeat keep masks, first representatives, -group lookup, removed original indices, and retained traversal. Share that pure -bookkeeping with family-supplied eligibility/keys; include spells only if its -nil/allocation behavior stays local. Item occurrences' bucket-plus-exact-equality -guard must remain intact, even if that variant stays separate. Preserve family -ordering, identity, cloning, and independent expected-output tests; this is not -one universal normalizer or permission to combine evidence ranges. - -### CAT-022 — Runner Stage Flow Is Obscured By Evidence And Output Assembly - -**Status:** Resolved. The runner coordinates source preparation, chunk planning, -ordered steps, single diagnostic finalization, and logical output explicitly; -private collaborators own parsing, chunk-map construction, and output/evidence -assembly. Existing pipeline, integration, CLI, and full verification checks pass. - -**Assessment:** Local maintainability opportunity; original medium. - -**Source:** [CPLX-005](03-complexity.md#cplx-005--runner-stages-are-obscured-by-debug-and-output-assembly). - -`Runner.Run` alternates stage control with large evidence and auxiliary-output -construction. Extract cohesive private source, chunk/map, and output phases so -the coordinator exposes order and failure boundaries. Keep physical publication -in the CLI and preserve cancellation, fallback eligibility, diagnostics, ownership, -and required-capture errors. Coordinate CAT-003/CAT-006/CAT-009, but their defects -remain independently verifiable; avoid a generic string-named stage dispatcher. - -### CAT-023 — CLI Declaration And Invocation Lifecycle Are Entangled - -**Status:** Resolved. The native declaration creates a per-invocation owner for -execution, capture finalization, publication state, and reporting. Regressions -cover combined causes and published versus unpublished locations; existing CLI -and integration checks and affected CLI race checks pass. - -**Assessment:** Local maintainability opportunity; original medium. - -**Source:** [CPLX-006](03-complexity.md#cplx-006--the-run-command-owns-declaration-and-the-whole-invocation-lifecycle). - -The run command embeds loading, selection, preparation, identity/capture, -execution, publication, and terminal presentation with captured mutable state. -Keep the native declaration small and give invocation/finalization a cohesive -private owner. Preserve one configuration/engine, supplied-value semantics, -capture-before-preparation, cause retention, and distinct execution/publication/ -report-delivery outcomes. This is CLI lifecycle work, separate from CAT-022; -do not introduce another command framework or result envelope. - -### CAT-024 — Enabled Debug Capture Repeats Immutable Full-Source Inputs - -**Assessment:** Capacity/convenience design opportunity; original P3; requires -deliberate review of the existing evidence representation. - -**Status:** Resolved. The selected evidence sink receives one original and one -parsed source record, with bundle-root references in run and operation inputs. -Tests cover explicit/debug/distinct sinks, multiple jobs, cache hits, and source -write and parse failures. [ADR-0027](../../adr/0027-share-whole-source-capture-evidence.md) -records the selected representation. - -**Source:** [RES-003](05-resources.md#res-003--enabled-capture-repeats-the-full-source-for-every-extraction-job). - -Each extraction operation serializes the full source again, multiplying debug -disk usage by chunk/lane count, even on cache hits. Consider bundle-local reuse -of immutable source/references plus per-operation selections. ADR-0024 permits -duplication and current tests expect self-contained inputs, so this is not a -breached size promise or a preapproved removal. Account for direct EvidenceWriter -consumers and keep actual inputs recoverable, native evidence complete, and -required-capture failures visible. No silent truncation, quotas, or deletion. - -**Subsequent decision:** [Discussion Item 2](discussion.md#2-convenient-debug-evidence-and-repeated-full-source-capture) -selects sharing original input and complete parsed source once per run through -the operation capture destination. Operation-specific inputs, selected references, -and convenient native evidence remain directly inspectable. General deduplication -is out of scope. - -### CAT-025 — Extension Concurrency And Capture Obligations Are Implicit - -**Assessment:** Documentation/extension-contract clarity gap; original P3; -no current default implementation was found to race. - -**Status:** Resolved. Interface comments and internals describe actual sharing, -borrowed lifetimes, callback and writer obligations, and the worker join boundary. -Contract, pipeline, integration, and relevant race tests pass. - -**Source:** [CONC-002](04-concurrency.md#conc-002--extension-and-explicit-capture-concurrency-obligations-are-implicit). - -Prepared extractors/validators and codecs are reused across concurrent chunk -jobs; source is read-only. Explicit capture writers are not serialized merely -because each operation's NativeCapture has a mutex. Document actual shared-instance, -callback, and operation-lifetime behavior in canonical internals and interface -comments, linking upstream-owned client rules. Prefer clarifying existing -caller-side writer obligations; serial-only writer support would be a separate -choice, not a reason to add locks everywhere or promise universal thread safety. - -### CAT-026 — Prompt Tests Pin Authored English Instead Of Behavior - -**Assessment:** Test-maintenance weakness; original P3. - -**Status:** Resolved. Prompt tests exercise supplied inputs, native contracts, -shared asset placement, cache hints, and follow-up routing without pinning prose. -The targeted asset, reconciliation, and extraction suites pass. - -**Source:** [TEST-005](08-testing.md#test-005--prompt-tests-contain-prose-change-detectors). - -Several asset/module tests require literal prose fragments; composition tests -also use production wording as message-location markers. Remove those incidental -assertions, use test-controlled supplied-content markers, and consolidate genuinely -duplicate checks at the asset owner. Retain native preparation, input/schema/ -default selection, required-property compatibility, cache hints, and follow-up -binding contracts. Do not replace word checks with hashes/snapshots or remove -all string assertions; authored prompt quality still needs review. - -### CAT-027 — Concurrency Tests Rely On Sleep Or Unbounded Handshakes - -**Assessment:** Static reliability/diagnosability risk; original P3; -no failure was observed in the audit's repeated runs. - -**Status:** Resolved. Controlled gates establish continuation overlap and reverse -completion; bounded handshakes cancel and join work on failure. Repeated focused -tests and affected race tests pass. - -**Source:** [TEST-007](08-testing.md#test-007--concurrency-tests-need-controlled-overlap-and-better-failure-bounds). - -A continuation test uses a five-millisecond sleep to induce required overlap; -reverse-completion receives can wait until the global test timeout after an -early error. Use explicit start/release gates with bounded, cancellation-safe -failure handling and join started work. Keep meaningful worker-limit/order -assertions. Test watchdogs do not imply a new runtime timeout guarantee or need -for a general deadline framework. - -### CAT-028 — Maintained-Example Tests Mix Independent Contracts - -**Assessment:** Test readability/refactoring opportunity; original low. - -**Status:** Resolved. Loading, composition, inheritance, and listing have focused -checks; the parent is resolved independently. Repeated focused and CLI tests pass. - -**Source:** [CPLX-008](03-complexity.md#cplx-008--maintained-example-testing-combines-several-independent-concerns). - -One nested test combines loading, transcript handling, composition, generated -references, inheritance, and listing. Its mutable parent map introduces fixture -order dependence. Build explicit resolved fixtures and separate focused checks, -obtaining the parent directly for comparison. Retain useful integration coverage -and local expectations; do not replace it with an assertion DSL or new snapshots. - -### CAT-029 — Run-ID Test Freezes A Private Representation - -**Assessment:** Incidental test restriction; original P3, small cleanup. - -**Status:** Resolved. Uniqueness and safety remain covered without a private -format regex; allocation, partial-write, and versioned session checks are retained. - -**Source:** [TEST-006](08-testing.md#test-006--run-id-test-freezes-an-incidental-private-format). - -Remove the exact timestamp/hex-width run-ID regex while retaining uniqueness, -path safety, allocation/collision, and partial-write protection. The separately -versioned session-ID vector protects an expressly selected cross-run routing -contract and should remain. This is not a blanket reason to remove exact-value -assertions. - -### CAT-030 — Disconnected Policy Labels Suggest Nonexistent Behavior - -**Assessment:** Confirmed private dead metadata; original medium for clarity, -not runtime impact. - -**Status:** Resolved. Removed the unused validator, correction, and scene -normalizer labels. The spell, combat-turn, enemy-event, item-occurrence, -NPC-occurrence, and location-occurrence normalization aliases and their private -strings were also removed: all are internal, have no callers or documented -consumer contract, and do not participate in cache or identity. Live domain -identity policy bytes, validator keys, reasons, schemas, and guidance remain. -Focused D&D tests and repository vet pass. - -**Source:** [DEAD-002](12-deadcode.md#dead-002--obsolete-private-policy-labels-remain-disconnected). - -Remove the 48 confirmed unused private constants: 44 deterministic-validator -`policy` labels, three registry-identity `correctionPolicy` labels, and the scene -`normalizerPolicy`. They do not affect validation or cache identity. Retain live -domain identity constants, keys, reason codes, schemas, and guidance. In -particular, identity policy bytes affect durable IDs. Do not resurrect cache -fingerprints to justify unused labels. - -The separately reviewed internal aliases have the disposition recorded above; -no absence/count change-detector test was added. - -### CAT-031 — Three Private Helpers Are Unused - -**Assessment:** Confirmed dead declarations; original low; no runtime speedup -is implied by deleting code that already does not execute. - -**Status:** Resolved. The three disconnected helpers were removed. The live -spell catalog copier and scoped reuse eligibility remain; focused tests and vet pass. - -**Source:** [DEAD-001](12-deadcode.md#dead-001--three-private-helpers-have-no-references). - -Delete config's `cloneStringMap`, pipeline's `laneReferencesReuseEligible`, and -`sortValidatorSpecs`, cleaning only imports made unused. Keep the live spell -helper with the same name, operation-specific reference eligibility, and other -registry sorting. Do not wire the obsolete aggregate back into runtime behavior. -Existing focused tests suffice; declaration-only deletion needs no new test. - -### CAT-032 — Reusable Native Capture And Pipeline Scoping Share A Home - -**Subsequent decision:** [Discussion Item 9](discussion.md#9-cleanup-scope-and-optional-improvements) -selects package extraction as required ownership remediation, independent of -performance benefit. - -**Assessment:** Low-priority package-cohesion opportunity, not an import violation. - -**Status:** Resolved. Native request evidence is owned by framework/capture; -pipeline retains operation scoping and CLI retains physical capture lifecycle. - -**Source:** [BND-004](11-boundaries.md#bnd-004--native-capture-and-pipeline-scoping-share-one-implementation-home). - -Request-level native evidence lifecycle is reusable by producers and validators, -but lives with pipeline-specific operation paths. Consider one small sink-neutral -framework owner, or a cohesive extension of debug, leaving scope paths in pipeline -and physical lifecycle in CLI/recorder. Proceed only if the resulting API remains -direct. Preserve prepared ownership, cause retention, admission behavior, and -cache-hit evidence; add no telemetry service or replacement execution interface. - -### CAT-033 — Token Matching Has Avoidable Worst-Case Repeated Work - -**Disposition:** Deferred under -[discussion Item 9](discussion.md#9-cleanup-scope-and-optional-improvements) -until representative workloads justify the optimization; not resolved by a code fix. - -**Assessment:** Low-practical-priority algorithmic opportunity; original P3. - -**Source:** [EFF-004](02-efficiency.md#eff-004--avoid-restarting-token-sequence-matching-at-every-position). - -Restarting a token-sequence match at each source position is quadratic for long -repeated-prefix queries, though ordinary short entity names are effectively -linear. Consider a small prefix-function/KMP matcher after higher-impact work. -Keep exact consecutive-token semantics, Unicode normalization, punctuation, -empty-query behavior, and token boundaries; compare with an independent simple -reference matcher. No fuzzy search dependency or name-length cap is indicated. - -## Other Resolved Finding - -### CAT-034 — Distribution Architecture Described A Retired Source-Only Workflow - -**Status:** Resolved; original P3; no remaining remediation. - -**Source:** [DOC-001](02-efficiency.md#doc-001--distribution-architecture-still-describes-the-retired-source-only-workflow). - -Commit `65ce8f7fe55b91244c4114ea95fb87494a1449b9` corrected the architecture's -distribution summary and linked to the release-policy owner. Current wording -describes ReleaseKit source publication and hosted binary/checksum delivery, -retaining Linux support, best-effort macOS development, and no Windows support. -The source audit records the earlier observation; it should not be reopened as -an outstanding defect or treated as approval for additional targets/release gates. - -## Original-Finding Coverage - -Every original finding is mapped below. Multiple source IDs in one catalog entry -are corroborating observations or attached test obligations, not extra runtime -defects. Conversely, a source test finding can map to several catalog entries -because its fixtures omit several independent behaviors. Each catalog entry above -links directly to every corresponding original finding. - -| Audit document | Original finding → catalog entry | -| --- | --- | -| [01-correctness.md](01-correctness.md) | Finding 1 → CAT-001; Finding 2 → CAT-002; Finding 3 → CAT-011 | -| [02-efficiency.md](02-efficiency.md) | EFF-001 → CAT-005; EFF-002 → CAT-004; EFF-003 → CAT-019; EFF-004 → CAT-033; DOC-001 → CAT-034 (resolved) | -| [03-complexity.md](03-complexity.md) | CPLX-001 → CAT-015; CPLX-002 → CAT-018; CPLX-003 → CAT-014; CPLX-004 → CAT-016; CPLX-005 → CAT-022; CPLX-006 → CAT-023; CPLX-007 → CAT-017; CPLX-008 → CAT-028; BUG-001 → CAT-012; BUG-002 → CAT-013 | -| [04-concurrency.md](04-concurrency.md) | CONC-001 → CAT-010; CONC-002 → CAT-025 | -| [05-resources.md](05-resources.md) | RES-001 → CAT-003; RES-002 → CAT-006; RES-003 → CAT-024 | -| [06-error-handling.md](06-error-handling.md) | ERR-001 → CAT-007; ERR-002 → CAT-008; ERR-003 → CAT-009 | -| [08-testing.md](08-testing.md) | TEST-001 → CAT-001/CAT-002/CAT-011; TEST-002 → CAT-012/CAT-013; TEST-003 → CAT-007; TEST-004 → CAT-008/CAT-009; TEST-005 → CAT-026; TEST-006 → CAT-029; TEST-007 → CAT-027 | -| [10-equivalence.md](10-equivalence.md) | EQ-001 → CAT-016; EQ-002 → CAT-021; EQ-003 → CAT-017; EQ-004 → CAT-014; EQ-005 → CAT-007 | -| [11-boundaries.md](11-boundaries.md) | BND-001 → CAT-014; BND-002 → CAT-017; BND-003 → CAT-020; BND-004 → CAT-032; BND-005 → CAT-016 | -| [12-deadcode.md](12-deadcode.md) | DEAD-001 → CAT-031; DEAD-002 → CAT-030 | - -## Review Limits And Validation - -This consolidation read all ten reports and verified the resolved policy change -against Git history/current wording. It did not rerun the application suite, -perform inference, measure production performance, or independently reproduce -every earlier finding. The source reports record their own methods: reproduced -numeric defects, static counterexamples, passing offline/race checks, and the -testing audit's 89.2% cross-package statement coverage. Those results apply to -the audited baseline, not to a new validation run performed for this catalog. - -Catalog validation checks original-finding coverage, consecutive catalog IDs, -local link/heading targets, and whitespace. No production code, tests, policies, -or original audit reports are changed by this consolidation. Proposed cleanup -does not add contracts, security restrictions, complexity thresholds, required -benchmarks, or new release gates. Any later implementation should retain the -original reports' qualifications and focused behavioral protection. diff --git a/docs/roadmap/audit/discussion.md b/docs/roadmap/audit/discussion.md deleted file mode 100644 index 66303256..00000000 --- a/docs/roadmap/audit/discussion.md +++ /dev/null @@ -1,420 +0,0 @@ -# Audit Remediation Discussion - -## Purpose And Status - -This document consolidates the review recommendations for the -[audit catalog](catalog.md) into an ordered discussion for maintainers. The -catalog owns the finding inventory and prioritization; its linked audit reports -own detailed evidence and qualifications. This document preserves discussion -decisions and rationale. The completed Audit Remediation Roadmap and -implementation plan are retained in Git history, recording the consolidated -target and worker stages. - -Prepared on 2026-11-24 against catalog revision -`5a0650250686353cf34fbbbf0e780b04f60e70c1`. All discussion decisions are now -accepted with the recorded conditional/deferred scope. Acceptance selects the -intended design; implementation remains pending unless explicitly recorded otherwise. - -The review supports the existing typed pipeline and native-kit architecture. -The strongest opportunities are removing repeated interpretation, unnecessary -work, and retained state. No replacement workflow, retry, configuration, or -resource-management framework is indicated. Smaller files and more helpers are -useful only when they make ownership and callers clearer. - -Items 1–10 are settled. Items 1–3 contain explicit behavior choices; -Items 4–8 principally need bounded implementation analysis. Items 9–10 settle -scope and sequencing. This discussion order is not a mandatory implementation -order, and independent fixes need not wait for unrelated refactors. - -## 1. Diagnostic Capacity And Pipeline Success - -**Findings:** CAT-009; related CAT-008 and CAT-022. -**Status:** Accepted; implementation pending. - -CAT-009 identifies a real loss of aggregation errors and available diagnostics. -Its suggested remediation also preserves the existing policy that exceeding the -warning-group bound can fail an otherwise successful pipeline. These are separate -issues: fixing error loss does not require endorsing that policy indefinitely. - -**Accepted decisions:** - -- Diagnostic volume alone does not fail a pipeline. Artifact acceptance continues - to follow the configured validation and strict/permissive decisions. -- Retain every distinct diagnostic group. Remove the local producer group-count - cap and both final warning/non-warning group-count caps. Remove collection-level - truncation and omission bookkeeping used solely to enforce those caps; do not - replace them with configurable limits. -- Retain grouping, occurrence counts, and representative sampling within each - group, initially keeping the existing three-example behavior and omitted-sample - counts. Distinct-group retention does not require storing every occurrence. -- Preserve diagnostics from completed operations when later execution fails, - independently of lane continuation. Incomplete lanes remain ineligible for - artifact publication. -- Preserve genuine diagnostic-contract, arithmetic-overflow, reporting, and - requested-capture failures. When finalization fails, retain the primary and - finalization causes alongside available valid diagnostics. The error can - explain incompleteness; no new report schema or durable sidecar is needed. -- Keep the small completion report, fallback disclosure, and native CommandKit - presentation unchanged. - -This removes capacity-driven acceptance policy and collection-overflow paths while -preserving useful summaries. Memory grows with distinct groups; grouping and -representative samples still prevent repeated occurrences from requiring one -retained message each. No exhaustive diagnostic ledger is introduced. - -Removing group caps eliminates the ordinary capacity-overflow case in CAT-009, -but genuine finalization failures must still retain their causes and available -diagnostics. CAT-008's completed-work diagnostic loss remains a separate fix. - -Existing bounded aggregation is retained by -[ADR-0015](../../adr/0015-separate-process-warnings-from-quality-diagnostics.md) -and [ADR-0024](../../adr/0024-publish-artifacts-with-native-reports-and-debug-evidence.md). -Reconcile this accepted change with those architectural decisions and canonical -documentation during implementation, preserving accepted ADR bodies. - -**Decision:** Accepted as above. No open policy choices remain in this item. - -## 2. Convenient Debug Evidence And Repeated Full-Source Capture - -**Findings:** CAT-024; distinguish the independent CAT-003 fix. -**Status:** Accepted; implementation pending. - -Repeating a full source for every chunk and lane has a credible capacity cost, -including on cache hits. Self-contained operation evidence also serves the -deliberate convenience goal recorded in -[ADR-0024](../../adr/0024-publish-artifacts-with-native-reports-and-debug-evidence.md). - -Choose the most convenient representation, not automatically the most concise, -complete, or deduplicated one. Share whole-source material while keeping -operation-specific evidence directly readable. - -**Accepted decisions:** - -- Capture the original input and complete parsed source once per run. Operation - inputs clearly reference that shared material through logical bundle paths. -- Keep the particular chunk, operation selection, selected reference contents, - and incoming artifacts directly in operation evidence initially. -- Preserve convenient native representations of prepared messages, responses, - and exchanges, including useful duplication. Reading the actual prepared - request must not require reconstructing it from fragments. -- Accept bundle-level completeness for whole-source context. Copying the complete - bundle preserves that context; an isolated operation directory need not be - independently portable with the entire transcript. -- Write shared source material through the same capture destination that receives - operation evidence. Explicit `EvidenceWriter` consumers receive both the shared - records and operation records, without assuming a CLI filesystem root or files - written to another sink. References use logical paths, not a requirement for - filesystem symlinks or a reconstruction tool. -- Limit sharing to whole-source material for this remediation. Do not introduce - general content deduplication, additional identities, or configurable capture - modes. Reconsider other repeated material only when concrete usage warrants it. - -Preserve actual inputs and available native evidence, secret-aware omissions, -and requested-capture failure behavior. No silent truncation, quotas, automatic -deletion, or new scrubbing machinery is proposed. CAT-003 can independently guard -expensive evidence construction when capture is disabled without changing any -enabled-capture representation. - -Reconcile the selected representation with ADR-0024 and current operation-input -tests during implementation; private debug filenames remain implementation details. - -**Decision:** Accepted as above. No open representation choices remain in this item. - -## 3. Process Signals And Cooperative Cancellation - -**Finding:** CAT-010. -**Status:** Accepted; implementation pending. - -**Accepted decisions:** - -- The first SIGINT or SIGTERM requests cooperative cancellation through the - existing invocation context, allowing dispatch to stop, native requests to - cancel, started jobs to drain, and ordinary failure/capture finalization to run. -- A subsequent signal permits ordinary process termination rather than being - swallowed while cleanup proceeds. That signal may interrupt finalization; - a completed debug bundle is not guaranteed after forced termination. -- Introduce no application shutdown deadline or timeout configuration. Operators - and supervisors retain control over forced termination. -- Install signal handling only at the executable boundary. Embedded callers - retain context ownership; application invocation does not install process-wide - signal handlers on their behalf. -- Cancellation remains cancellation: no permissive fallback, model retry, or - successful completion claim. Retain existing cache entries, published files, - and available debug evidence under the existing lifecycle rules. - -Implement a small standard-library signal adapter around the existing invocation. -A focused subprocess test with a local fake backend should verify cancellation -and available terminal capture evidence. No new shutdown subsystem, SIGKILL -handling, or guarantees for collaborators that ignore cancellation are introduced. - -**Decision:** Accepted as above. No open behavior choices remain in this item. - -## 4. One Owner For Pipeline Interpretation And Pure Copying - -**Findings:** CAT-014, CAT-017, CAT-018; coordinate CAT-012 where files overlap. -**Status:** Accepted; implementation pending. - -Centralize pipeline meaning and pure copying in the existing `pipeline` package -while retaining distinct loading, CLI binding, and complete-resolution phases. -Preserve current configuration and CLI behavior. - -**Accepted decisions:** - -- Provide small shared operations for catalog-independent structural layout and - catalog-aware selected-target inventory. Layout determines ordered steps/lanes - and their structural identities; inventory selects modules/defaults/variants - and discovers reference slots without requiring those slots to be populated. -- Reuse that interpretation and selection logic in complete resolution. The CLI - must be able to discover selected reference slots, apply its bindings, and only - then check completeness. Do not route this through a full resolver with a - partial/allow-missing mode. -- Keep loading, imports, inheritance, source presence, and provenance with - ConfigKit and its application integration. Keep CLI selector parsing and - precedence with the CLI. Complete binding, type-compatibility, and generated - dependency checks remain with pipeline resolution/preparation. -- Put pure copying of pipeline-owned values beside their types. Copying preserves - values; trimming and default selection are explicit interpretation/resolution - operations. Preserve omission, explicit-empty, explicit-zero, and detached - ownership behavior. -- Inventory supported mutable option containers before consolidating copy - implementations. Retain necessary independent values at caller/extension - boundaries, but remove redundant copies where ownership makes them unnecessary. - Do not replace those boundaries with a universal immutability convention. -- Decompose resolution around these owners in the existing package and types, - using cohesive helpers/files as useful. No new configuration model, general - pipeline interpreter, or reflection-based copier is selected. - -Exact helper names and file placement remain implementation choices. Demonstrate -the shared operations through representative callers before expanding the change, -and retain independent selection and mutation-isolation tests at the relevant -boundaries. The generated-key correctness fix does not depend on completing this -broader consolidation. - -**Decision:** Accepted as above. Remaining work is implementation design and verification. - -## 5. Producer State And Shared Reconciliation Lifecycle - -**Findings:** CAT-015 and CAT-016; coordinate CAT-007. -**Status:** Implemented for the selected core/integration boundary; see -[ADR-0026](../../adr/0026-core-owned-operation-preparation-and-execution.md). - -The discussion selected a clear core/integration boundary, core ownership of as -much demonstrated shared lifecycle responsibility as practical, and a clean, -flexible API that future integration authors can understand without reading core -execution internals. Improving private producer state alone does not satisfy -that target. Internal integration interfaces may change to achieve it. - -The [Core And Integration API Roadmap](../core-integration-api.md) now owns the -targeted end state, accepted API decisions, migration work, and verification. -That initiative implemented the selected lifecycle and the catalog records the -reassessment. Remaining audit remediation is separate. Items 1–4 remain -accepted; later discussion items are not silently accepted by this change. - -CAT-007's native usability/error-detail correction was implemented with that -roadmap. Producer disposition and validator unavailability remain distinct; -no new structural repair loop or budget is selected. - -**Decision:** Accepted direction and API choices; implementation details and status -are maintained in the linked roadmap and current internal guides. - -## 6. Finalization, Completed Diagnostics, And Intermediate Lifetimes - -**Findings:** CAT-006, CAT-008, CAT-009, CAT-022; coordinate CAT-023 at the CLI boundary. -**Status:** Accepted direction; implementation pending. Apply Item 1's accepted -diagnostic policy. - -Design diagnostic collection and lifetime reduction together. Completed work's -diagnostics must survive a later failure before its intermediate values are -released. Diagnostic availability must not depend on whether an incomplete lane -became eligible for continuation or publication. - -Use private working state and one clear runner finalization boundary for success, -failure, and cancellation. Keep execution accumulators separate from the returned -logical result, collecting completed-operation diagnostics independently of -artifact publication eligibility. Release owner references after their last -consumers; do not clear shared backing storage or discard information still -needed for handoffs, evidence, or encoding. Exact private types and helper -boundaries remain implementation choices. - -Preserve stable diagnostic order without double counting, primary and relevant -finalization causes, and existing cancellation precedence. Do not repeat failed -aggregation. Keep incomplete-lane artifacts ineligible for publication. - -The runner and CLI have different lifecycle responsibilities. Simplify each -locally: runner phase control and logical results; CLI configuration, capture, -physical publication, and terminal presentation. Preserve distinct execution, -publication, and report-delivery outcomes without a new command framework or -result envelope. Related defects remain independently testable even when their -implementation shares a finalization path. - -**Decision:** Accepted as above. Remaining work is implementation design and -verification; the catalog findings remain outstanding until implemented. - -## 7. Shared Domain Rules And Exact-Duplicate Bookkeeping - -**Findings:** CAT-020 and CAT-021; coordinate CAT-019 where normalization changes overlap. -**Status:** Accepted direction and scope; implementation pending. - -Place reusable scene checks with a small scene-family domain owner, allowing tiny -predicates alongside domain types where that is clearer. Normalizers and validators -reuse these checks; selectable validator assessment, extraction-specific -cardinality, and corrective prose remain adapter-owned. Codec acceptance and -optional shape validation differ, so the codec shares only primitives that already -match its contract. Preserve existing acceptance and validator-override behavior. - -Introduce a small pure duplicate-grouping helper returning retained positions and -duplicate groups. Start with NPC occurrences, location occurrences, and combat -turns. Families supply eligibility and identity keys and retain ownership of -ordering, cloning, original-input-index mapping, and diagnostic messages. Include -spells if its existing nil/allocation behavior fits cleanly. Leave item occurrences -separate initially, preserving its bucket-plus-exact-equality check; accommodating -that variant is not a prerequisite for sharing the straightforward cases. - -Review representative callers and independent expected outputs before expanding -the shared surface. No universal normalizer or repository-wide movement of every -shape check is selected. Calculate invariant sort keys once per normalized record, -following the existing combat normalizer's approach. This local CAT-019 improvement -can proceed independently of duplicate grouping. Preserve existing ordering, ties, -and invalid-reference behavior without introducing a general sorting framework. - -**Decision:** All three recommendations accepted as above. Remaining work is -implementation and verification; the catalog findings remain outstanding until -implemented. - -## 8. Extension And Capture Concurrency Obligations - -**Finding:** CAT-025. -**Status:** Accepted documentation scope; implementation pending. - -Document the actual shared-instance, immutable-source, callback, and operation -lifetime model in canonical internals and interface comments. Current default -implementations were not found to race; this is clarity for extension authors -and direct framework consumers. Prepared extractors, extract validators, and -shared codecs can receive overlapping calls. Keep per-operation mutable state -local or operation-owned and synchronize intentionally shared mutable state. -Source data shared by operations remains read-only. Describe the call pattern by -interface and stage, including merge/normalization following completed extraction -for a lane, without implying every method is invoked concurrently. The runner -waits for dispatched operations, not arbitrary extension-created background work; -extensions must manage that work's lifetime relative to borrowed collaborators. - -State the existing caller-side obligation for custom capture writers shared across -concurrent operations to support concurrent calls, and point to the standard -synchronized recorder. Defer an optional synchronized writer wrapper until a -concrete serial-only consumer needs it. If introduced later, all users of the -underlying writer must share the same wrapper; separate operation mutexes do not -serialize one shared sink. No automatic core serialization, per-job module -construction, or general addition of locks is selected. - -Explain where Notarius shares native clients, observers, and callbacks, linking -to upstream-owned concurrency contracts rather than restating their guarantees. - -**Decision:** All three recommendations accepted as above, including deferral of -the optional writer wrapper. Remaining work is documentation and verification; -CAT-025 remains outstanding until that work is implemented. - -## 9. Cleanup Scope And Optional Improvements - -**Findings:** CAT-026 through CAT-033. -**Status:** Accepted scope; implementation pending, with CAT-033 deferred. - -- Remove the confirmed private dead helpers and obsolete policy labels - (CAT-030/CAT-031) after checking they remain unused, preserving live identity - bytes and behavior. No new tests of declaration counts or absence are needed. -- Give the six exported `NormalizationPolicy` aliases a short intended-use check. - Remove them if they have no supported purpose; defer any whose purpose remains - unclear rather than expanding the review into a compatibility project. - They reside under `internal/`; capitalization alone does not establish a - supported external API. Do not turn unused internal metadata removal into a - broad compatibility project, or recreate cache fingerprints to give it a use. -- Remove incidental prompt-prose/run-ID assertions, use controlled scheduling in - concurrency tests, and separate order-dependent example fixtures - (CAT-026–CAT-029). Include these explicitly in remediation scope. Use - test-controlled content and bounded, cancellation-safe scheduling gates. - Preserve genuine schema, routing, ownership, worker-limit, ordering, safe - allocation, uniqueness, and maintained-example contracts, including the distinct - session-ID contract. Do not replace fragile assertions with snapshots or add - tests for every private helper. -- Carry out native-capture package extraction (CAT-032) as required ownership - remediation, independent of performance benefit. A focused framework capture - package owns native request preparation hooks, result/exchange evidence, and - capture-error retention, using native PromptKit types and the existing - `EvidenceWriter`. Core operations and independently executing validators use - that same implementation. Pipeline retains operation identity and step/lane/ - chunk evidence paths; CLI/recorder retain filesystem allocation and run-level - capture lifecycle/finalization. Prefer a dedicated capture package over expanding - the storage-oriented debug package; exact naming remains an implementation - choice. Preserve cancellation, error causes, prepared-value ownership, admission - behavior, and existing evidence behavior without duplicate preparation or model - calls. No replacement execution API, telemetry service, or synchronized-writer - wrapper is included. -- Defer a KMP token matcher (CAT-033) until representative workloads demonstrate - worthwhile benefit. Ordinary short entity names make the current matcher - effectively linear. Keep existing exact token-matching semantics; no benchmark - gate or name-length restriction is selected. - -Deferral or declining a refactoring opportunity can be a valid outcome. Closing -every catalog entry through code changes is not itself the goal. - -**Decision:** Cleanup, test improvements, and capture-package extraction accepted -as above; token-matching optimization deferred. Catalog implementation statuses -remain outstanding until the selected work lands; deferral is not a code fix. - -## 10. Remediation Sequence And Verification - -**Scope:** Incorporate the preceding decisions into a focused implementation plan. -**Status:** Accepted planning and verification direction. Formal roadmap prepared; -detailed implementation planning and execution remain pending. - -Recommended approach: - -1. Fix narrow correctness defects with focused regressions: CAT-001/CAT-002 and - CAT-011–CAT-013. Native classification/test-oracle handling in CAT-007 is resolved. - Preserve supported inputs rather than imposing new restrictions. Reproduce - static counterexamples at their real boundaries when implementing the fixes. -2. Address ordinary-run source costs in CAT-004/CAT-005: avoid full-document scans - for sparse citations and share an immutable source index at run/source lifetime. - Preserve standalone use and current-source cache checks without a process-global - cache or new cache-key dimensions. -3. Extract native capture and address disabled-capture costs and whole-source - representation (CAT-003/CAT-024/CAT-032). Keep the package move distinguishable - from behavior changes. -4. Implement private working state, completed-diagnostic retention, group-cap - removal, and clear runner/CLI finalization. Add signal cancellation against that - lifecycle; shorten intermediate lifetimes after their final consumers are clear. -5. Consolidate composition/copying and shared domain mechanics, including local - sort-key preparation, as independently reviewable units. The selected core - producer/reconciliation migration is already complete. -6. Finish concurrency documentation, obsolete declarations, test cleanup, and - final acceptance. Improve fragile tests before relying on them during earlier - stages and update interface documentation alongside affected code. The token - matcher remains deferred. - -Use one focused implementation plan linking worker stages to catalog findings and -accepted scope, with dependencies, observable completion criteria, verification, -and documentation updates. Keep finding status in the catalog and rationale here; -do not copy the audit reports into the plan. The retired formal roadmap, -available in Git history, defined the end state for that handoff. - -This is an ordering guide, not a serial dependency chain. Cheap independent fixes -can proceed without waiting for broader discussion. Practical reachability and -maintenance benefit matter alongside severity; exotic boundary cases can be easy -to correct without displacing ordinary-run improvements. - -Use focused behavioral regressions and existing independent family/boundary tests. -Run broader offline checks and relevant race tests according to -[testing policy](../../policy/testing.md) when shared behavior changes. Do not -duplicate the upstream libraries' test suites or turn audit coverage/complexity -metrics into new targets. Source analysis establishes avoidable work, but measured -end-to-end speedups should be claimed only if measured. - -Update canonical behavior documentation when implementation lands. Record any -significant changed architectural decision without rewriting accepted ADR bodies. -Keep the catalog's evidence and qualifications linked rather than duplicating -all ten reports in an implementation plan. CAT-007, CAT-015, CAT-016, and -CAT-034 are resolved and require no further remediation within their stated scope. - -**Decision:** All three recommendations accepted: one focused implementation plan, -the dependency-aware sequence above, and boundary-focused verification followed -by repository-wide acceptance. No additional broad audit or new test threshold is -required. Detailed stages remain the planning agent's responsibility. diff --git a/docs/roadmap/core-integration-api.md b/docs/roadmap/core-integration-api.md deleted file mode 100644 index f200593c..00000000 --- a/docs/roadmap/core-integration-api.md +++ /dev/null @@ -1,356 +0,0 @@ -# Core And Integration API Roadmap - -## Status And Purpose - -**Status:** Implemented and reviewed for the selected core/integration boundary. -Final acceptance and review remediation records are retained in Git history. - -This roadmap records the completed prerequisite to the subsequent audit -remediation, whose completed planning documents are retained in Git history. It -develops -[discussion Item 5](audit/discussion.md#5-producer-state-and-shared-reconciliation-lifecycle) -into an integration-author API initiative, rather than a private-helper cleanup. -The target design below is retained as the migration record; its baseline section -describes the pre-migration state. - -The retired implementation plan records ordered stages and stage-specific -validation in Git history. This document owns scope, target behavior, and the -accepted design decisions. - -The selected goals are: - -1. Make the boundary between Notarius core and integrations clear and well defined. -2. Put as much demonstrated shared responsibility as practical in core, with a - clean, flexible interface for integration-owned behavior. -3. Make the API understandable and usable by future integration authors without - requiring them to reconstruct the execution lifecycle from core internals. - -Here, **core** means the framework contracts and orchestration, including shared -producer and reconciliation facilities. **Integrations** means Notarius artifact -families and their stage modules, validators, codecs, and domain behavior. It does -not mean replacing the adopted kits' APIs with another abstraction. - -The API is intended for multiple domains. The next anticipated integrations are -an email processor and an NWS Forecast Discussion text processor. Existing D&D -modules supply migration evidence, not the definition of what an integration or -chunk must be. - -## Current Baseline - -Reviewed baseline: `f0ba5cce843182e0f5f3eaa6577110a087cf1422`. -Production code is unchanged from the catalog's audited baseline -`3887d89b763b7040efc866d4a57eb910d8778730`; intervening changes are documentation. -[go.mod](../../go.mod) selects Go 1.27.0, PromptKit v0.25.0, ConfigKit v1.4.0, -CommandKit v0.8.0, ckconfig v0.11.0, and ckprompt v0.12.0. No dependency upgrade is -required by this plan; assess any concrete upstream gap if implementation finds one. - -The fixed typed pipeline and native-kit responsibilities are already implemented. -[Module Internals](../internal/modules.md) and -[Pipeline Internals](../internal/pipeline.md) describe current authoring and execution. - -| Current surface | Responsibility and friction | -| --- | --- | -| [Typed stage requests](../../internal/framework/contracts/typed_pipeline.go) and [producer contracts](../../internal/framework/contracts/producer.go) | Requests expose `ProducerOperation[T]`, including assessor, controls, cache binding, execution options, and reuse eligibility. Authors carry framework plumbing through their module implementation. | -| [RunProducer](../../internal/framework/pipeline/producer.go) | Shares native execution, assessment, corrections, caching, and disposition, but its closures coordinate candidate, guidance, failure, acceptance, and capture state through mutable outer variables. | -| [Producer outcome helpers](../../internal/framework/pipeline/producer_outcome.go) | Integrations choose between `RunProducer`, `AssessProducer`, and `FinishProducerFailure` for model work, no-model answers, and preparation outcomes. Correct lifecycle composition remains part of the authoring recipe. | -| [Spell extraction](../../internal/modules/dnd/extract/spells/extractor.go) and [scene planning](../../internal/modules/dnd/chunk/scenes/chunker.go) | Modules prepare domain/native inputs, supply interpretation/correction/fallback closures, invoke the producer, and assemble typed outcomes. Scene planning also demonstrates correctable interpretation without a usable candidate. | -| [NPC](../../internal/modules/dnd/normalize/npcregistry/normalizer.go), [item](../../internal/modules/dnd/normalize/itemregistry/normalizer.go), and [location](../../internal/modules/dnd/normalize/locationregistry/normalizer.go) reconciliation | Each repeats fixed-original preparation, proposal/evidence tracking, no-model and limit dispositions, correction construction, fallback bookkeeping, and result assembly around existing shared mechanisms. | -| [Semantic reconciliation](../../internal/framework/semanticreconcile/preparation.go) | Already provides neutral candidate preparation, proposal safety, request construction, and typed application. The missing sharing is primarily the lifecycle connecting those facilities to production. | -| [Combat semantic validation](../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go) | Executes one native assessment directly. It shares the native-usability classification defect with the producer, but is not a producer correction loop. | - -The production migration inventory starts with ten D&D extractors (spells, -combat turns, enemy events, scene descriptions, and NPC/item/location registries -and occurrences), D&D scene planning, and the three registry normalizers. -Combat/enemy extraction and registry reconciliation have no-model paths that must -be exercised. Deterministic stage completion and typed registration/preparation -also participate where they connect to the changed contracts. Confirm the caller -inventory during implementation rather than treating these counts as invariants. - -## Targeted End State - -### Domain-Neutral Operations And Chunks - -Core contracts describe sources, source units, chunks, typed artifacts, and -operation outcomes. A scene is a D&D interpretation of a chunk, not a core chunk -type that other integrations must imitate. Transcript speakers/timestamps, combat -annotations, entity registries, and D&D identity rules belong to integrations -where applicable; ordinary core operations do not require those concepts. - -The existing [source types](../../internal/core/source/source.go) already carry -generic units, ranges, content, and metadata. Evaluate their fit through the new -API rather than introducing a parallel source model preemptively. Source parsing, -unit selection, chunk meaning, and domain metadata remain integration concerns; -core owns generic plan materialization and orchestration. Neither a particular -D&D chunk prompt nor scene-specific annotations define the authoring contract. - -Use these anticipated scenarios alongside production D&D callers when evaluating -the API shape: - -| Scenario | Design question | -| --- | --- | -| Email processing | Can an integration prepare message content and its domain metadata, choose useful processing units/chunks, and produce typed results without transcript or scene conventions? | -| NWS Forecast Discussion text processing | Can an integration process document text using its own meaningful sections or other chunk boundaries and domain-specific findings, without entity-registry reconciliation being required? | - -These are design scenarios, not settled input formats, extraction schemas, or -chunking policies. A section/paragraph or whole-document chunk can illustrate an -API walkthrough without prescribing either integration's final behavior. Support -deterministic and model-assisted preparation where appropriate through the same -core lifecycle; specialized reconciliation remains optional. - -Develop small API sketches or synthetic fixtures to expose domain assumptions. -Implementing the email and NWS processors, network ingestion, or their complete -domain contracts is not part of this migration. If a walkthrough exposes a real -source/chunk contract mismatch, identify and resolve that specific boundary rather -than forcing the integration into scene terminology or promising arbitrary source -topologies without evidence. - -### Ownership - -| Responsibility | Target owner | -| --- | --- | -| Transport, credentials, native structural validation/repair, transient retries, exchanges, continuation iteration, and backend admission | PromptKit, through its native types and APIs | -| Configuration loading/composition and command parsing/rendering | ConfigKit, CommandKit, and their existing application integrations | -| Operation lifecycle, configured assessment, native continuation coordination, cache use, standard evidence, cancellation, and terminal mode application | Notarius core | -| Domain input preparation, prompt selection/native input construction, result interpretation, deterministic identity, and domain transformations | Integration | -| Validation meaning and actionable repair instructions | Detecting integration validator or interpretation rule; core collects and applies configured assessment | -| When supported fallback is selected and how it affects outcomes/reuse | Core, applying resolved policy | -| What constitutes a valid fallback and how to construct it | Integration, with existing intrinsic/downstream checks | -| Fixed-original and current-proposal reconciliation bookkeeping | Shared core reconciliation facility | -| Entity compatibility, typed proposal application, family diagnostics, and domain-specific reconciliation evidence | Integration, using family-shared helpers where appropriate | -| Physical publication, invocation debug allocation/finalization, and terminal reporting | Existing CLI/recorder boundary | - -Core should own the complete shared lifecycle, not merely offer utilities that -authors must arrange correctly. That does not require hiding native PromptKit -requests/results or moving domain rules into the framework. - -### Core-Driven Typed Operations - -Core calls the integration's preparation function and receives a small typed -operation definition. It supplies either a deterministic candidate for assessment -or a native initial request and the domain behavior needed to interpret results, -construct corrections, and produce a supported fallback. Core consumes that -operation and owns assessment, execution, continuation, caching, standard evidence, -and terminal disposition. - -Use ordinary Go data and functions or small interfaces for optional behavior. -Distinguish meaningful preparation outcomes rather than building a large bag of -unrelated optional fields. The operation definition is not a serializable workflow -language or another configuration system. Exact type names and method signatures -remain implementation choices within this accepted control flow. - -An ordinary integration no longer selects assessment/cache collaborators, chooses -terminal helpers, invokes an injected executor on each branch, tracks native -capture finalization, or maintains framework acceptance state. Required inputs and -optional capabilities should be clear from the author-facing types and examples. -Standalone callers can use the same core executor. - -Support the existing preparation outcomes: a deterministic answer, model work, an -existing preparation-limit disposition, or an ordinary failure. Moving their -handling into core must not turn arbitrary preparation errors into permissive -recovery. A model-backed module may legitimately complete without a model call; -deterministic work needs no manufactured prompt or cache key. - -Changing internal stage interfaces and callers is part of the migration where -needed. Retaining their current signatures or lifecycle plumbing is not the goal. -This does not promise a versioned public SDK, dynamic plugin loading, or universal -backwards compatibility. - -### Explicit Candidate Evaluation Results - -Interpretation/application returns an explicit evaluation containing the usable -candidate, if any, and its associated guidance, diagnostics, and applicable -proposal-application information. Interpretation can return actionable correction -guidance before it has a usable candidate. Core owns subsequent configured -assessment and acceptance; supplying a candidate is not an approval claim. - -Core replaces the evaluation as a unit and invalidates the previous candidate -when selecting another execution, so a failed correction cannot revive stale -candidate state. Candidate-associated findings must not survive accidentally in -separate mutable integration variables. Earlier evaluations may remain in debug -evidence without describing the final artifact. - -Keep reconciliation-specific typed issues and omission information in the -reconciliation facility or family adapter. Ordinary extraction does not acquire -registry-specific fields. Families retain domain translation and diagnostic -meaning. Fixed prepared inputs, lookup tables, and per-operation domain helpers -remain legitimate; explicit evaluation results do not require all integration -code to be pure or stateless. This decision does not expand cache payloads or the -completion report. - -### Convenient Native Correction Requests - -Provide a direct convenience path for the common case: the integration selects a -native correction prompt and specifies how ordered guidance is supplied. Core -collects applicable guidance and carries resolved execution selections; -PromptKit carries conversation history. Existing native prompt declarations own -message templates and schemas. - -Also accept a native request builder for specialized domain correction material. -The convenience path reduces to the same request-building mechanism as that -custom path, with one execution/continuation lifecycle. It does not impose a -universal guidance variable name, prompt schema, correction policy, D&D template, -or scene-specific response shape. - -Exercise both authoring forms with a simple extractor and a richer correction -case. Exact field names and helper placement remain implementation details; the -selected API supports the convenient default and native customization. - -### Reconciliation As A Focused Facility - -Build a typed reconciliation facility on the same producer lifecycle. It owns -fixed preparation, proposal decoding/safety bookkeeping, current-proposal -replacement, standard evidence, and disposition handoff. Families supply records, -candidate projections, prompts, application policies, fallback construction, and -domain diagnostics. Reuse the existing neutral reconciliation mechanisms. - -Preserve item currency compatibility, NPC naming/identity rules, and distinctions -between same-named locations. Neutral proposal issues can be translated into -family diagnostics by a D&D-local adapter; generic core need not import D&D. -Ordinary extractors do not acquire reconciliation concepts they do not use. - -The useful outcome is that family code reads primarily as domain preparation and -policy. If a proposed common facility instead needs numerous family switches, -revise the boundary rather than hiding three procedures in a configurable engine. - -### Native Result Handling - -The CAT-007 correction is accepted. Share a small native usability check where -needed by producers and the LLM validator. Distinguish absent results, completed -failed validation, and actual native Go errors; retain useful validation details -without manufacturing `promptkit.ErrValidation` for completed content rejection. -Preserve producer disposition and validator unavailability as separate outcomes. -Correct the test that expects the wrong sentinel and the native fixture that -currently accepts an arbitrary error. This adds no repair loop or budget. - -## Behavioral Scope - -This is an ownership/API migration. Existing selected behavior is the starting -contract, as recorded in [Architecture](../policy/architecture.md), -[Configuration](../config.md), and the focused internal guides. In particular: - -- Preserve complete configured assessment of each delivered usable candidate, - including the last allowed revision; no duplicate outer assessment. An unusable - interpretation may supply domain correction guidance without claiming a candidate. -- Keep native structural work upstream. Preserve growing native exchanges, - explicit execution selections, and release of native admission before nested - validation. A failed/result-less correction does not revive an earlier candidate. -- Apply reconciliation proposals afresh to fixed originals. Preserve final-only - fallback behavior, ordinary deterministic error propagation, and cancellation - precedence. Moving code must not widen fallback eligibility. -- Preserve accepted-result reuse under the original prepared message-content - hash, current-source usability checks, and no semantic reassessment on hits. - Store final accepted domain artifacts/plans, not exchanges or rejected proposals. -- Preserve fallback disclosure and dependency-specific reuse ineligibility, - required-capture failure handling, and independent consumer-owned observation. -- Preserve typed artifact/codec compatibility, module selections, native prompt ownership, - fixed stage boundaries, worker/admission separation, and domain output shapes. - -These are references to existing behavior, not an invitation to freeze incidental -callback order, private error prose, debug filenames, or implementation structures. -Keep flexibility for concrete integration requirements. No new correction limits, -input restrictions, shutdown guarantees, resource caps, or model-quality claims -are selected here. - -A redesign of input/output adapters, the CLI, registry discovery, or configuration -composition is not needed merely to centralize producer behavior. Adapt their -existing connections where necessary. Native LLM validators retain their one-shot -assessment role; sharing usability/evidence support does not enroll them in the -producer correction lifecycle. - -## Required Change Surface - -- Author-facing typed stage contracts, registration, and core execution reflect - preparation followed by core-owned production. The same executor serves - registered and standalone callers. Deterministic work and preparation-limit - dispositions have explicit paths without synthetic model requests. -- Candidate evaluation, correction request construction, assessment, cache use, - and evidence have clear owners. Candidate-associated information is replaced - as one evaluation; native capture state is independent. Existing internal - helpers may remain where useful, without requiring integrations to compose them. -- Shared reconciliation connects existing neutral preparation, safety, and typed - application mechanisms to the same lifecycle. The three registry families - retain policy and diagnostics rather than duplicated coordination. -- Affected extraction, scene planning, normalization, deterministic completion, - and programmatic callers use the selected boundary. One-shot validators share - native usability handling without acquiring a producer correction loop. -- Module, pipeline, and D&D authoring guides describe the implemented API and - its ownership and concurrency expectations. One minimal domain-neutral working - example introduces the API; an existing registry provides the richer example. - Architecture policy and significant ADR decisions reflect the resulting - ownership while preserving accepted ADR bodies. -- Superseded authoring plumbing is removed, and overlapping audit findings have - evidence-based statuses. Unrelated audit remediation remains separate work. - -## Verification And Completion Evidence - -Use existing boundary tests and real native kits with offline provider fakes. -Tests should protect behavior and author-facing contracts, not private callback -sequences or exact struct layouts. Relevant starting points include -[producer](../../internal/framework/pipeline/producer_test.go), -[producer cache](../../internal/framework/pipeline/producer_cache_test.go), -[operation completion](../../internal/framework/pipeline/runner_operation_test.go), -[chunk-plan cache](../../internal/framework/pipeline/chunk_plan_cache_test.go), -and [native capture](../../internal/framework/pipeline/native_capture_test.go) tests. - -Cover the distinct risks introduced by moving ownership: - -- Registered typed extraction, scene planning, reconciliation, and no-model paths - reach core execution without integration-owned assessment/disposition plumbing. -- A small non-D&D example exercises generic source/chunk handling and typed - production without scene/combat fields or mandatory registry reconciliation. - Email/NWS walkthroughs inform that example; complete processors are not required - as verification dependencies. -- Replacing or invalidating a candidate also replaces or invalidates its associated - findings; historical debug evidence remains distinguishable from final results. -- The convenient correction path and a specialized native builder preserve the - selected prompt/input bindings, execution selections, and native history through - the same core lifecycle, without requiring a universal guidance variable. -- Every usable revised candidate receives complete assessment; interpretation-only - guidance can request correction; native failed checks retain details and do not - become semantic approval or an extra structural-repair loop. -- Fixed-original reconciliation retains each family's expected output, fresh - proposal application, and final-only fallback. Failed/undelivered corrections - and caller cancellation retain their established behavior. -- Cache hits, accepted corrected writes, failed refresh, fallback-derived - ineligibility, and cache/capture error distinctions survive the new boundary. -- Native evidence and supplied observers remain attached to actual executions; - cache hits invent no model execution. Disabled evidence does not require - expensive domain-only debug construction in the new API. -- Concurrent operations do not share candidate state; nested validation still - works with limited native capacity. Reuse relevant worker/admission tests. - -Place common lifecycle coverage in core and retain representative independent -family tests. Simplify tests coupled to retired plumbing; do not derive expected -domain outputs from the same helper under test. This is a coverage guide, not a -new test for every row or an exhaustive cross-product requirement. - -The retired implementation plan assigned focused and final checks -under [Testing Policy](../policy/testing.md) and -[Development](../development.md#validation). Completion evidence includes offline -full tests, vet, build, and focused race checks for changed concurrency paths. -No paid inference, benchmark target, coverage percentage, or new release gate is -required. This planning pass has not run those implementation checks. - -The roadmap is complete when affected production integrations use the selected -API, ordinary authors no longer compose the shared lifecycle, obsolete paths are -removed, behavior is verified, author guidance matches the implementation, and -the catalog is reassessed. The design has also been exercised against email and -NWS processing scenarios without making their domain behavior a core requirement. -A clearer private `RunProducer` alone is insufficient. - -## Relationship To The Audit - -| Findings | Treatment in this roadmap | -| --- | --- | -| CAT-015 / CAT-016 | Central scope: replace coupled author-facing lifecycle responsibilities and duplicated registry reconciliation coordination. | -| CAT-007 | Accepted correction included at both producer and one-shot validator boundaries, including the misleading test oracle. | -| CAT-006 / CAT-008 / CAT-009 / CAT-022 / CAT-023 | Coordinate candidate/evidence/diagnostic lifetime changes where this migration touches them. Runner-wide finalization and CLI lifecycle issues remain outstanding unless separately demonstrated fixed. | -| CAT-003 / CAT-024 / CAT-025 / CAT-032 | Keep new optional evidence inexpensive and document actual concurrency. Apply the accepted whole-source capture direction if touched, but do not assume a package move or the entire capture inventory must be redesigned here. | -| CAT-014 / CAT-017 / CAT-018 | Accepted composition/copying direction remains valid. Make only changes required by the new registration/operation boundary; broader consolidation follows this initiative unless it becomes a concrete prerequisite. | -| Other entries | Reassess after migration; retain independent defects, optional cleanups, and CAT-034's resolved status. | - -The accepted diagnostic retention, source-capture, signal, and composition choices -in [discussion Items 1–4](audit/discussion.md) remain selected future work. This -roadmap does not reverse them or silently incorporate all their implementation. -If an overlapping fix is completed during this work, record its actual scope and -tests. Catalog IDs are evidence references, not a mandate to close every entry.