26 KiB
Automatic Usage Reporting Implementation Plan
Status: ready for review; implementation not started.
Scope and execution
Implement the agreed automatic usage reporting target. This document selects the core API, internal approach, and ordered work. Read the developer guide 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'stypedCommand.prepare: input construction andCheckInputare inside its returned closure, before publicRunor private builtin execution.execute.go,reporter.go,report.go: invocation state, finalization, reporting destinations, rendering, and presentation failures.integrations/ckprompt/command.go,declarations.go, andsmoke_report.go: family assembly, convenience aliases, and explicit smoke projections.
Public core API
Add these core-owned declarations, with private records behind the handle:
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:
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
Complete. Captured features, installation-wide collision and alias validation,
reusable handles, absence handling, and atomic registration are covered by
TestInvocationFeature*; the core GOTOOLCHAIN=local go test ./... suite passed
with Go 1.27.4.
- Add the selected public API, preferably in a focused root
invocation_feature.go, with private typed payloads analogous totypedCommand. Copy captured flag collections; retain callbacks under existing caller-ownership rules. Add GoDoc for installation scope, fresh invocation inputs, and report production. - 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. - 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. - 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-tokensapplication binding or debug-style coalescing. Without the integration installed, that name remains available to applications. - 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
Complete. Invocation metadata and raw values remain separate from local bindings; focused feature tests exercise aliases, repeated values, conversion errors, help and completion, and the Go 1.27.4 core suite passes.
- 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.
- 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. - 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. - 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
Complete. Core lifecycle tests verify input and context ordering, builtin and preflight exclusions, deferred/summary/terminal ordering, quiet rendering, and diagnostic failures with preserved domain outcomes. Go 1.27.4 core tests pass.
- Refactor the prepared command closure so feature startup occurs after input
construction and successful
CommandSpec.CheckInput, immediately beforeRun. Preserve existing input/classification behavior. Integration validation insideRunis execution and retains the requested summary after failure. - 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. - 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.CheckInputfailures. Leave panic behavior unchanged. - Add a private coordinated diagnostic-report rendering operation that takes a
normal
Reportand callsRenderReportwithFormatText. Reuse destination bookkeeping, short-write detection, render/write error separation, and presentation-failure handling. Do not change the publicReportshape orReporter.Report's main-result semantics; no new public reporter method is needed for the feature's returned report. - 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.
- Quiet suppresses delivery, not report preparation/rendering, matching the
existing output-failure contract.
--formatdoes 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
Complete. External-package tests cover both registration orders, aliases,
reuse, isolation, quiet, JSON, rejection, failure and rollback. Core lifecycle
tests cover diagnostic render and short-write failures. The Go 1.27.4 core suite
passes; GOWORK=off go list -deps -test ./... contains no optional modules.
- Complete external-package facade tests using a small core-only feature and
application command. Exercise
Newand laterRegister, both registration orders, aliases, a reused declaration in two Apps, and successive executions with different selections. Include no-feature behavior. - Cover the material lifecycle branches: rejected
CheckInputnever starts; failure/cancellation withinRunstill reports; quiet suppresses irrespective of flag order; ordinary/verbose/debug visibility; main JSON output unchanged; deferred messages before summary and terminal explanation afterward. - 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.
- 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.
- 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
Complete. Selected the published module and checked its license notice; ckprompt forwards provider and explicit false zero-cost inspection data. Smoke projection/render tests cover reasoning, absent and zero ratios, percentages, and retained single/aggregate evidence in text, YAML, and JSON. The affected Go 1.27.4 workspace suite passes.
- 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.
- Inspect native
BackendInspectionforwarding and retainProviderandZeroCost, 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. - Extend
smokeUsageDTOandsmokeUsageFromNativewithreasoning_tokensusing the existing observed-count representation. Addcache_hit_ratioas a nullable*float64from nativeCacheHitRatio(); nil means unavailable, and a present zero stays present. Preserve the unrounded ratio in the DTO. - 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/jsonfor structured output. - 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
Complete. Nonempty family assembly attaches the native context observer; summary tests cover empty, unknown, zero, incomplete, mixed-source, reasoning, ratio, repair, coverage, and smoke-separation representations. The ckprompt workspace suite passes with Go 1.27.4.
- Implement the common-family feature attachment shown above. Retain both public
factory signatures, normal aliases, and the empty-suite early return. Declare
--show-tokensexactly as the target roadmap specifies, default false, no short name, last occurrence wins. Construct no group when the feature is disabled. - In the enabled
Start, allocate one native group and use itsObservemethod withWithExecutionObserver. The final-report closure snapshots the group. Do not aggregate usage fromRunResult, wrap loaders, intercept engines, or enroll smoke-test reports. - Add a private summary DTO retaining the native usage, cost, and coverage states;
derive prompt count as
len(summary.Members)and carryRepairCalls. 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. - 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. - Text count formatting: unknown counts display
unknown; known counts display their value, with anincompleteindication when not complete. Retain the underlying native data in the DTO. Always show terminal coverage as complete or incomplete separately from usage/cost completeness. - Show cost as USD with six significant digits (
%.6g) when known, labeling an incomplete subtotal when appropriate, orunknownotherwise. 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. - Reuse small private token/cost/percentage template functions as useful; retain
raw values until text formatting. For canonical
promptkit test, include the noteSmoke-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
- Extend the maintained composed consumer rather than add another consumer.
Add an application-owned
pipeline runcommand that loads its engine normally and performs two prompt executions withInvocation.Context. Keep accounting, final reporting, and observer setup out of the handler. - 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.
- Verify automatic flag availability and reports through both
CommandandDeclarations, 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. - 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.
- 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
-
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.
-
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:
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.
-
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. -
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.
-
Check
gofmton 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. -
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.