Files
commandkit/docs/roadmap/implementation.md

446 lines
27 KiB
Markdown

# Automatic Usage Reporting Implementation Plan
Status: implementation complete; retained for review.
## 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
**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.
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
**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.
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
**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.
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
**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.
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
**Complete.** Selected the published module and checked its license notice;
ckprompt forwards provider and explicit false zero-cost inspection data. An
offline native vLLM authentication fixture confirms supported, applicable, and
accepted-credential findings reach the command report. 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.
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
**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.
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
**Complete.** The offline composed pipeline reports two executions, 28 tokens,
and USD 0.0025 from the injected client. Consumer tests exercise both assembly
paths and registration orders, explicit observer composition, empty suites,
help/completion, failure, quiet, JSON, disabled reporting, and smoke aliases.
The ckprompt and composed-consumer workspace suites pass with Go 1.27.4.
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
**Complete.** Updated GoDoc, CLI and consumer guidance, internal inventory, and
workspace instructions. Go 1.27.4 passed the three workspace `go test` suites;
independent root and ckconfig suites passed with `GOWORK=off`. An isolated
ckprompt suite passed with a temporary modfile replacing core and ckconfig with
local sources and selecting published PromptKit v0.25.0. Offline pipeline text,
JSON, quiet and disabled runs passed; smoke separation passed using the injected
consumer fixture. Formatting, local links, dependency boundaries and diff checks
were reviewed. Final validation also fixed required invocation flags blocking
generated version or group help.
Release follow-up: publish core, align and publish ckconfig, then align ckprompt
with the published releases and run its independent suite against those versions
before publishing. No release versions or publication are selected here.
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.