# Library Adoption Remediation **Status:** Findings from the implementation, integration, and algorithm reviews; remediation is in progress. **Reviewed source:** `338e93a7ebda9a86593069d63f9d5a7fe23ccaf5` (`Complete library adoption validation and cleanup`). The follow-up review used `ca06f7c4e34d5702d2234a56c84250c31435fcf2`, which adds the initial findings without changing application code or dependencies. The algorithm review used `a020d155f4f2b4270745a2e4ccf9c3565ea129e2`, which adds the integration finding and also leaves application code unchanged. The review covered Stages 1–10 of the [implementation plan](implementation.md) against the [feature roadmap](library-upgrades.md), including implementation, tests, maintained documentation, migration guidance, and release preparation. The intended architecture is substantially in place. The initial review found test-maintenance and documentation gaps; the follow-up integration review also confirmed an output-safety gap involving operator-owned schema files. The algorithm review adds a debug-assembly memory opportunity and a diagnostic ordering defect. R1–R3 remain outstanding. ## R1: Remove the Test Fixtures' Implicit YAML Layout Requirement **Complete.** Shared structural YAML fixture editing replaces all three text injections; focused layout/contract regressions and affected package tests pass. **Priority:** P2 — test maintainability and unintended constraint. **Affected code:** - [Adapter fixture](../../internal/framework/llm/adapter_test.go): `adapterFixtureWithPrompt`, budget insertion near line 102. - [Native adapter fixture](../../internal/framework/llm/native_adapter_test.go): budget insertion near line 98. - [Subprocess fixture](../../cmd/audita/main_integration_test.go): budget insertion near line 280. **Finding:** These new fixture paths copy complete shipped prompt documents and append `repair_attempts` as raw text with ten leading spaces. This assumes the prompt's `output` mapping is last and has the current indentation. Equivalent YAML formatting or mapping-order changes can therefore break adapter and subprocess tests while the production native loader continues to accept the prompt. The same fragile operation is duplicated in three places. This strengthens an incidental source-layout choice into a test requirement. The selected contract is that fixtures choose explicit prompt-owned repair budgets; it does not require shipped YAML to retain a particular indentation or key order. **Evidence:** A temporary, external probe loaded the shipped glossary prompt through native PromptKit successfully, then decoded and reserialized it with the selected YAML library. The equivalent document also loaded successfully. Appending the fixture's budget line to that equivalent document made native configuration loading fail. No repository prompt was modified for this probe. **Recommended change:** Set the selected prompt record's `output.repair_attempts` structurally using a YAML node or mapping, then render the complete replacement document. Reuse a small fixture helper where practical so adapter, native-adapter, and subprocess tests do not maintain independent text-injection rules. Keep this adaptation in test support; production request contracts should continue to come directly from prompt definitions. **Acceptance:** Fixture budgets remain test-controlled and native loading continues to see the complete intended prompt contract. Equivalent YAML formatting or key-order changes do not invalidate budget insertion. Retain a focused regression at the helper boundary without duplicating upstream YAML or budget-resolution test matrices. ## R2: Align Remaining Documentation with the Removed Schema Registry **Complete.** Prompt guidance describes prompt-owned contracts and domain validation; roadmap statuses reflect the completed implementation. Local links and whitespace checks passed. **Priority:** P3 — incomplete documentation cleanup. **Affected documents:** - [Prompt registry guide](../internal/prompts.md), especially lines 58–68. - [Feature roadmap](library-upgrades.md), implementation status near its opening. - [Implementation plan](implementation.md), opening status. **Finding:** The prompt guide still says `responseschema` retains Audita's schema-key lookup and that structured calls carry a response-schema key. The implementation intentionally removed both: `responseschema` now exposes only the embedded filesystem/asset root, and `structuredoutput.Request` selects a prompt without a schema field. These statements contradict the central prompt-owned-contract decision and could lead a future contributor to restore the retired override path. The feature roadmap also says implementation has not begun, and the plan's opening still says ready for implementation despite completion records for all ten stages. These status statements no longer describe the reviewed source. **Recommended change:** Remove the obsolete schema-key/lookup descriptions. Describe the remaining shared schema assets, the selected prompt's output contract, and Audita's domain decoding and validation. Link to upstream for native schema behavior. Update the roadmap and plan statuses to reflect that implementation is complete and review remediation remains outstanding; preserve their baseline and decision history. **Acceptance:** Maintained guidance does not claim that production structured requests carry schema keys or that a schema registry still chooses their contracts. Roadmap status agrees with the implementation and this review. No application code, historical release record, or accepted ADR needs to change to address this finding. ## R3: Include Operator Schema Files in Existing Output-Collision Checks **Complete.** Effective schema files now share origin-based consumed-input tracking with message files. Source-local/inherited paths, transcript/report collisions before writes, and successful noncolliding processing pass focused LLM and assembled CLI tests. Operational guidance lists schema protection. **Priority:** P2 — consumed-input preservation and runtime integration. **Affected code:** - [Runtime source tracking](../../internal/framework/llm/source_paths.go): `capturedSourcePaths`, especially lines 23–44. - [Processing input assembly](../../internal/cli/process_inputs.go): protected-path handoff near lines 71–77. - [Output selection](../../internal/core/diagnostics/output_session.go): `SelectOutput` consumes that protected set before preparing outputs. **Finding:** Prompt-owned contracts now make an operator's native `output.schema_file` an actual processing input. Source tracking still collects only configuration sources and effective `messages[].content_file` paths. The schema file is absent from ConfigKit's configuration-source inventory and from Audita's protected paths, so existing output-collision checks never see it. A transcript destination can consequently overwrite a schema used by its own run. An ordinary report can also overwrite the schema during initialization, before PromptKit prepares the first request. That both damages an input and turns a valid configuration into a fatal validation-contract failure. The configured contract is valid; the conflict arises between the newly honored schema input and the previously existing output lifecycle. This concerns the integration work in Stages 3 and 4, rather than a defect in native schema validation. **Evidence:** Two isolated subprocess probes used a grammar-only pipeline, a complete operator prompt replacement with a source-relative `schema_file`, and a local HTTP stub returning `{"corrections":[]}`: - Selecting that schema file as the transcript output completed successfully after one provider request and replaced the schema with transcript JSON. - Naming the schema `errors.yml` beside the transcript output let report initialization replace it. Processing then failed with `structured validation contract failed`, made no provider request, and left report YAML in the former schema file. The probe binary's build metadata identifies the reviewed implementation commit. Application code and dependencies are unchanged at the follow-up review revision. All probe files were temporary and synthetic. **Recommended change:** Extend the existing consumed-input path collection to include effective host-backed `output.schema_file` inputs for root and collection prompts. Use the native recorded origin/filesystem context to identify the same file PromptKit resolves, including inherited or replaced definitions, and pass those paths through the existing collision mechanism before any output preparation. Keep schema parsing and validation upstream; this requires no alternate resolver or restriction on operator contracts. Keep inline and embedded schemas valid and preserve intentional in-place transcript replacement. Update the operational description of protected inputs when the fix lands. **Acceptance:** Colliding transcript and ordinary-report destinations are rejected before writes or provider calls, leaving the schema unchanged. A noncolliding operator schema still supports processing and native preparation. Cover source-local origin selection at the source-tracking boundary and both output-collision outcomes at an assembled boundary, reusing existing collision semantics rather than duplicating their complete filesystem test matrix. ## R4: Build Per-Call Summaries Without a Second Event Inventory **Complete.** One-pass native groups replace per-call event inventories. Reporting tests pass for unsorted inputs, retained order, duplicate terminals, incomplete coverage, and calls with no events. **Priority:** P3 — optional debug-memory improvement. **Affected code:** - [Debug execution assembly](../../internal/framework/processreport/llm.go): `BuildLLMExecution`, especially the `eventsByCall` construction and replay. - [Native aggregation handoff](../../internal/framework/llm/observations.go): `Summarize` replays each selected event sequence into an `ExecutionGroup`. **Finding:** The builder copies the event slice for the returned artifact, then copies every complete observation again into per-call slices in `eventsByCall`. Those extra slices exist solely to replay their contents into native groups. The grouping pattern predates this upgrade, but the revised builder carries it forward with the richer native event values. The plan requires native per-call aggregation and retained events; it does not require a second event inventory. **Complexity:** Let `E` be observations, `C` logical calls, and `R` distinct call/run memberships. Current assembly takes expected `O(E + C + R)` time, with `Theta(E + C)` additional storage for event grouping. A map of call IDs to native `*ExecutionGroup` instances can observe events directly in one pass, retaining `O(C + R)` grouping state instead. This helps when attempts and repair activity produce many events for each run. Required snapshot/artifact storage remains linear in the retained evidence, and processing time remains linear; this is an auxiliary-memory improvement, not a quadratic-time defect or a claim of measured performance impact. **Evidence:** Inspection of the selected native group shows that it retains run membership and aggregate facts, rather than event history. A temporary synthetic probe matched the existing per-call summaries using direct native group accumulation for 40 events, four logical calls, and three observed runs, including duplicate terminal events, incomplete coverage, and a call without events. No benchmark or real-provider workload was used. **Recommended change:** If undertaking this cleanup, accumulate native groups by call ID while traversing the retained events, then snapshot those groups when constructing calls. Preserve the returned event sequence and call order, including for unsorted supplied snapshots. Continue delegating terminal deduplication, coverage, usage, and cost to PromptKit. Retain the existing invocation summary handoff; do not introduce copied metric DTOs or a second accounting algorithm. **Acceptance:** Per-call summaries retain their current meaning, including pre-execution calls and incomplete runs, without allocating a second full event inventory for grouping. Reuse existing reporting tests with a focused multi-event case where needed. This opportunity does not require a new runtime limit, benchmark gate, or change to the debug artifact schema. ## R5: Order Native Group Members at the Debug Presentation Boundary **Priority:** P3 — deterministic diagnostic presentation. **Affected code:** - [Collector snapshots and summaries](../../internal/framework/llm/observations.go): `Snapshot` and `Summarize`. - [Debug execution assembly](../../internal/framework/processreport/llm.go): top-level and per-call `promptkit` group summaries. **Finding:** The selected PromptKit group enumerates its membership map when creating `ExecutionGroupSummary.Members`. Audita now includes that slice in debug output without ordering it. Sorting the surrounding calls and events does not order the summary's members. An unchanged completed collector can therefore produce different serialized membership orders across snapshots. The previous metric projection did not expose this new slice. Stage 5 explicitly retains deterministic presentation ordering. This is an incomplete adaptation of native evidence to that selected presentation requirement. Counts, correction decisions, and ordinary reports are unaffected; the defect is confined to optional diagnostic presentation. **Complexity:** Enumerating `R` members is linear. Canonical presentation adds `O(R log R)` string comparisons for the invocation summary, plus `sum O(R_i log R_i)` for per-call member lists. A detached copy costs `O(R)` storage where an existing owned copy cannot be reused. This is a correctness tradeoff for the already selected ordering requirement, not a speed optimization. **Evidence:** A temporary overlay-only test populated one collector with 32 completed calls and fixed timestamps, then serialized 32 snapshots without changing any records. It observed multiple distinct membership orders in the top-level summary. The test file remained outside the repository. **Recommended change:** At one Audita diagnostic-presentation boundary, order detached native `Members` slices by run ID for the top-level and per-call summaries. Preserve native values, attribution, and the existing call/event sequence. Keep aggregation upstream and avoid changing shared snapshot slices as a side effect of rendering. No upstream ordering guarantee or new ordering of model execution is required. **Acceptance:** A fixed captured membership set has a consistent displayed order, regardless of native map enumeration. Use a small deterministic serialization regression with deliberately permuted member inputs; do not retain the audit probe's probabilistic map-order check. Native totals, availability, coverage, and run identities remain intact. ## Follow-Up Integration Coverage The review revisited the numbered implementation stages in order: | Stages | Interaction reviewed | Result | | --- | --- | --- | | 1–2 | Shared settings, domain defaults and overrides, companion origins, secrets bootstrap, native inspection, and startup diagnostics. | No additional gap identified. | | 3–4 | Runtime handoff, source protection, prompt-owned contracts, recoverable decoding, and semantic correction repair. | R3 confirms a missing input in existing output protection. | | 5–6 | Native execution evidence alongside domain operation counts, proposal attribution, repair histories, and optional debug output. | No additional gap identified. | | 7 | Invocation context propagation, shared admission, nested validation, usage reporting, quiet mode, and transcript streams. | No additional gap identified. | | 8–9 | Maintained examples, migration guidance, canonical contracts, attribution, and prepared release documentation. | Existing R2 remains; no additional gap identified. | | 10 | Cleanup and assembled workflows, including failure, cancellation, partial success, and output publication. | Existing tests pass; the schema-collision probes expose R3 beyond their coverage. | ## Algorithm Review Coverage The algorithm review examined the implementation stages in their numbered order. It did not reconsider the explicitly retained repair-history sharing, native retry/repair/admission and aggregation algorithms, or presentation ordering. No additional avoidable quadratic-time algorithm was identified in the reviewed changes. | Stage | Algorithm review result | | --- | --- | | 1 | Source composition and domain callback lifting delegate loading to the selected libraries; no additional local superlinear algorithm identified. | | 2 | Bootstrap forwarding and diagnostic buffering are linear in their supplied evidence; the retained invocation-local capture is not a growing processing cache. | | 3 | Source tracking uses maps for source identity, path deduplication, and native metadata lookup, followed by sorting unique paths. No repeated full metadata scan occurs per message. | | 4 | Removal of contract overrides and registry copying simplifies the call path; response decoding is linear in response size. Existing domain algorithms are preserved. | | 5 | Collection uses map updates and append operations; snapshot sorting follows the selected presentation design. Native membership ordering needs R5. | | 6 | Report assembly is linear in calls/events but has the avoidable grouping storage in R4. R5 also applies to its native summary presentation. Planned message-prefix sharing is retained. | | 7 | Context propagation and native invocation reporting add no separate local accounting algorithm. | | 8 | Documentation and maintained-example updates introduce no additional production algorithm. | | 9 | Attribution and release preparation introduce no additional production algorithm. | | 10 | Cleanup and final wiring introduce no additional algorithm beyond those reviewed above. | ## Review Validation With Go 1.27.4, the complete `go test -race ./...` suite, `go vet ./...`, `go mod tidy -diff`, and Linux amd64/arm64 builds passed. All 58 changed Go files were gofmt clean, and 145 local links in the changed Markdown documents resolved. The fixture-format probe above confirmed R1 separately from the passing current suite. This review did not change application code or publish a release. For the follow-up, uncached race-enabled tests passed for `internal/appconfig`, `internal/cli`, `internal/framework/llm`, `internal/framework/runner`, `internal/framework/processreport`, and `cmd/audita`. The two controlled schema collision probes confirmed R3. The follow-up changes only this remediation document; it does not implement the fixes or publish a release. The algorithm review used source-level complexity analysis and two temporary synthetic tests through a Go overlay. The membership-order probe confirmed R5; the single-pass native-group comparison supports R4. It gathered no real-world performance data and made no application-code changes. Existing tests for `internal/framework/llm`, `internal/framework/processreport`, and `internal/framework/runner` passed; remediation links and whitespace checks also passed.