# Native Kit Observability Implementation Plan ## Objective And Working Rules Implement the selected end state in [upgrade-kit.md](upgrade-kit.md). That roadmap owns scope and policy choices; this document owns execution order. The inspected baseline is `1483e8e`: configuration version 6, PromptKit v0.24.0, CommandKit v0.7.0, ckconfig v0.10.0, ckprompt v0.11.0, and ConfigKit v1.4.0. Each numbered stage is one bounded Luna implementation prompt. Execute them in order as one end-to-end sprint. Intermediate stages may leave compile errors or temporarily outdated documentation; do not add compatibility fields, temporary adapters, or duplicated accounting merely to make an intermediate checkpoint green. Resolve the affected callers in the assigned subsequent stage. The final tree must compile, pass the checks below, and match the complete target. Start with [development guidance](../development.md) and read applicable [agent](../policy/agents.md), [architecture](../policy/architecture.md), [testing](../policy/testing.md), [documentation](../policy/documentation.md), and [OSS](../policy/oss.md) policies. The approved roadmap authorizes replacing the exact-one-group clause through the narrow ADR process in Stage 6. Preserve accepted ADR bodies while that documentation work is pending. Implementation decisions already settled: - Use the exact released dependency set in Stage 1. The feature roadmap records its source commits. Do not expand the sprint to a later release without review. - ckprompt owns ordinary invocation reporting. Debug and other callers attach native contextual observers only when they need evidence. The runner owns neither a group nor invocation accounting. - Remove `RunInput.Executions` and `ExecutionOptions.Observer`; retain native per-request capture observers, `OnPrepared`, and operation evidence. Independent native groups are fine; no shared-group registry or application totals service. - Keep application configuration version, model/profile choices, prompt content, artifact schemas/paths, cache identity/eligibility, assessment, producer budgets, worker/admission policy, and completion-report fields unchanged. - Missing accounting details are not new warnings or errors. No automatic `zero_cost`, provider inference, pricing estimates, credential probes, or billing guarantees. Library-owned behavior is documented by upstream links. Use real kits, temporary files, fake native clients, and local HTTP servers for tests. Reuse meaningful existing coverage; each acceptance item is not a demand for a separate test or a copy of upstream's parser/provider test matrix. ## Stage 1 — Upgrade The Published Dependency Set **Status:** Complete. Selected the four reviewed releases together, retaining ConfigKit v1.4.0 and Go 1.27.0. Tidy changes only the selected kit checksums; there are no replacements or application compatibility changes. Published tags resolve to the reviewed source commits. Updated the four attribution entries after comparing unchanged COPYRIGHT/LICENSE contents. The existing nonempty ckprompt declarations install `--show-tokens` without local plumbing or collision. Focused CLI/config/preflight tests, native run help and bare config-explain help, module selection, and `git diff --check` pass. Context ownership and new accounting coverage remain in the following stages. **Goal:** Adopt the coordinated releases through the existing composition root. **Inspect/change:** `go.mod`, `go.sum`, `internal/cli/application.go`, and the four changed kit entries in `docs/oss/attribution.md`. Inspect the release notes linked in the feature roadmap and the selected modules' actual manifests/notices. 1. With `GOWORK=off`, select PromptKit v0.25.0, CommandKit v0.8.0, ckconfig v0.11.0, and ckprompt v0.12.0 together; retain ConfigKit v1.4.0 and Go 1.27.0. Run ordinary module tidy and review its resulting changes. No local replaces or upstream compatibility patch is needed. 2. Retain the nonempty `ckprompt.Declarations` installation in `NewApplication`. Its update installs native `--show-tokens`; add no local flag, result wrapper, final usage callback, or manual counting. Fix a real installation collision if discovered, without changing native spelling or normal input semantics. 3. Review expanded public structs/decoders if compilation identifies an issue. Native result/event serialization should naturally retain reasoning/cost; do not introduce a parallel Notarius accounting DTO. 4. Update changed attribution versions and commit-specific source/COPYRIGHT/ LICENSE links using the feature roadmap's distinct commits for root and integration modules. Compare notice/license contents; retain unchanged local license texts and ConfigKit/policy entries. Upstream maintainer tools alone do not become Notarius runtime dependencies or attribution entries. **Acceptance:** The selected graph contains all five target versions. Native reporting installs through the existing command assembly. No model, prompt, schema, configuration-version, or budget change accompanies the upgrade. **Checks:** ```sh GOWORK=off go get go.maximumdirect.net/promptkit@v0.25.0 go.maximumdirect.net/commandkit@v0.8.0 go.maximumdirect.net/ckconfig@v0.11.0 go.maximumdirect.net/ckprompt@v0.12.0 GOWORK=off go mod tidy GOWORK=off go list -m go.maximumdirect.net/configkit go.maximumdirect.net/promptkit go.maximumdirect.net/commandkit go.maximumdirect.net/ckconfig go.maximumdirect.net/ckprompt GOWORK=off go test ./internal/cli ./internal/core/config ./internal/preflight ``` ## Stage 2 — Move Debug Accounting To Its CLI Consumer **Status:** Complete. Removed the runner group input, allocation, enrollment, and implicit summary write. Requested CLI capture decorates the inherited execution context with its own native group after allocation and writes one snapshot immediately before finalization. The recorder's sticky errors preserve operation causes and published artifacts. Direct runner reuse coverage now owns its context/group and confirms no implicit summary file. Focused pipeline capture, CLI recovery/run/debug tests pass, including summary-write failure after publication and combined provider/capture/diagnostic failures; whitespace passes. General option forwarding remains until the next stage. **Goal:** Remove runner-owned groups and give requested debug capture ownership of its native summary, without changing operation evidence. **Inspect/change:** `internal/cli/pipeline_run.go`, `run_capture.go` if useful, `internal/framework/pipeline/runner.go`, `operation_capture_test.go`, and CLI capture/recovery/completion tests. Inspect `internal/framework/debug/recorder.go` before changing error/finalization flow; reuse its existing sticky write errors. 1. Remove `RunInput.Executions`, the runner's unconditional group allocation, enrollment into execution options, and deferred group snapshot write. Remove now-unused imports. Do not move that allocation into another generic framework constructor. 2. In the run handler, retain a local context derived from `invocation.Context`. After requested capture has been allocated successfully, create a native `ExecutionGroup` only if `capture.Enabled()`, and decorate this context using `promptkit.WithExecutionObserver`. Pass the decorated context through the remaining engine/preflight/run work. Without capture, keep the original invocation context, including any ckprompt or external caller observer. 3. Keep the debug group local to this consumer. Write its native snapshot once in the existing `finish` path immediately before `capture.Finalize`, after started pipeline work has been joined. Use the existing private `executions.json` filename to avoid needless fixture churn, not as a new public contract. Early failures with no allocated group need no snapshot. 4. Let the recorder retain snapshot write failures and finalize with the primary operation cause. Preserve nonzero failure, available locations, and any already published artifacts. Do not retry models, turn capture failure into permissive fallback, finalize twice, or move publication into a CommandKit invocation feature. Snapshot placement is private; it need not remain inside the runner or precede publication. 5. Migrate direct runner test/caller group inputs to caller-owned decorated contexts and `group.Snapshot()`. A framework test may explicitly write its own summary if it actually needs that file; the runner must not do it implicitly. Keep operation input/result/exchange/cache evidence tests otherwise intact. **Acceptance:** A runner with no interested caller allocates no accounting group. Captured CLI runs retain actual native execution summaries on success and returned failure, and cache-only runs retain no historical execution. Debug summary writes participate in existing capture failure handling. **Checks:** Run focused pipeline operation-capture tests and CLI recovery, preflight-capture, completion, and capture-failure tests. General observer forwarding still exists from the baseline until Stage 3; do not add a temporary replacement for the removed group input. ## Stage 3 — Remove General Observer Forwarding **Status:** Complete. Removed the general execution-option observer and all producer/coordination/validator forwarding, including the accounting-only request-builder Boolean. Native contexts now carry caller observers; direct request observers, preparation hooks, and operation capture remain intact. Migrated callers/tests and checked remaining observer names semantically. Raw start/terminal counts and independent run IDs cover initial/correction/nested execution without relying on group de-duplication; synchronized concurrent coverage, event-free cache preparation/hits, frozen prepared misses, cancellation, and undelivered-response checks pass. Pipeline, concrete combat-validator, CLI, focused prepared-cache tests, full pipeline race tests, and whitespace pass. **Goal:** Make native context propagation the only invocation-accounting path. **Inspect/change:** `internal/framework/contracts/producer.go`, `internal/framework/pipeline/producer.go`, `internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go`, and affected tests. Current migration sites include `producer_test.go`, `producer_cache_test.go`, `native_capture_test.go`, `typed_registry_request_test.go`, and `internal/cli/pipeline_run_test.go`. Search the entire current tree for remaining field uses rather than assuming this list is exhaustive. 1. Delete `ExecutionOptions.Observer` and its obsolete comment. Keep execution target overrides, transient retries, `OnPrepared`, and `Capture` unchanged. 2. Remove enrollment from initial `producerRequest`, `CoordinateRequest`, and the scene semantic validator. Remove the `initial` Boolean argument from `producerRequest` if, as in the baseline, accounting was its only purpose; update its initial/correction callers and comments. 3. Keep direct `RunRequest.Observer` callbacks belonging to a request or `CaptureNativeRequest`. Preserve capture's observer/`OnPrepared` composition, synchronization, error checks, and native result/exchange recording. Do not blindly delete all uses of the word `Observer`. 4. Migrate test observers to `WithExecutionObserver` on the actual execution context. Update typed-option tests to check the remaining request overrides and preparation callback; contextual observation is not another option field. 5. Reuse/extend existing producer/native-capture tests to prove one contextual observer sees initial execution, semantic correction, and nested validator executions exactly once, with independent run IDs and terminal coverage. Retain the concurrent-operation test with synchronized observer state. Keep cancellation and undelivered-response behavior covered. 6. Update the frozen-prepared-handle/cache tests to exercise contextual observation on a prepared miss and no events on a hit. Where an application boundary actually separates preparation/execution, assert that execution's context owns observation. Do not introduce new split-preparation machinery solely to retest PromptKit's own prepared-context contract. **Acceptance:** Neither removed field nor a forwarding alias remains. Context reaches `Run`, `RunPrepared`, coordination, and LLM validation. Request capture continues to work independently; native group de-duplication is not concealing duplicate registration of the same observer. **Checks:** ```sh GOWORK=off go test ./internal/framework/pipeline ./internal/modules/dnd/validate/scenedescriptions/combat_semantics ./internal/cli GOWORK=off go test -race ./internal/framework/pipeline ``` Inspect remaining `Observer`/`Executions` occurrences semantically: native request observers and unrelated names remain legitimate. ## Stage 4 — Verify Native Reporting Through Assembled Pipeline Runs **Status:** Complete. Extended the existing recovery fixture with optional flags and explicit native usage/cost. Its concurrent corrected/nested-validator run, returned failure, selective recovery, and full hit compare actual calls with debug facts and selected diagnostic values, without copied production totals. Completion formats, alias routing, quiet, cancellation, bare config-explain help, and diagnostic-only delivery failure retain their contracts. Installed real ckprompt declarations in the reduced run fixture after the new tests exposed its missing feature. Upstream omission/explicit-false handling remains native. The focused checks, full CLI suite, touched concurrent/failure race checks, and whitespace pass. All providers in these checks are fakes. **Goal:** Prove the application uses native invocation reporting without lost or duplicated accounting, including failure and accepted-result reuse. **Inspect/change:** CLI tests, primarily `recovery_contract_test.go`, `run_result_command_test.go`, `pipeline_run_test.go`, and `application_test.go`. Use a focused `usage_reporting_test.go` only if it keeps the tests clearer. Reuse `newRecoveryFixture`, `recoveryClient`, and `runFixture` rather than building a second miniature application/framework. 1. Allow the recovery fixture to accept additional CLI flags if needed, keeping its existing default behavior. Use an invocation with `--show-tokens`, JSON main output, requested capture, a corrected scene, and nested combat assessment. Use more than one worker in this representative observation case if needed to exercise concurrent context propagation; synchronize fake counters and do not assert completion order. 2. Give the native fake explicit token presence and known test-controlled usage/cost where numerical assertions are needed. Compare expected native execution totals with actual fixture calls/debug group facts, not with a new production accumulator. This fixture has no structural repair unless explicitly arranged, so a semantic correction is a separate execution, not a repair count. 3. Assert stdout still decodes as the ordinary completion report and artifacts remain correct. Requested usage appears only on diagnostics. Assert only selected numeric/semantic fragments of native text; do not snapshot its entire wording or clone its renderer into a test helper. 4. Reuse the accepted-result recovery/full-hit path with `--show-tokens`: accepted predecessors are reused, a full hit makes no new provider calls, and the new invocation reports no historical executions/tokens/cost. 5. Exercise the same installed feature with a returned producer failure, and reuse a controlled cancellation boundary where necessary to show observed work survives. Preserve the original operation cause, no false success report, and ordinary artifact/capture behavior. A final summary is not permission to catch a panic or manufacture terminal facts. 6. Extend existing help/report-delivery tests with representative usage-enabled cases: a run alias, quiet suppression, bare `config explain` help without loading, and diagnostic-write failure with retained publication/native delivery evidence. Omission/explicit false and repeated flags inherit native semantics; inspect existing/upstream coverage rather than adding a Cartesian parser matrix. Native reporting failure must not rerun pipeline work. **Acceptance:** Native reporting observes real application work and leaves stdout/domain deliverables unchanged. Requested debug and CLI reporting can coexist without adding their overlapping totals. Real failures remain visible; missing measurement is not promoted to a warning. **Checks:** Run the touched CLI tests and `GOWORK=off go test ./internal/cli`. Use focused `-race` runs for the new concurrent fixture. No production API calls. ## Stage 5 — Verify Provider Accounting And Native Smoke Exposure **Status:** Complete. A real native HTTP client and one local server fixture cover explicit OpenRouter selection on an arbitrary backend ID, reasoning/cache details, positive and reported-zero cost, unchanged domain/completion output, and native result/debug/diagnostic propagation. Installed smoke commands retain reasoning and nullable ratio values in JSON, native default text, and separate ordinary accounting; help does not load configuration. Recorded the published smoke API's target-only prompt selection rather than inventing input flags. Unknown-cost capture coverage and complete-example inherited-provider inspection pass. Focused CLI/pipeline checks and whitespace pass; fixtures use no real credentials and all HTTP calls stay local. Example configurations are unchanged. **Goal:** Cover the new provider/accounting boundary once through the real HTTP client and installed native commands. **Inspect/change:** CLI integration tests near `production_contract_test.go` or `native_process_test.go`; a focused new provider-accounting test file is fine. Inspect PromptKit v0.25.0's response contract and ckprompt v0.12.0's smoke report contract linked from the feature roadmap. 1. Use one `httptest.Server` fixture with the production application loader and no injected `LLMClient`. Declare a test backend with `provider: openrouter`, an arbitrary non-OpenRouter ID, the local endpoint, and a fake model/profile that needs no real credentials. This proves convention selection comes from configuration rather than hostname or ID. 2. Return valid minimal spell output and a valid OpenRouter envelope with prompt/completion/total tokens, cached tokens, nested cache-write and reasoning tokens, and a small test-controlled `usage.cost`. Verify those values reach native debug evidence and the requested diagnostic report. Reasoning/cache details must not inflate totals. Select simple values that avoid brittle floating-point or exact text-format expectations. 3. Retain unavailable-versus-known-zero coverage from the fake/native evidence tests. Add a missing-optional-details case to this same fixture only if that application boundary remains unprotected. Do not retest every malformed provider field, add custom response parsing, or add a second vLLM decoder suite; upstream owns those contracts. 4. Through the installed ckprompt suite, use the same local fixture for explicit `promptkit test text_inference` with a concrete prompt and profile. The selected native smoke API uses the prompt only for target selection; it does not execute its body or accept prompt inputs. Request structured JSON (and YAML only if an existing test covers it) and check reasoning and nullable cache-hit-ratio propagation. Smoke usage is in its own report, not an added smoke cost field or duplicate ordinary accounting. Check default smoke output/help against native behavior without a full-format golden file. 5. Inspect the complete example's `limited-openrouter` through the real loader: it inherits the bundled `provider: openrouter`. Keep both example source configurations unchanged unless a real incompatibility is found. Leave `zero_cost` unset; do not add implicit local-backend or authentication policy. **Acceptance:** Native provider selection, expanded accounting evidence, and the existing smoke interface are usable through Notarius. No application-side provider adapter, default cost, unsolicited probe, or additional reporting schema is introduced. **Checks:** Run the focused CLI provider/smoke tests offline and review fixture URLs/credentials to confirm all calls stay local. ## Stage 6 — Align Architecture, The ADR, And Internal Ownership Docs **Status:** Complete. Added ADR-0025 for consumer-owned contextual observation and narrowly updated ADR-0024's status; its accepted body is unchanged. Replaced the architecture group-count clause and aligned CLI/LLM/pipeline/state ownership with conditional CLI capture, inherited context, native optional reporting, and publication-aware finalization. Native mechanics link to selected upstream contracts. Policy provenance and its current implementation-date metadata are retained. All 178 local links in the seven affected documents resolve; selected upstream anchors, stale ownership searches, ADR status-only diff, and whitespace pass. Reused passing runtime checks for unchanged code. **Goal:** Record the implemented ownership change without rewriting accepted history or preserving a redundant exact-one-group requirement. **Inspect/change:** `docs/policy/architecture.md`, ADR-0024, a new successor ADR, and the affected passages in `docs/internal/{cli,llm,pipeline,state}.md`. 1. Add `docs/adr/0025-use-consumer-owned-execution-observation.md` if 0025 is still available; otherwise use the next sequential number and update links. Use the repository's concise Nygard sections and the actual implementation date. The approved decision is consumer-owned native contextual observation, with independent native groups when separate consumers need them. 2. Supersede only ADR-0024's requirement for one native invocation group. Preserve native identity/coverage/unknown-state accounting, no fabricated historical executions, and all other artifact/report/capture/failure decisions. Explain briefly why shared-group discovery and application accounting services are unnecessary; do not establish a new rule for an exact number of consumers. 3. Change ADR-0024's status to accepted with that narrowly identified partial supersession and a link to the successor. Leave its accepted body unchanged. 4. Replace architecture's exact-one-group sentence with the implemented consumer ownership/context boundary and link the successor decision. Preserve native fact handling and event-free cache hits. Update its local `Last Updated` date, retaining its upstream source/version because this is a local adaptation, not another upstream policy adoption. 5. Update the concrete ownership passages: the CLI owns optional debug grouping and summary capture, ckprompt owns optional presentation, and the runner simply propagates context. Keep operation-specific `NativeCapture` evidence, secret handling, cancellation/draining, and publication/finalization ownership accurate. Replace affected library-mechanics explanations with upstream links rather than expanding them. **Acceptance:** Current policy, decision status, and internals describe the implemented consumer boundary consistently. No unrelated ADR decision or application invariant changes. ADR-0024's body is unchanged from the baseline. **Checks:** Review the ADR body diff explicitly; verify local links/anchors and search current ownership docs for stale runner-owned/exact-one-group claims. Historical accepted text remains historical and need not be erased. ## Stage 7 — Refresh Operator Links And Adoption Documentation **Goal:** Make the adopted capabilities discoverable without maintaining copies of upstream feature documentation. **Inspect/change:** Affected passages in `docs/cli.md`, `docs/config.md`, `docs/operations.md`, the three `docs/integrations/pkg-*.md` kit documents, and `docs/consumers/{subprocess,dnd-pipeline}.md`. Check `docs/consumers/native-migration.md` for an affected default-smoke-output claim. Review maintained examples; no new example collection is required. 1. Update changed dependency versions and upstream links to the selected releases or their exact commits. The independently tagged ckconfig/ckprompt sources are not the CommandKit core tag. Keep unchanged ConfigKit v1.4.0 references. 2. State which native interfaces Notarius imports; link directly to canonical upstream usage reporting, provider configuration, inspection, and smoke contracts. Remove/replace affected duplicated explanations instead of adding new flag tables, accounting manuals, provider-field references, or tutorials. 3. Keep local application choices: source/embedded collection assembly, invocation alias and pipeline inputs, domain publication/completion reports, requested debug lifecycle, and accepted-result reuse. One short concrete Notarius invocation can show `--show-tokens`; link upstream for its semantics. Explain locally that accepted-artifact hits perform no current model work, rather than copying upstream accounting definitions. 4. Keep subprocess callers focused on successful stdout decoding and artifact retrieval; link optional diagnostics without inventing a durable usage API. Where a script/example consumes smoke output, select JSON or YAML explicitly rather than assuming the old native default. Do not rewrite historical release notes or conduct a repository-wide documentation overhaul. 5. Recheck Stage 1's attribution against the final selected graph and license texts. Preserve unrelated policy provenance/attribution and the project's existing license grant. **Acceptance:** Operators can reach applicable upstream documentation from Notarius, and local docs accurately describe only the relevant application integration/workflows. Examples remain valid, secret-free, and no stronger behavioral guarantees have been introduced. **Checks:** Review local links/anchors, pinned upstream source paths, affected commands against built help, and examples against offline preflight. No new permanent documentation checker or network-dependent test is required. ## Stage 8 — Verify The End-To-End Sprint **Goal:** Confirm the complete target, remove migration leftovers, and report actual validation results. This stage is verification and targeted correction, not a second refactoring initiative. **Checks:** Perform the following review and validation against the final tree. 1. Review the final diff against the feature roadmap. Confirm removal of both old fields and invocation-observer forwarding; no unconditional application group, observer service, manual totals, or copied report renderer remains. Native request capture and explicit caller observers remain legitimate. 2. Confirm worker/continuation/validator contexts preserve inherited observers and work is drained before the CLI's native final report. Review success, failure, cancellation, partial publication, and debug finalization paths. 3. Run the repository checks below with the actual selected module files, not a sibling workspace replacement. Reuse successful unchanged checks rather than re-running the full suite after every prose edit. ```sh GOWORK=off go test ./... GOWORK=off go vet ./... GOWORK=off go test -race ./internal/framework/pipeline ./internal/cli GOWORK=off go mod verify ``` 4. Build `./cmd/notarius` to an explicitly chosen temporary directory using `GOWORK=off go build -o /notarius ./cmd/notarius`. With that executable, run: ```text notarius version notarius run --help notarius pipeline run --help notarius pipeline validate dnd-session --config examples/dnd-minimal/config.yml --show-tokens --format json notarius pipeline validate dnd-session --config examples/dnd-complete/config.yml --show-tokens --format json notarius promptkit show backend limited-openrouter --config examples/dnd-complete/config.yml --format json notarius config explain --show-tokens ``` Use the built binary's full path in these commands. These are offline checks; the example profiles need no production credentials for preflight/inspection. Model-backed behavior is exercised by the local fixtures, not a paid run. 5. Check whitespace, local documentation links, ADR partial-supersession links, selected attribution commits, and the absence of unintended prompt/schema/ model/budget/cache/artifact changes. Report checks run and any genuine limits. Do not tag, release, push, or delete planning documents as part of this sprint unless separately requested. **Acceptance:** All feature-roadmap requirements are accounted for, the final tree builds and passes deterministic checks, and documentation matches the implemented ownership. Ordinary no-flag behavior retains its existing contracts; native opt-in diagnostics add no application-maintained accounting model. ## Open Questions None. The dependency set, consumer-owned observation, optional debug grouping, native reporting, documentation ownership, and narrow ADR supersession have been selected. Snapshot filename/helper layout and test organization are implementation details, not new product decisions or approval gates.