Files
commandkit/docs/roadmap/automatic-usage-reporting.md

333 lines
19 KiB
Markdown

# Automatic PromptKit Usage Reporting
Status: implemented; retained for review. See the implementation record for
validation and release follow-up.
## Purpose
Normal ckprompt installation will make optional invocation-wide token and cost
reporting available to application-owned commands and the PromptKit command
family. Operators will be able to request a summary of a review or pipeline run
without applications implementing their own accounting infrastructure.
Applications will continue to pass `Invocation.Context` through their work and
wait for work they own before returning. They will not need per-command usage
flags, request observers, accounting groups, execution wrappers, snapshots, or
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.
The [implementation plan](implementation.md)
owns the concrete API, wiring example, ordered stages, and validation steps.
## Target Behavior
### Installation and flag selection
Both `ckprompt.Command` and `ckprompt.Declarations` will automatically install
usage support for ordinary nonempty suites. The capability will apply to
application-owned commands regardless of whether they are registered before or
after the integration. Consumers will use normal application assembly without
a special usage-enabled factory or a wrapper around `App.Execute`. Preserve
existing factory signatures where practical and assess source compatibility
before any signature change.
Importing ckprompt alone will install nothing. An empty suite will continue to
install no command, namespace claim, or usage capability. Usage support will not
depend on an engine-loader wrapper or a particular inspection callback.
The invocation-wide flag will be `--show-tokens`, a Boolean defaulting to false,
with no shorthand. Explicit `--show-tokens=false` will be supported; the last
supplied value will win when repeated. It will use the existing typed parsing,
help, and completion conventions. Its help text will be:
> Show token usage and available cost information after execution.
Installation will make reporting available; a summary will be produced only
when requested.
### Invocation scope
For an enabled invocation, ckprompt will create one native PromptKit
`ExecutionGroup` and attach its observer through `WithExecutionObserver` to the
invocation context. This will happen after successful input construction and
`CommandSpec.CheckInput`, before the selected command's `Run` callback. Integration
state initialization and acquisition within `Run` will therefore participate
alongside application handler work. Input construction and `CheckInput` remain
outside observation.
Validation performed inside `Run`, including integration validation, is execution
for this purpose. A failure there will still produce the requested summary; core
does not identify or move arbitrary validation inside handlers. The composition
hook must respect the `CheckInput`/`Run` boundary rather than wrap the entire
prepared execution, which currently includes `CheckInput`.
Calls using that context will participate through PromptKit's public observation
boundaries, including nested and concurrent calls, multiple engines, prepared
executions, and coordinated continuations. No particular engine instance or
construction adapter will be required. Calls using unrelated contexts will
remain outside the scope. Existing explicit request observers will continue to
compose according to the upstream contract.
On command completion, including returned failure or cancellation, ckprompt will
snapshot the group and submit its summary before reporting closes. Observation
will not require a successful `RunResult`. Groups will remain private to their
invocations rather than being cached on reused engines or suites or retained in
process-wide history.
Help, completion, version, routing errors, parsing errors, and failures in input
construction or `CommandSpec.CheckInput` will produce no usage summary and perform
no acquisition for reporting. Installation and help will not invoke engine loaders
or providers.
Application startup, context propagation, and waiting for application-owned work
remain application responsibilities. This feature does not change panic recovery,
process-lifetime behavior, or concurrent `App.Execute` support.
### Summary delivery
The requested summary will be concise text on the application's diagnostic
destination, normally stderr. It will be visible in ordinary, verbose, and debug
modes without another flag. Active quiet mode will suppress it regardless of the
position of `--show-tokens`, consistent with explicit progress reporting.
The summary will follow normal command output and deferred messages and precede
any terminal failure explanation. It will supplement the application result,
preserving its outcome, explanation, and supported error identity. Summary
rendering and delivery failures will use the existing core
[presentation-failure model](../cli.md#output-failures), including when the
command has already failed.
Usage text will be independent of `--format`, which will continue to govern the
command's main result. Application result shapes and stdout will remain
unchanged. ckprompt will supply summary content and its text template; core will
handle rendering, visibility, delivery, and finalization through the application's
selected streams.
### Summary content
The summary will present native invocation totals with the following detail:
| Content | Presentation |
| --- | --- |
| Prompts | Number of observed prompt executions, using the native group's observed run count. |
| Repair calls | A detail beneath the prompt total, shown only when nonzero. |
| Tokens | Aggregate prompt, completion, and total tokens, with reasoning, cached, and cache-write tokens as details. |
| Cache-hit ratio | The native `Usage.CacheHitRatio()` result when available, displayed as a percentage with one decimal place. |
| Cost | Available USD cost with its native source, displayed with six significant digits. |
| Availability and completeness | Clear indications of unknown values, incomplete subtotals, and incomplete terminal coverage. |
The prompt count measures executions, not distinct prompt definitions or provider
requests. Repeated execution of one prompt increases the count; transient retries
and repairs within an execution do not. Attempts and transient retries will not
be separate display counts. Reasoning and cache figures will not be added to
total tokens. Cache-hit ratio will use the native aggregate helper rather than
an average of per-run ratios or an independently derived value.
Cost will appear automatically when available, without a separate accounting
opt-in. Preserve provider/injected-client reports, configured-zero evidence,
mixed sources, and the absence of a sourced contribution according to the native
API. Preserve the unrounded upstream value during adaptation; six significant
digits is a text presentation choice. No local pricing inference or billing
guarantee will be added.
An invocation with no observed executions will receive the same standard report,
using native empty-group zero totals for prompts, tokens, and cost and preserving
the absence of a cost source. Derived values such as cache-hit ratio will remain
unavailable when upstream supplies no value. Observed executions with unknown
usage will retain their unknown state rather than being converted to zeros.
Known zeros, incomplete subtotals, and terminal coverage will retain their
distinct meanings after failures as well as successes.
Label the summary as usage from observed PromptKit executions. For smoke
commands, state that smoke-test usage is reported separately in the command's
main report. Retain the standard empty-group summary when no ordinary executions
were observed; its zeros must not be presented as measured smoke-test usage or
cost.
## Upstream and Current Baseline
The target dependency is `go.maximumdirect.net/promptkit v0.25.0`, released at
commit `207677e9948dc5699073a4d6620d21139033c72d`. Its annotated tag was verified
against the upstream remote. The [release notes][promptkit-release] and tagged
public API are the adoption baseline; no upstream feature work remains a
prerequisite. Sibling checkouts are review evidence, not build dependencies.
The released APIs supply the accounting needed for this feature:
- [Contextual observation][promptkit-observations] supplies
`WithExecutionObserver(context.Context, ExecutionObserver) context.Context`.
Prepared executions select contextual observers when run, while explicit
request observers remain intact.
- [Execution groups][promptkit-groups] supply `Observe(ExecutionEvent)` and
`Snapshot() ExecutionGroupSummary`. The detached summary supplies members,
terminal coverage, execution counts, token usage, and cost. PromptKit owns
aggregation and duplicate accounting; ckprompt will use the snapshot rather
than summing attempt, result, and terminal totals locally.
- `ObservedTokenUsage` includes `ReasoningTokens` and the native cache-hit-ratio
helper. [Cost metadata][promptkit-cost] supplies `ObservedCost` with `Value`,
`Known`, `Complete`, and `Source`. Group accounting remains the invocation
source because failed calls return no partial result and `RunResult.Usage`
uses different successful-generation accounting.
CommandKit currently selects PromptKit v0.24.0. Core v0.7.0 carries context in
[Invocation](../../identity.go), but its [execution path](../../execute.go)
finalizes reporting internally without a public extension for this capability.
ckprompt v0.11.0 installs inspection and smoke commands through
[Command](../../integrations/ckprompt/command.go) and
[Declarations](../../integrations/ckprompt/declarations.go); neither currently
adds observation to application-owned commands.
The existing independent ckprompt suite previously passed against released
PromptKit v0.25.0 using temporary module files and other published dependencies.
Tracked module files were unchanged. That establishes a compatibility baseline,
not verification of the unimplemented usage feature.
## Required Work
### Composition boundary
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
Add the narrow, library-neutral public composition capability needed to capture
invocation-wide flags, decorate context at the selected execution boundary,
retain private invocation state, and submit final presentation before reporting
closes. Include the generic reporting support needed for requested summaries to
be visible in ordinary mode; ordinary Info messages are hidden without verbose
mode and cannot provide the selected behavior alone. Reuse the existing `Report`
handoff, text templates, rendering, and presentation-failure handling for
requested diagnostic reports. Keep existing Info visibility and Progress
controls unchanged; neither provides the requested summary's visibility policy.
Use the existing reporter finalization sequence to deliver the summary after
deferred messages and before terminal explanations. Core owns this timing and
delivery; ckprompt supplies the content and template.
Validate captured flags and lifecycle behavior with the installation batch so a
failed registration leaves no partial installation. Apply the capability to
application commands in either registration order. Preserve aliases, help,
completion, typed bindings, and existing installation collision handling through
the normal CLI machinery.
Keep the mechanism proportionate to this use case. Core must remain independent
of PromptKit and ckprompt in public signatures, implementation, tests, examples,
tools, and module requirements. The integration will not parse raw arguments
again or introduce a separate rendering pipeline, general application runtime,
dependency-injection system, or plugin framework.
### ckprompt adoption and report adaptation
Adopt PromptKit v0.25.0 and connect both ordinary installation paths to the core
capability. Implement invocation-scoped observation and the agreed summary using
the native group, token, ratio, and cost APIs. PromptKit will retain ownership of
event generation, observer composition, accounting, provider decoding, and cost
interpretation; CommandKit will own CLI coordination and faithful presentation.
The release also changes native [backend settings][promptkit-backends]. Forward
`BackendInspection.Provider` and `ZeroCost` declarations, including explicit
false, without manufacturing defaults in inspection reports. Provider selection
is explicit and controls upstream usage/cost decoding and authentication
conventions. Preserve native support and applicability findings, including the
vLLM authentication adapter. Configuration inspection will continue to expose
upstream safe evidence and history. No new provider-selection CLI flags, loader
wrappers, or local zero-cost defaults are needed.
Review maintained backend fixtures and adoption guidance against the released
provider and authentication conventions. Application-defined OpenRouter
backends must explicitly select `provider: openrouter` to use those conventions;
backend names and endpoint hostnames do not select them. Native `zero_cost`
fallback and reported-cost precedence remain upstream behavior. The Go consumer
minimum remains 1.27.0, and upstream dependencies, including ConfigKit v1.4.0, are
unchanged from v0.24.0. Review positional struct literals and strict result
decoders for added fields and native JSON cost/reasoning data.
Extend the existing [smoke usage projection](../../integrations/ckprompt/smoke_report.go)
to preserve native `ReasoningTokens` in attempt and aggregate reports. Include
cache-hit ratio through the same native helper and percentage presentation used
for invocation summaries, retaining native values in adaptation.
Smoke diagnostics will retain their separate upstream reporting model; ordinary
context observation does not enroll them. Do not add their usage to an execution
group or interpret an empty ordinary group as a measurement of smoke usage.
PromptKit v0.25.0's `SmokeTestReport` has no cost field; the adoption will not
fabricate one from group summaries or token counts.
### Consumer evidence, documentation, and release alignment
Extend the maintained [composed consumer](../../integrations/ckprompt/examples/composed)
with an application-owned pipeline command demonstrating automatic flag
availability and final usage reporting without accounting code in its handler.
Use offline injected-client evidence to demonstrate CommandKit's contribution.
As implementation lands, update owning GoDoc, the [CLI reference](../cli.md),
[consumer guidance](../consumers/guide.md), and [internal inventory](../internal/overview.md).
Document the chosen CLI behavior, public composition contract, context lifecycle,
report changes, and applicable upstream adoption effects in their canonical
owners. Review dependency alignment and [attribution](../oss/attribution.md).
Core changes will require a core release and downstream integration releases
under the [dependency alignment policy](../policy/release.md#commandkit-downstream-dependency-alignment).
Publication follows the [release order](../release.md#scope-and-release-order)
with integrations selecting the published dependencies. ckconfig needs alignment,
not usage functionality. Exact release versions and publication are separate
release work.
## Completion Evidence
Completion will require a normally installed ckprompt integration and an
application-owned pipeline command whose requested summary needs no per-request
observers, local accounting state, or final reporting callback. Verify both
assembly paths and commands registered before and after the integration.
Focused core checks will cover atomic installation, typed Boolean selection,
context decoration at the selected boundary, invocation isolation, finalization
order, mode visibility, and rendering/delivery failures. Integration checks will
cover context forwarding and faithful summary presentation: prompt counts,
conditional repair details, token fields, cost sources and precision, ratio
presentation, empty groups, unknown/incomplete evidence, and available data after
failure or cancellation. Verify preserved application outcomes and supported
error identity.
Verify help, completion, version, routing/parsing errors, and failures in input
construction or `CommandSpec.CheckInput` without usage summaries or acquisition
for reporting. Distinguish these from validation failures returned inside `Run`,
including integration validation, which retain the requested summary. Verify
explicit-observer coexistence, smoke reasoning and ratio
adaptation, clear separation of smoke usage from ordinary execution summaries,
and preservation of explicit provider/zero-cost inspection evidence.
Keep checks offline and test CommandKit-owned integration behavior. A real
upstream engine can support representative consumer evidence; PromptKit retains
tests for its accounting, retries, repairs, and provider decoding. Run affected
core and nested-module suites using the [developer guide](../development.md),
including independent builds against released dependencies before release.
Live inference, benchmarks, and a new concurrent-dispatch guarantee are not
required.
After completion, retire this roadmap and preserve unfinished scope in
[future work](future.md).
## Deferred Scope
A machine-readable usage-output interface is deferred until a concrete consumer
needs it. It will require an explicit destination and framing because the
diagnostic stream may contain other messages. No additional JSON/YAML document
or modification of arbitrary application result shapes is part of this feature.
A separate usage-only installation API, per-model breakdowns, event traces, and
persistent history are also deferred. The initial feature will use normal
nonempty ckprompt installation and the native invocation summary.
[promptkit-release]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/releases/v0.25.0.md
[promptkit-observations]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/observations.go
[promptkit-groups]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/execution_group.go
[promptkit-cost]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/cost.go
[promptkit-backends]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md#backend-definitions