# Automatic Usage Reporting Review Status: four open findings: documentation R1, integration R2, and efficiency opportunities R3–R4. Production code is unchanged by these reviews. ## Scope and evidence Reviewed implementation commit `b7467c5` against all eight stages of [the implementation plan](implementation.md) and the agreed [target state](automatic-usage-reporting.md). | Stages | Review result | | --- | --- | | 1–2: capture, installation, parsing and discovery | Captured feature handles, prospective-registry validation, rollback, separate flag values, aliases, help and completion follow the selected design. | | 3–4: lifecycle, reporting and public assembly | Startup follows successful command input checking; builtin exclusions, context composition, invocation isolation, quiet rendering, finalization order and presentation failures follow the selected contracts. | | 5–6: upstream adoption and reports | Published PromptKit v0.25.0 supplies observation/accounting; native reasoning, ratio, cost, zero/unknown/incomplete states and smoke separation survive adaptation. R1 concerns the operator documentation. | | 7: consumer evidence | Normal integration installation enables the offline application pipeline without accounting code in its handler. | | 8: documentation and validation | Workspace and isolated-source checks pass. R1 remains in the canonical CLI reference. Published-dependency alignment remains the explicitly planned release follow-up. | The initial stage-oriented review identified no production correctness defect, missing architectural capability, or inadvertently strengthened contract. The subsequent interaction review below identifies the help-fallback integration defect R2. Validation used Go 1.27.4: - All three workspace `go test` suites passed. - Independent root and ckconfig `GOWORK=off` suites passed. - Isolated ckprompt `go test -count=1 ./...` passed using a temporary modfile replacing only core and ckconfig with local sources. PromptKit remained the published v0.25.0. This does not establish compatibility with newly published core/ckconfig releases, which have not been selected for this checkout. - The offline pipeline returned valid JSON on stdout and the expected two-prompt, 28-token, USD 0.0025 summary on diagnostics. Quiet suppressed both streams. - The offline `text_inference` smoke command retained its own nonzero token/ratio evidence while the ordinary execution summary remained zero and carried the smoke-separation note. - Core dependency inspection found no optional integration/domain modules; formatting and diff checks passed. ## R1: Complete the canonical smoke-report documentation **Priority:** P3. **Status:** complete. **Plan coverage:** Stages 5 and 8. Verified against the smoke DTO, text templates, and existing smoke projection checks. Updated the format row, field definitions, and emitted-shape example. **Relevant material:** the smoke `--format` row in [the CLI reference](../cli.md#smoke-test-flags), the [smoke report fields and example](../cli.md#smoke-report-fields), and the new [usage-reporting description](../cli.md#promptkit-usage-reporting). Compare [the smoke report DTO and templates](../../integrations/ckprompt/smoke_report.go) and [their installation in smoke commands](../../integrations/ckprompt/smoke_command.go). **Expected:** the canonical operator reference should consistently describe the implemented text-template default and the added structured usage evidence. Both attempt and aggregate usage now include `reasoning_tokens` and `cache_hit_ratio`. The ratio is a nullable numeric fraction in JSON/YAML, including a present zero; text additionally presents available ratios as percentages with one decimal place. **Actual:** the new usage-reporting section says smoke reports default to text, but the smoke flag table retains the earlier description that automatic/text output uses YAML for structured reports. The current text template does retain the YAML evidence and append percentage comments, so the table should describe that selected template rather than imply the old generic fallback. The smoke field description and sample also omit the two added usage fields and do not explain the numeric ratio's units or unavailable/null representation. **Impact:** readers get inconsistent format guidance and an outdated example of the emitted usage shape. In particular, the structured ratio's `0.2` means 20%, not 0.2%; the canonical reference currently leaves that distinction unexplained. The implementation and existing projection tests retain the correct evidence. **Remediation:** update the smoke format row, usage-field description, and sample in `docs/cli.md` to match the implemented reports. Include reasoning count state and nullable fractional cache-hit ratio at the attempt/aggregate boundary; explain the text percentage presentation and keep provider/accounting semantics linked upstream. Verify the sample against the current DTO or offline consumer. This requires documentation updates, not a production behavior change or a new upstream-domain test suite. ## R2: Honor ckconfig's help-only fallback before starting invocation features **Priority:** P2. **Status:** complete. **Plan coverage:** Stages 2–4 and 7–8. Added the CheckInput help signal and deferred feature requiredness until real execution. Regression checks cover implicit/explicit/aliased help, malformed values, real operations, and normal ckprompt installation. All three workspace suites passed on Go 1.27.4. **Relevant code and contracts:** - [prepareConfigOperation](../../integrations/ckconfig/input.go) records a help-only plan when `config explain` has neither `--path` nor `--list`. - [runConfigOperation](../../integrations/ckconfig/operations.go) returns `Invocation.Help()` for that plan before initializing state or acquiring data. - [App.Execute and prepareFeatures](../../execute.go) enforce required feature flags before the command's input check reveals that help-only plan. - [typedCommand.prepare](../../command.go) starts features after successful `CheckInput`, before ckconfig's `Run` can delegate to help. - The [existing explain contract](../cli.md#explain-a-configuration-path) defines the invocation without either mode as help. The new [invocation-scope target](automatic-usage-reporting.md#invocation-scope) excludes help from observation and usage summaries. **Failure condition:** install ckconfig alongside a nonempty ckprompt family, or alongside another invocation feature, then enter `config explain` without a mode. The existing integration represents this help path inside its handler rather than as a generated builtin or a parser-level help request. The new lifecycle recognizes only the latter forms before starting features. **Expected:** this documented help-only invocation should have the same feature exemption as explicit help: no usage summary or feature startup, no acquisition, and no requirement to supply execution-only invocation flags. Ordinary inspection commands without model executions should still receive the selected zero summary. Validation failures inside an actual `Run` remain execution as already agreed. **Actual and reproduction:** from the repository root, with the maintained offline consumer and Go 1.27.4: ```sh go run ./integrations/ckprompt/examples/composed config explain --show-tokens go run ./integrations/ckprompt/examples/composed config explain --help --show-tokens ``` Both return status 0 and display help. The first additionally emits the standard zero-token/zero-cost usage summary; the explicit-help invocation emits none. A temporary external consumer further confirmed the generic feature interaction: install `ckconfig.AppCommand` with a loader counter and an invocation feature having a required Boolean flag and a `Start` counter. `config explain` returns status 2 with `required flag --feature-required was not supplied`, while `config explain --help` returns status 0. Supplying `--feature-required` returns status 0 but calls `Start` once before displaying help. The loader remains uncalled in all three cases. The temporary consumer did not modify repository sources. **Consequence:** equivalent help paths have different output and eligibility rules. Invocation features can execute callbacks on this help path or prevent the help display altogether. This is an interaction with an established standard integration, not a request to reinterpret arbitrary application validation. **Remediation approach:** provide a narrow, library-neutral way to communicate a known help-only preflight disposition to core, and have ckconfig expose its existing `plan.help` decision through it. Honor that disposition before enforcing execution-only feature requiredness and before feature input construction/startup. Keep supplied-value syntax checking and existing main help rendering in the shared CLI machinery. Preserve requested summaries for real executions, including empty groups and returned validation/acquisition failures. A report-output heuristic or blanket suppression of zero summaries would miss the callback/requiredness defect and discard intentionally supported empty-execution reports. **Regression coverage:** exercise ckconfig's implicit explain help and explicit `--help`, both with normal ckprompt installation and with a generic required invocation feature. Verify successful help, zero feature-start/provider calls, and no invocation summary in both paths. Include a real explain operation and an ordinary non-model command to verify that their requested zero summaries and execution-only required flags still work. Cover an alias to the help-only command through the same dispatch behavior. ## Follow-up interaction audit evidence The interaction review used source baseline `b7467c5`, with R1 already recorded at `70cd68f`. It revisited the eight stages through their existing collaborators: registry/alias installation, local and shared flag parsing, discovery, reporting, configuration preflight, native observation, smoke reporting, and consumer wiring. All three workspace suites passed afresh with `go test -count=1` on Go 1.27.4. A temporary external consumer also passed checks combining a late-installed feature with local shared-debug input, local and feature repeatable values, scoped/global flag aliases, an alias-only help prefix, operands after `--`, version, and completion. R2 was reproduced separately despite those passing suites. No other new interaction defect requiring remediation was identified. ## R3: Partition occurrence preparation instead of rescanning argv for every feature **Priority:** P3. **Status:** open. **Plan coverage:** Stages 2–4. **Relevant code:** [execution.prepareFeatures](../../execute.go), [typedInvocationFeature.prepare](../../invocation_feature.go), and [prepareInputWithOccurrences](../../binding.go). Each feature receives its own raw value/spelling slices, but receives the entire `parsed.FlagOccurrences` log. Its call to `prepareInputWithOccurrences` rebuilds the ordinal map by scanning that complete log. Captured ordered bindings can also allocate and sweep an ordered array sized to the whole log, even when only a few occurrences belong to the feature. **Complexity:** let F be the installed feature count, N the parsed flag occurrence count, and B the total feature binding count. Apart from metadata conversion and caller-supplied converter work, successful feature preparation takes Θ(F + B + FN) time and Θ(FN) cumulative ordinal-index allocation. This is allocation churn, not a claim that all those indexes remain live simultaneously. It can be quadratic when F and N grow together. Even features with no flags scan every occurrence. A valid example is F distinct flagless features plus N occurrences of one application repeatable flag: each feature builds an index it never uses. ckprompt currently contributes one feature, so this does not make the ordinary single-feature path quadratic. The scaling problem concerns the new public composition API as more features are installed. **Refactoring opportunity:** build a binding-owner lookup and partition the occurrence stream once, preserving canonical names, entered spellings, and relative occurrence order within each input owner. Supply each feature and the selected command with only their owned occurrences, using dense owner-relative positions. Total indexing/preparation overhead can then be expected O(F + B + N), plus the selected command's bindings and inherent conversion work. A shared ordinal index is another possible approach, but it must also eliminate each owner's full-N ordered-array allocation/sweep; sharing only the map leaves that second source of repeated work intact. This retains the selected typed binding machinery and directly implements Stage 2's intended partitioning by ownership. It does not reconsider parsing grammar, feature order, conversion semantics, or the selected input/Run boundary. Preserve alias spellings, malformed earlier occurrences, explicit false/empty values, and `CaptureFlags` ordering in regression coverage with multiple features and local bindings. No timing threshold or benchmark is necessary. ## R4: Share invocation-flag lookup across installation contexts **Priority:** P3. **Status:** open. **Plan coverage:** Stages 1–2. **Relevant code:** [validateInvocationFlagCollisions](../../registry.go), [collectInvocationFeatures](../../registry.go), and the invocation-flag insertion loop in [compileFlagAliases](../../flag_aliases.go). There are two related command-by-flag products in installation: - Collision validation builds a local spelling map for each command, then tests every invocation flag against that map, including commands with no local flags. - Alias compilation inserts the same invocation spellings into every canonical, root, and alias-discovery context's map, regardless of whether aliases exist. **Complexity:** let C be the command count, G the invocation flag count, L the total local spelling count, and Q the number of alias-validation contexts (canonical commands, root, and discovery prefixes). Collision checking takes O(C + L + CG) expected time. The new alias insertion adds Θ(QG) expected time and transient map entries. Together these introduce avoidable command/context-by-flag work and storage. With C and G both proportional to n and no alias rules, Q is C + 1 and this is quadratic despite linear-sized command/flag declarations. **Refactoring opportunity:** construct one feature-only spelling index after the existing reserved/duplicate checks. For collision validation, walk each command's local spellings once and query that shared index, reducing that work to expected O(G + C + L). For alias resolution, retain local canonical maps and provide a lookup that also consults the shared invocation index. Both alias destination resolution and source-collision checking should use that combined lookup. This avoids copying G entries into all Q context maps, adding O(G + Q) storage instead of Θ(QG). Merely fixing the collision loop leaves the alias-copying product, so the two paths should be considered together. These bounds describe the added invocation-flag work; they do not claim that the entire installer becomes linear. Existing tree construction, selected sorting, context/alias resolution, and validation of the prospective registry still have their own costs. The shared lookup preserves atomic installation, validation in both registration orders, canonical/scoped/global alias behavior, and ordinary long/short spelling collisions. Regression checks should cover those semantics, including inactive global aliases that become active when a feature is installed. The plan selected deterministic traversal, handle deduplication, and validation of every command; it did not select either nested loop or require duplicated canonical maps. Indexing the global spellings once preserves those decisions. ## Algorithmic audit scope and evidence Reviewed all eight stages against source baseline `b7467c5`, with prior findings retained from `367d05b`: | Stages | Algorithmic assessment | | --- | --- | | 1 | Preserved the explicitly selected traversal, root sorting, immutable capture and handle deduplication. R4 concerns unselected repeated spelling checks. | | 2 | R3 concerns repeated full-log indexing; R4 concerns copied global spelling maps. Existing parser grammar and alias policies were not reconsidered. | | 3–4 | Feature startup and report-producer traversal are linear in the feature count, apart from callback/report work. Existing lifecycle and public-assembly checks remain applicable. | | 5 | Smoke projection visits each attempt once; added token/ratio adaptation is constant-size per attempt. Text rendering adds a linear pass for percentage comments. | | 6 | Local summary adaptation reads a fixed set of native fields and uses `len(Members)`. Native group accounting and snapshot selection were expressly delegated upstream and were not reevaluated. | | 7 | The maintained consumer's two-call pipeline is explicitly selected and bounded. No new domain algorithm was added. | | 8 | Validation/documentation introduce no additional production algorithm. Prior R1 and R2 remain open. | The findings follow from loop bounds and allocation sizes in the implementation; no performance measurements or new benchmark/test code were added. Existing focused `TestInvocationFeature*`, `TestInvocationFeatures*`, and `TestRequiredInvocationFlag*` checks passed with Go 1.27.4. No additional ordinary correctness defect was discovered in this algorithmic pass.