# 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 [Audit Remediation Roadmap](../audit-remediation.md) owns the consolidated target and scope; a subsequent implementation plan will own detailed 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 [formal roadmap](../audit-remediation.md) defines 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.