Remove completed audit history from the roadmap

This commit is contained in:
2026-11-26 13:53:00 +00:00
parent d064d25db9
commit 78ad79d64d
15 changed files with 0 additions and 7835 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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/<family>/<check>/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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.