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

356 lines
20 KiB
Markdown
Raw Normal View History

# Automatic PromptKit Usage Reporting
Status: adoption goal agreed; upstream v0.25.0 reviewed and available;
OD-1 through OD-4 selected; OD-5 and OD-6 open; implementation not started.
## Goal
Normal ckprompt installation should make an optional usage-reporting flag
available to application-owned commands as well as the PromptKit command family.
When an operator selects the flag, CommandKit should collect and present usage
for PromptKit executions in that invocation automatically.
Applications must not need to declare the flag on each command, attach observers
to individual requests, create accounting groups, wrap execution methods, take
snapshots, or add final reporting callbacks. Importing ckprompt alone continues
to install nothing; the integration participates through ordinary application
assembly. Merely exposing a report adapter would not meet this goal.
Audita review commands and Notarius pipelines motivate the feature. Their domain
execution remains application-owned. Applications continue to pass
`Invocation.Context` through their work and wait for work they own before
returning. PromptKit calls using unrelated contexts are outside the observation
scope. No engine-construction adapter or particular engine instance is required.
This roadmap records the adoption strategy and open decisions. It is not an
implementation plan or a current CLI/API contract.
## Upstream Dependency
Target `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
replace the earlier upstream proposal as the adoption baseline. The upstream
availability dependency is resolved; CommandKit's module selection remains
v0.24.0 until implementation.
### Released observation and accounting API
The [observation API][promptkit-observations] provides:
```go
func WithExecutionObserver(ctx context.Context, observer ExecutionObserver) context.Context
```
ckprompt can associate an existing `ExecutionGroup` with the invocation context.
Ordinary runs, nested and concurrent calls, multiple engines, prepared executions,
and coordinated continuations participate through upstream execution boundaries.
Explicit request observers run before contextual observers, which compose in
registration order; a nil contextual observer leaves the context unchanged.
Prepared handles retain explicit request observers but select contextual
observers when executed. No per-engine installation is needed.
The released [group API][promptkit-groups] supplies `Observe(ExecutionEvent)` and
`Snapshot() ExecutionGroupSummary`. The detached snapshot exposes `Members`,
`TerminalCoverageComplete`, `Attempts`, `TransientRetries`, `RepairCalls`, `Usage`,
and `CostUSD`. It counts each run's first terminal event once. Coverage of members
and completeness of their reported usage/cost are separate facts. Use this
snapshot as the summary source, including after a returned failure; do not add
per-attempt, per-result, or terminal totals together locally.
`ObservedTokenUsage` includes `ReasoningTokens` in addition to the existing token
categories. Reasoning is a subset of completion tokens, and cache reads/writes
do not add to token totals. Its `CacheHitRatio() (float64, bool)` derives the
ratio from complete, consistent input/cache-read counts; use that native helper
if the selected presentation includes a ratio.
[Cost metadata][promptkit-cost] uses `ObservedCost` with `Value float64`, `Known`,
`Complete`, and `Source`. It appears as `CostUSD` on execution events, group
summaries, and successful `RunResult` values; injected clients may supply
`GenerateResponse.CostUSD` as `*float64`. Cost sources distinguish provider or
injected-client reports, configured-zero fallback, mixed contributions, and no
sourced contribution. Retain those distinctions rather than labeling every known
amount as a provider charge. Result cost is available without observation;
invocation accounting should still use the group because errors return no partial
result and `RunResult.Usage` has different successful-generation accounting.
PromptKit owns event generation, observation scope, aggregation, duplicate
accounting, token presence/completeness, and cost interpretation. Reuse its public
contracts without adding local accounting, provider decoding, or pricing logic.
Sibling checkouts are review evidence, not build dependencies.
### Released configuration and compatibility changes
The final release expands the original proposal. Its
[backend settings][promptkit-backends] select provider conventions explicitly:
`provider` supports `openai-compatible`, `openrouter`, and `vllm`. Omitted, null,
or blank selects generic OpenAI-compatible behavior. Backend names and endpoint
hostnames do not select provider conventions. The bundled OpenRouter definition
already selects `openrouter`; application-defined OpenRouter backends must select
it explicitly for provider-specific usage, cost, and authentication defaults.
Optional `zero_cost: true` supplies an upstream zero fallback when no usable
charge is reported. A usable reported amount, including zero, takes precedence.
Do not add a ckprompt default that declares local or otherwise unreported work
free. Present configured-zero evidence with its native source attribution.
Provider selection also controls native reasoning/cache-field mappings and
authentication defaults. OpenRouter defaults to `openrouter_key`, vLLM to the new
`vllm_models` adapter, and generic backends have no authentication default.
Omitted/null authentication configuration uses the provider default; `kind: none`
declares authentication inapplicable. These diagnostics still run only when
explicitly requested. Forward selections and native findings without implementing
provider policy in CommandKit.
The Go consumer minimum remains 1.27.0 and upstream dependencies, including
ConfigKit v1.4.0, are unchanged from v0.24.0. Public structs gained fields and native
JSON adds cost and reasoning usage. Review positional literals and strict result
decoders, and document applicable report/configuration changes during adoption.
## Current CommandKit Baseline
- Core v0.7.0 owns dispatch, typed input, reporting, and outcomes. Its
[execution path](../../execute.go) finalizes reporting internally and exposes
no public invocation extension for this use case.
- [Invocation](../../identity.go) already carries the execution context.
- ckprompt v0.11.0 installs inspection and smoke-test commands through
[Command and Declarations](../../integrations/ckprompt/command.go). The family
does not currently add observation to application-owned commands.
- [Suite](../../integrations/ckprompt/adapters.go) capabilities can be narrowed;
an empty suite currently yields an absent command. Existing construction,
registration, namespace, and absence contracts must be considered deliberately.
- Core [reporting](../cli.md#reporting) separates command results from diagnostics
and preserves application outcomes when presentation fails.
The existing ckprompt independent suite passed against released PromptKit v0.25.0
using temporary module files and the other published dependencies. Tracked module
files were unchanged. This is a baseline compatibility check, not verification
of the planned usage integration, which does not yet exist.
## Adoption Strategy
### Core invocation integration
Add a narrow, library-neutral capability sufficient for ckprompt to register an
invocation-wide flag, decorate the context before execution work begins, retain
private invocation state, and submit final presentation before reporting closes.
Choose its public shape under OD-2 below. Core must not import PromptKit or ckprompt,
including through its tests, examples, tools, or module requirements.
Capture this behavior through supported installation contracts. Validate it with
the installation batch so a failed registration does not partially install flags
or lifecycle behavior. Apply it to applicable application commands regardless of
their registration order. Preserve help, completion, aliases, typed bindings,
and ordinary installation collision handling through the existing CLI machinery.
Do not parse raw arguments again inside ckprompt or require consumer wrappers
around `App.Execute`.
Keep the mechanism proportionate to this need rather than introducing a general
application runtime, dependency-injection system, or plugin framework.
### ckprompt observation and final reporting
Normal installation registers the usage capability automatically. When the flag
is enabled, ckprompt creates one native `ExecutionGroup` for that invocation and
decorates its context with the upstream helper. Create the scope early enough
for application initialization and acquisition callbacks reached during command
execution to receive it, as well as the main handler. Do not invoke engine
loaders or providers merely to install the capability or display help.
On ordinary command completion, including returned failure or cancellation,
snapshot the group and submit the selected summary through core reporting before
the reporter closes. The collection does not require a successful `RunResult`.
Keep each invocation's group separate; do not retain a process-wide history or
cache a group on a reused engine or suite.
Delegate composition, concurrency within the pipeline, and accounting to
PromptKit. Do not accumulate attempt and terminal usage locally or discover and
intercept arbitrary engine calls. This work does not establish concurrent
`App.Execute` support or change panic recovery and process-lifetime contracts.
### Report content and delivery
Expose the upstream token categories and available USD cost, keeping unknown
values, reported or configured zero, cost sources, incomplete subtotals, and
terminal coverage distinct. Select presentation under OD-3 through OD-6. Describe
these facts neutrally using the adopted upstream meaning; no local pricing inference or
billing guarantee is needed. Do not round cost during adaptation; any text
display precision is a presentation choice.
The summary supplements the application result. Preserve its outcome, explanation,
and supported error identity. Report output failures through the existing
presentation-failure model, including when the command already failed. Do not
append prose to an application's JSON result or write directly to process stderr
outside the application's selected streams and core reporting lifecycle.
### Existing report adaptation
Backend inspection already forwards native `BackendInspection`; preserve its new
`Provider` and `ZeroCost` declarations, including explicit false, without
manufacturing runtime defaults in inspection reports. Configuration inspection
continues to expose upstream safe evidence and history. No new provider-selection
CLI flags or loader wrappers are needed for this adoption.
The explicit [smoke usage projection](../../integrations/ckprompt/smoke_report.go)
currently lists five token fields. Extend it to retain native `ReasoningTokens`
in attempt and aggregate reports rather than silently dropping that added field.
Use OD-6 to decide cache-ratio presentation consistently across usage reports.
Smoke diagnostics retain their separate upstream reporting model and are not
enrolled in ordinary context observation. Do not add their reported usage to an
execution group or imply that an empty ordinary group measures smoke-test usage.
v0.25.0's `SmokeTestReport` has no cost field; do not fabricate one from an
execution summary or attempt to infer it from token counts. Existing authentication
diagnostics should continue to expose native support and applicability findings,
including the new vLLM adapter, through the current smoke command.
## Decisions
OD-1 through OD-4 are selected below. Recommendations under OD-5 and OD-6
remain proposals, not selected contracts. Resolve the remaining choices before
writing a concrete implementation plan; implementation should then be able to
proceed through that plan without intermediate design gates.
### OD-1: Flag name and selection — selected
Use `--show-tokens` as a Boolean flag, defaulting to false, with no shorthand.
Support `--show-tokens=false`; the last supplied value wins when repeated.
Use the existing typed parsing and help/completion conventions. Help text:
"Show token usage and available cost information after execution."
Automatic availability does not mean printing a summary when the operator has
not requested it.
### OD-2: Installation API and capability availability — selected
Both `ckprompt.Command` and `ckprompt.Declarations` automatically install usage
support for the PromptKit family and application-owned commands. Consumers need
no special factory or execution wrapper. Preserve existing factory signatures
where practical; assess source compatibility before any signature change.
Core supplies a small, library-neutral composition mechanism for invocation-wide
flags, context decoration, and final reporting. ckprompt owns PromptKit observation
and summary content. The mechanism must not depend on wrapping the engine loader
or on enabling a particular inspection callback.
Preserve empty-suite absence behavior: an empty suite installs no command,
namespace claim, or usage capability. Defer a separate usage-only installation
API until there is a concrete need. Automatic usage support applies to ordinary
nonempty installations.
### OD-3: Output destination, visibility, and finalization order — selected
Present the requested summary on the application's diagnostic destination,
normally stderr, preserving the result stream for application output. Show it in
ordinary, verbose, and debug modes without requiring another flag. Use a small,
generic core reporting capability: an ordinary Info message is insufficient
because it is hidden without verbose mode. ckprompt supplies the summary content
through that capability.
Active quiet mode suppresses the summary regardless of the position of
`--show-tokens`, consistent with the existing explicit-progress behavior.
Present the summary after normal command output and deferred messages, but
before any terminal failure explanation.
Still report observed usage after returned errors or cancellation. Route summary
delivery failures through core's existing presentation-failure handling,
preserving the application outcome. Commands that do not reach execution and
empty observation scopes remain subject to OD-5.
### OD-4: Text and structured summary access — selected
The initial summary is text on the diagnostic stream selected under OD-3.
`--show-tokens` produces the same concise text summary regardless of `--format`;
that flag continues to govern the command's main result. Usage reporting leaves
application result shapes and stdout unchanged. ckprompt supplies the summary
content and text template; core handles rendering and delivery.
Defer a machine-readable usage-output interface until a concrete consumer needs
it. Such an interface needs an explicit destination and framing, because the
diagnostic stream may also contain other messages. A separate report file is a
possible future approach, not a selected interface.
### OD-5: No observations and commands that do not execute models
Decide what an explicitly requested summary shows when no ordinary execution
events were observed, including inspection-only commands or early returned
failures. Recommend a concise "No PromptKit executions observed" message rather
than an unlabeled zero-cost total; retain upstream empty-group semantics in any
structured representation. Recommend help, completion, and parse-only failures
produce no usage summary and require no acquisition work. Specify the boundary
for input/preflight failures when designing the lifecycle hook.
### OD-6: Initial summary detail
Choose the initial report fields and text precision. Recommend aggregate prompt,
completion, reasoning, total, cached, and cache-write tokens; available USD cost
with its source; and clear availability/completeness and terminal-coverage
indicators. Include cost automatically when the native summary provides it,
without a separate accounting opt-in, including explicit configured-zero evidence.
Recommend exposing the native `Usage.CacheHitRatio()` when available, using
aggregate counts rather than averaging per-run ratios. Decide its text format
and whether it also appears in smoke reports; do not derive it independently.
Reasoning and cache values must be presented as details, not added to total tokens.
Decide whether run, attempt, retry, and repair counts belong in the concise
summary. Recommend deferring per-model breakdowns, event traces, and persistent
history; the native group summary is sufficient for the initial invocation-total
task. These remain CommandKit presentation decisions despite the released upstream
availability of the evidence.
## Delivery Sequence
1. Resolve OD-5 and OD-6 against the reviewed PromptKit v0.25.0 API. Upstream
implementation and release are complete; no upstream feature work remains a
prerequisite.
2. Implement and verify the neutral core installation, flag, context, and
finalization support. Preserve existing reporting and assembly contracts.
3. Adopt PromptKit v0.25.0 in ckprompt and attach observation and summary
presentation through normal installation. Cover both current assembly paths
and application commands registered separately from the standard family.
Carry new native fields through existing reports and review maintained backend
fixtures for intended provider and authentication conventions.
4. Extend the maintained composed consumer to demonstrate the CommandKit-specific
benefit: an application-owned command receives the flag and final summary
without accounting code in its handler. Use offline injected-client evidence.
5. Update owning GoDoc, the CLI reference, consumer guidance, and internal
inventory as implementation lands. Review dependency alignment and attribution.
Retire this roadmap after completion, preserving any deferred scope separately.
This work is expected to require a core release as well as ckprompt. Follow the
[downstream alignment policy](../policy/release.md#commandkit-downstream-dependency-alignment):
release core, align and release ckconfig, then align and release ckprompt against
the published core and ckconfig versions. ckconfig need not acquire usage
functionality. Exact versions and publication remain separate release work.
## Verification And Completion
The decisive consumer check is a normally installed ckprompt integration plus
an application-owned pipeline command. Selecting the usage flag must produce its
summary without request observers, accounting state, or a final reporting step
in application code. Verify the alternate assembly path and later registration
so automatic behavior does not depend on a particular declaration layout.
Use focused core tests for installation, flag forwarding, context decoration,
finalization timing, visibility, invocation isolation, and writer failures. Use
integration tests to establish that ckprompt passes the scoped context to the
native API and faithfully presents returned summary values, including reasoning,
cost sources, unknown/reported-zero/configured-zero/incomplete evidence, and
available data after failure. Verify the new reasoning field survives smoke
projection and explicit provider/zero-cost declarations survive backend inspection.
Exercise a representative multi-call consumer with the real upstream engine as
useful; PromptKit retains tests for its accounting, retries, repairs, and provider decoder.
Do not duplicate those upstream domain suites in CommandKit.
Validate help/completion without acquisition, existing explicit observer
coexistence, preserved application outcomes, and the selected empty-scope and
quiet-mode behavior. Keep checks offline. Run affected core and nested-module
suites using the developer guide, including independent builds against released
dependencies before release. No live inference, performance benchmark, or new
concurrent-dispatch guarantee is needed.
[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