From 68515668de54e2c239e73362698113bac7f3f7ac Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sun, 22 Nov 2026 20:26:16 +0000 Subject: [PATCH] Plan automatic usage reporting implementation --- docs/roadmap/automatic-usage-reporting.md | 28 +- docs/roadmap/implementation.md | 394 ++++++++++++++++++++++ 2 files changed, 404 insertions(+), 18 deletions(-) create mode 100644 docs/roadmap/implementation.md diff --git a/docs/roadmap/automatic-usage-reporting.md b/docs/roadmap/automatic-usage-reporting.md index 7730a0e..644816f 100644 --- a/docs/roadmap/automatic-usage-reporting.md +++ b/docs/roadmap/automatic-usage-reporting.md @@ -17,8 +17,8 @@ final reporting callbacks. Audita review commands and Notarius pipelines motivate the feature; their domain execution remains application-owned. This roadmap describes the agreed end state and the work needed to reach it. -It does not describe implemented behavior. A subsequent implementation plan will -define the concrete Go API and organize the work into discrete ordered stages. +It does not describe implemented behavior. The [implementation plan](implementation.md) +owns the concrete API, wiring example, ordered stages, and validation steps. ## Target Behavior @@ -184,23 +184,15 @@ not verification of the unimplemented usage feature. ## Required Work -### Core API design checkpoint +### Composition boundary -The subsequent implementation plan will include a small proposed public core API -and a short ckprompt wiring example for review before plan approval. This design -checkpoint belongs to plan review; it will not introduce a separate approval gate -during implementation. Demonstrate captured invocation-wide flags, -context decoration at the `CheckInput`/`Run` boundary, and final presentation -through the existing reporter. Show how both ordinary installation paths support -application commands registered before and after ckprompt without application -accounting callbacks. - -Start with a per-invocation closure retaining integration-owned state, such as -the execution group, and assess whether it satisfies these needs directly. Avoid -introducing a public state registry, lifecycle object hierarchy, or configurable -middleware framework for this feature. Exact Go declarations and internal -factoring remain work for implementation planning; this roadmap does not select -them. +Core will provide captured invocation-wide flags, context decoration at the +`CheckInput`/`Run` boundary, and final presentation through the existing reporter. +Integration-owned state, such as the execution group, will remain in a +per-invocation closure. Both ordinary installation paths will support application +commands registered before and after ckprompt without application accounting +callbacks. A public state registry, lifecycle object hierarchy, or configurable +middleware framework is unnecessary for this capability. ### Core composition and reporting diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md new file mode 100644 index 0000000..32e0ec9 --- /dev/null +++ b/docs/roadmap/implementation.md @@ -0,0 +1,394 @@ +# Automatic Usage Reporting Implementation Plan + +Status: ready for review; implementation not started. + +## Scope and execution + +Implement the agreed [automatic usage reporting target](automatic-usage-reporting.md). +This document selects the core API, internal approach, and ordered work. Read the +[developer guide](../development.md) and applicable policies before editing. +The target audience is the Luna implementation agent; execute Stage 1 through Stage 8 +in order after approval of this plan. No stage requires another design approval. + +This is one end-to-end sprint. Intermediate stages may leave unresolved references +or failing builds while their collaborators are being implemented. Complete the +final validation before declaring the sprint finished. Add completion evidence to +each stage and commit completed, nonempty units under the agent policy. Keep +unrelated work intact. Do not push, publish releases, change sibling repositories, +or implement deferred scope as part of this sprint. + +The target roadmap owns behavior and intent. Concrete signatures and steps below +are the selected implementation approach, not current exported contracts. Routine +private factoring may change without reopening the agreed feature or inserting +approval gates. Keep GoDoc with the code it describes. + +## Baseline and selected design + +The planning baseline is core v0.7.0, ckconfig v0.10.0, ckprompt v0.11.0, and +PromptKit v0.24.0 selected in ckprompt. Target PromptKit v0.25.0, source commit +`207677e9948dc5699073a4d6620d21139033c72d`, using its published public API. +Core and all modules retain the current Go 1.27.0 minimum. + +Relevant implementation owners: + +- `command.go`, `registry.go`, `app.go`: captured declarations, atomic installation, + and routing snapshots. +- `internal/commandmeta`, `internal/cobra`, `flag_aliases.go`, and routing/help/ + completion code: neutral flag metadata, parsing, aliases, and discovery. +- `command.go`'s `typedCommand.prepare`: input construction and `CheckInput` are + inside its returned closure, before public `Run` or private builtin execution. +- `execute.go`, `reporter.go`, `report.go`: invocation state, finalization, + reporting destinations, rendering, and presentation failures. +- `integrations/ckprompt/command.go`, `declarations.go`, and `smoke_report.go`: + family assembly, convenience aliases, and explicit smoke projections. + +### Public core API + +Add these core-owned declarations, with private records behind the handle: + +```go +type InvocationFeature struct { /* private captured record */ } + +type InvocationFeatureSpec[I any] struct { + NewInput func() I + Flags []Flag[I] + Start func(Invocation, I) (context.Context, func() Report) +} + +func NewInvocationFeature[I any](spec InvocationFeatureSpec[I]) InvocationFeature +func WithInvocationFeature(command Command, feature InvocationFeature) Command +``` + +`NewInvocationFeature` captures flag metadata and callback references like command +factories. A nil `NewInput` uses the type's zero value. `Start` is required; +construction defects remain attached for installation to report. Reuse existing +binding validation and preparation instead of adding a second flag type system. +There are no feature operands, feature `CheckInput`, state registry, public +lifecycle hierarchy, or generic middleware chain. + +`WithInvocationFeature` returns a copied command record with the feature attached; +it does not mutate the original command. Its feature contributes application-wide +behavior when the containing declaration is installed. Collect attached features +from the installed command tree, not from a process-global registry. An absent +command contributes no capability; attached construction errors still follow +ordinary error-before-absence validation. An invalid zero feature is a wiring +error. Reused declarations remain reusable across applications. + +Once the selected command's input construction and `CommandSpec.CheckInput` +succeed, build fresh feature input from its captured converted values and call +`Start`. Each feature receives the invocation context produced by earlier features. +A nil returned context keeps the current context. A nil final-report function +means no report. Otherwise retain that function only for this invocation and +call it once during ordinary finalization, including returned failure/cancellation. +It returns a normal `Report`; core renders it as text on diagnostics after deferred +messages and before terminal explanations. Snapshotting thus occurs at reporting +finalization. This is a report producer, not an application cleanup hook. + +Use a deterministic private traversal order: canonical root paths sorted, children +in captured declaration order, attached features in attachment order. Deduplicate +reuse of the same captured feature handle within one application. Distinct handles +with competing flags are collisions, not last-writer selection. Use this order +for start and final-report callbacks. This needs only slices and a temporary set, +not a dependency/order configuration API. + +### ckprompt wiring + +Keep both factory signatures. Attach a newly captured feature once in the common +`buildCommand` nonempty-family path. The existing empty-suite branch stays absent +and retains its wiring errors. `Declarations` continues to return that command +plus its aliases. + +The following sketch identifies the complete integration boundary; the helper +names and private report DTO are implemented in Stage 6: + +```go +type usageInput struct { ShowTokens bool } + +feature := commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[usageInput]{ + Flags: []commandkit.Flag[usageInput]{ + commandkit.BoolFlag( + commandkit.FlagMeta{Name: "show-tokens", Usage: "Show token usage and available cost information after execution."}, + false, + func(input *usageInput, value commandkit.Supplied[bool]) { + input.ShowTokens = value.Value + }), + }, + Start: func(inv commandkit.Invocation, input usageInput) (context.Context, func() commandkit.Report) { + if !input.ShowTokens { return inv.Context, nil } + group := new(promptkit.ExecutionGroup) + ctx := promptkit.WithExecutionObserver(inv.Context, group.Observe) + smoke := inv.CanonicalPath() == "promptkit test" + return ctx, func() commandkit.Report { + return usageReport(group.Snapshot(), smoke) + } + }, +}) +return commandkit.WithInvocationFeature(family, feature) +``` + +The group lives in this invocation's closure. No engine loading, engine wrapping, +accounting map, local observer forwarding loop, or application callback is needed. +Canonical path selects only the explanatory smoke note, not observation eligibility. +The proposed API and wiring are reviewed with this plan, before implementation. + +## Stage 1: Capture features and validate their installation + +1. Add the selected public API, preferably in a focused root `invocation_feature.go`, + with private typed payloads analogous to `typedCommand`. Copy captured flag + collections; retain callbacks under existing caller-ownership rules. Add + GoDoc for installation scope, fresh invocation inputs, and report production. +2. Extend private command records with attached feature handles. Preserve existing + `WithError`, root-only family placement, child capture, and absence behavior. + Validate feature issues while validating the command tree. +3. Extend installation candidates and routing snapshots with collected features + and their neutral flag metadata. Collect from the entire prospective registry + on both construction and later `Register`, so installation order cannot alter + availability or collision handling. Commit registry changes only after all + candidate checks succeed. Do not mutate captured commands to inject flags. +4. Validate feature flags against help/reporting options, other feature flags, + and local long/short spellings on every command. Extend existing alias + validation to include feature flags as valid targets and to detect source + collisions or competing mappings; legitimate aliases to these flags remain + supported. There is no special shared + `show-tokens` application binding or debug-style coalescing. Without the + integration installed, that name remains available to applications. +5. Keep structural wiring errors operational/assembly errors and bad operator + values usage errors. Do not create a second declaration-registration system. + +Evidence: focused declaration/installation checks establish capture isolation, +empty-suite/absence behavior, reused handles across Apps, and failed-registration +rollback. Full parsing and dispatch checks follow their implementation stages. + +## Stage 2: Carry invocation flags through parsing, help, aliases, and completion + +1. Extend neutral command metadata with invocation-feature flags separate from + consumer-local flags and fixed reporting flags. Extend parser results with + corresponding raw values/spellings. Preserve the existing consumer binding + indexes and reporting selection semantics. +2. Build one effective flag view for each parser/help/completion context from + local, invocation, and core flags. Reuse `interpretFlagTokens`, ordinary pflag + construction, occurrence tracking, and typed binding preparation. Partition + values/occurrences by binding ownership; do not parse argv again in core or + ckprompt. Earlier malformed repeated occurrences remain errors under existing + parsing rules, even when a later occurrence is valid. +3. Carry the same feature flag view through canonical nodes, root/discovery help, + alias-only prefixes, scoped/global flag-alias resolution, generated help, + usage diagnostics, and completion suggestions. Update helpers that currently + assume only `ReportingFlags()` are invocation-wide. Keep flags after the full + command path under existing grammar; do not introduce persistent-flag grammar. +4. Prepare feature binding conversions before command input construction. Help + may validate supplied flag syntax but must not construct feature input or call + `Start`. Completion and generated builtin dispatch must not acquire providers. + +Evidence: parser/facade checks cover ordinary Boolean repetition/false, alias +spellings and `--`, unchanged local binding indexes, help/completion availability, +and collisions for both installation orders. Extend existing tests where their +boundary already owns the behavior rather than duplicating every grammar case. + +## Stage 3: Run features at the input boundary and finalize diagnostic reports + +1. Refactor the prepared command closure so feature startup occurs after input + construction and successful `CommandSpec.CheckInput`, immediately before `Run`. + Preserve existing input/classification behavior. Integration validation inside + `Run` is execution and retains the requested summary after failure. +2. Store converted feature inputs/start closures and final-report closures in + `execution`. Apply returned contexts to the invocation given to the handler, + including integration state factories/acquisition reached there. Never cache + input, contexts, groups, or finalizers in App/suite state. +3. Exclude generated help, version, and completion handlers from feature startup + using private builtin metadata, not arbitrary user command-name heuristics. + Also skip startup/final reports for routing, parsing, input-construction, and + `CommandSpec.CheckInput` failures. Leave panic behavior unchanged. +4. Add a private coordinated diagnostic-report rendering operation that takes a + normal `Report` and calls `RenderReport` with `FormatText`. Reuse destination + bookkeeping, short-write detection, render/write error separation, and + presentation-failure handling. Do not change the public `Report` shape or + `Reporter.Report`'s main-result semantics; no new public reporter method is + needed for the feature's returned report. +5. Extend reporter finalization to accept the invocation's final-report producers. + Close deferred-message admission and drain the existing batch, retain existing + handler-completion debug reporting, then produce/deliver the feature reports, + then apply presentation failure and terminal explanation handling. Invoke + integration report producers outside the reporter mutex; render their returned + reports through the coordinated locked operation. Do not let them reenter a + rendering callback on the same reporter. +6. Quiet suppresses delivery, not report preparation/rendering, matching the + existing output-failure contract. `--format` does not change these reports. + Retain the existing domain outcome/cause handling if the summary fails to + render or write. Finish reporting even after returned cancellation. + +Evidence: generic core fixtures prove exact callback boundary, per-invocation +isolation, returned context propagation, report ordering, no summary before Run, +and diagnostic render/write failure behavior without importing optional modules. + +## Stage 4: Verify the core contract through public assembly + +1. Complete external-package facade tests using a small core-only feature and + application command. Exercise `New` and later `Register`, both registration + orders, aliases, a reused declaration in two Apps, and successive executions + with different selections. Include no-feature behavior. +2. Cover the material lifecycle branches: rejected `CheckInput` never starts; + failure/cancellation within `Run` still reports; quiet suppresses irrespective + of flag order; ordinary/verbose/debug visibility; main JSON output unchanged; + deferred messages before summary and terminal explanation afterward. +3. Test rollback when adding a feature conflicts with existing commands and when + adding a command conflicts with an installed feature. A failed batch must leave + metadata, help, alias resolution, and later dispatch using the prior registry. +4. Cover diagnostic template failure, short/write failures, and preserved domain + cause/status through the existing presentation model. Test reported values and + ordering rather than an entire incidental help/report snapshot. +5. Run the core suite with Go 1.27.4. Preserve boundary checks: optional integration + imports/dependencies remain absent from core, including tests/examples/tools. + +Evidence: record the core suite result and focused cases in this stage. No new +concurrent-App-dispatch guarantee, benchmark gate, or public feature framework is +part of this work. + +## Stage 5: Adopt PromptKit v0.25.0 and preserve existing report evidence + +1. Select the published PromptKit v0.25.0 in ckprompt's module files; use no sibling + replacement. Preserve ConfigKit v1.4.0 and unrelated dependency selections. + Check the selected upstream notices and update the PromptKit attribution entry + to its exact source revision under the OSS policy. +2. Inspect native `BackendInspection` forwarding and retain `Provider` and + `ZeroCost`, including false. Review maintained backend fixtures and positional + literals/strict JSON decoders. Add explicit provider selections only where + needed for the fixture's intended upstream convention. Do not add local + authentication, pricing, provider inference, or zero-cost defaults. +3. Extend `smokeUsageDTO` and `smokeUsageFromNative` with `reasoning_tokens` using + the existing observed-count representation. Add `cache_hit_ratio` as a nullable + `*float64` from native `CacheHitRatio()`; nil means unavailable, and a present + zero stays present. Preserve the unrounded ratio in the DTO. +4. Supply text templates for single and aggregate smoke reports so available + ratios display as percentages with one decimal place. Preserve the existing + report's selected facts, targets, timing, attempts, errors, and availability; + this is a presentation change, not a smaller smoke report. Continue to route + all rendering through core. JSON/YAML retain numeric ratios and native count + state. With a template, the default smoke representation becomes text under + existing automatic format selection; document this change and retain explicit + `--format yaml`/`json` for structured output. +5. Keep smoke observation separate from ordinary groups. Do not add a smoke cost + field. Verify native provider/authentication applicability data flows through + current reports, including vLLM findings, without asserting upstream probe + correctness. + +Evidence: focused projection/render checks cover reasoning, nullable/zero ratio, +percentage precision, explicit false declarations, and existing smoke content in +single/aggregate text, JSON, and YAML. Run affected ckprompt tests in the workspace. + +## Stage 6: Install automatic observation and the invocation summary + +1. Implement the common-family feature attachment shown above. Retain both public + factory signatures, normal aliases, and the empty-suite early return. Declare + `--show-tokens` exactly as the target roadmap specifies, default false, no short + name, last occurrence wins. Construct no group when the feature is disabled. +2. In the enabled `Start`, allocate one native group and use its `Observe` method + with `WithExecutionObserver`. The final-report closure snapshots the group. + Do not aggregate usage from `RunResult`, wrap loaders, intercept engines, or + enroll smoke-test reports. +3. Add a private summary DTO retaining the native usage, cost, and coverage states; + derive prompt count as `len(summary.Members)` and carry `RepairCalls`. Use the + native aggregate cache helper, storing a nullable unrounded ratio. No attempt + or transient-retry display counts, event history, or model grouping are needed. +4. Build one standard text report headed `Observed PromptKit execution usage`. + Show prompts; show indented repair calls only when nonzero. Show prompt, + completion, and total tokens, with reasoning, cached, and cache-write tokens + as details. Show the available ratio with one decimal place as a percentage. +5. Text count formatting: unknown counts display `unknown`; known counts display + their value, with an `incomplete` indication when not complete. Retain the + underlying native data in the DTO. Always show terminal coverage as complete + or incomplete separately from usage/cost completeness. +6. Show cost as USD with six significant digits (`%.6g`) when known, labeling an + incomplete subtotal when appropriate, or `unknown` otherwise. Include the + native source when nonempty: provider, configured_zero, or mixed. Do not turn + an absent source into a provider/configured-zero assertion. Empty groups use + this same report with native zero totals and absent ratio/source. +7. Reuse small private token/cost/percentage template functions as useful; retain + raw values until text formatting. For canonical `promptkit test`, include the + note `Smoke-test usage is reported separately in the command report.` Keep + the ordinary summary even when it is empty. No extra warning or apology is + required. Preserve context and explicit-observer composition upstream. + +Evidence: adapter fixtures establish faithful rendering of empty, unknown, +reported-zero, configured-zero, mixed-source, incomplete, reasoning, and ratio +values. Zero repairs omit only the repair detail. Failures preserve observed data +and the command's outcome under core presentation rules. + +## Stage 7: Demonstrate and verify normal consumer installation + +1. Extend the maintained composed consumer rather than add another consumer. + Add an application-owned `pipeline run` command that loads its engine normally + and performs two prompt executions with `Invocation.Context`. Keep accounting, + final reporting, and observer setup out of the handler. +2. Extend its offline injected LLM client/fixtures with explicit native usage and + cost evidence. This evidence is supplied by the client, not a local estimate. + Keep existing example commands working. Do not add live inference or pricing. +3. Verify automatic flag availability and reports through both `Command` and + `Declarations`, and app commands registered before/after ckprompt. Include a + narrowed nonempty suite and an empty suite. Help and completion must not call + loaders/providers. Aliases must reach the same behavior. +4. Cover the native API handoff with a representative real-engine, multiple-call + fixture and an explicit request observer. Assert context reaches execution, + returned evidence is presented, and main output remains independent. PromptKit + owns tests of nested/concurrent accounting, retries, repairs, deduplication, + provider decoding, and cost aggregation; do not reproduce those domain suites. +5. Exercise returned handler failure/cancellation, an acquisition failure inside + Run, failure in core CheckInput, successive enabled/disabled executions, quiet, + main `--format json`, and smoke output with its separation note. Reuse narrower + core/projection coverage rather than multiply all combinations here. + +Evidence: an offline run of `pipeline run --show-tokens` reports two observed +prompts and native usage/cost automatically. With the flag absent/false there is +no invocation summary. Record the focused integration and consumer suite results. + +## Stage 8: Finish documentation, validation, and sprint records + +1. Update core and ckprompt GoDoc, CLI reference, consumer guide, and internal + inventory. Explain automatic installation, observer context responsibilities, + exact CheckInput/Run boundary, empty-suite absence, Boolean selection, visibility, + text-only diagnostic delivery, zero/unknown/incomplete states, smoke separation, + and the smoke default-text change. Keep upstream provider schemas/algorithms + linked to their owners. Update attribution and local links. +2. Use the developer guide's Go 1.27.4 toolchain. Preserve the ignored go.work and + go.work.sum. Run these workspace checks from the repository root: + + ```sh + GOTOOLCHAIN=local go test ./... + GOTOOLCHAIN=local go test ./integrations/ckconfig/... + GOTOOLCHAIN=local go test ./integrations/ckprompt/... + ``` + + Run the focused consumer commands with text and main JSON output, quiet, + disabled reporting, and smoke/report separation. Run affected suites once + after the final changes; repeat only where failures or later edits justify it. +3. Verify independent root and ckconfig builds with `GOWORK=off GOTOOLCHAIN=local`. + ckprompt now uses unpublished local core APIs; do not claim its current + published core requirement independently supplies them. Use a temporary + modfile, `GOWORK=off`, and temporary replacements for the local core/ckconfig + solely to validate isolated ckprompt build/test behavior in this sprint. Keep + PromptKit at the published v0.25.0. Do not commit replacements or temporary + files. This check is not the released-dependency check. +4. Preserve existing published core/ckconfig requirements until release preparation + selects new published versions. Document the temporary workspace requirement + for the unreleased integration in developer guidance. Leave publication out of + this sprint: release core, align/release ckconfig, then align/release ckprompt + under the release policy. Independent ckprompt tests against those published + dependencies are required before its release, not an implementation-stage + wait for upstream publication. Do not invent release version numbers here. +5. Check `gofmt` on changed Go files, relevant diffs, local documentation links, + `git diff --check`, and optional-dependency boundaries. Record actual commands, + results, and the distinction between local-source and published-dependency + validation. Do not add mandatory live, benchmark, shell-matrix, or race gates + without a concrete new concern. +6. Mark the stages complete with concise evidence. Keep implementation/target + records until the finished sprint has been reviewed; subsequent cleanup can + retire completed records and preserve deferred scope in future.md. Commit the + final nonempty unit with a plain-English message. Report any release follow-up + separately from completion of the implementation work. + +## Open Questions + +None required before implementation. Plan approval selects the proposed API, +closure-based state, builtin exclusions, diagnostic report handoff, and smoke +text-template behavior described above. Exact private helper/file names and +noncontractual whitespace remain ordinary implementation choices.