From ef92089125c7305b291fe2b3e0b61e962341a26d Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 23 Nov 2026 00:20:32 +0000 Subject: [PATCH] Retire completed usage reporting plans and reviews --- docs/roadmap/automatic-usage-reporting.md | 332 ---------------- docs/roadmap/future.md | 34 +- docs/roadmap/implementation.md | 445 ---------------------- docs/roadmap/remediation.md | 293 -------------- 4 files changed, 29 insertions(+), 1075 deletions(-) delete mode 100644 docs/roadmap/automatic-usage-reporting.md delete mode 100644 docs/roadmap/implementation.md delete mode 100644 docs/roadmap/remediation.md diff --git a/docs/roadmap/automatic-usage-reporting.md b/docs/roadmap/automatic-usage-reporting.md deleted file mode 100644 index 9c80e11..0000000 --- a/docs/roadmap/automatic-usage-reporting.md +++ /dev/null @@ -1,332 +0,0 @@ -# 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 diff --git a/docs/roadmap/future.md b/docs/roadmap/future.md index 4d95075..8251bbf 100644 --- a/docs/roadmap/future.md +++ b/docs/roadmap/future.md @@ -1,17 +1,31 @@ # Future work -Status — active adoption roadmap, optional shell validation, and future capability proposals. +Status — pending release coordination, optional verification, and future capability proposals. No delivery dates are selected here. -## Active roadmap +## Pending release coordination -[Automatic PromptKit usage reporting](automatic-usage-reporting.md) records the -agreed target state for invocation-wide usage reporting through normal ckprompt -installation, the released upstream API, and the required adoption work. +Automatic usage reporting and R1–R4 remediation are implemented. Publication is +separate follow-up work: release core, align and release ckconfig, then align and +release ckprompt with both published CommandKit dependencies under the +[release procedure](../release.md#scope-and-release-order). Integration module +requirements still select the earlier published versions. Update them during +release preparation and run independent integration suites against the new +published versions. Until then, unreleased integrations use the aligned workspace +or temporary local-source modfiles as described in the developer guide. + +## Open proposal + +The [selected-format accessor proposal](scriptorium-feature-request.md) remains +optional and unselected; it is not a prerequisite for the completed usage feature +or for the coordinated releases. ## Purpose and authority Earlier completed roadmaps, implementation plans, and review findings have been retired. +The completed automatic usage roadmap, implementation plan, and R1–R4 review +records remain available in their +[retirement snapshot](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/33f98db4f78f0b45ea89b0618203b1d947a89374/docs/roadmap). This document preserves unfinished work and unselected ideas under the [release policy](../policy/release.md#release-documentation-and-preparation). The completed shared debug binding and reporting-mode implementation is recorded @@ -132,6 +146,16 @@ remain unselected. Whole-run buffering to make failed runs show only errors was also outside that scope. Any later extension needs a deliberate API and presentation decision rather than assuming those behaviors are already provided. +### Usage reporting extensions + +Machine-readable invocation usage output remains deferred pending a concrete +consumer need. Select its destination, framing, and format explicitly when that +work is undertaken; the current main result stream remains application-owned. +A separate usage-only installation API for applications without a nonempty +ckprompt suite, per-model breakdowns, event traces, and persistent usage history +also remain future proposals. None is required for the delivered aggregate usage +summary through normal installation. + ### Release workflow extensions Historical hosted-page backfilling and automated CI delivery remain separate diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md deleted file mode 100644 index 8212d9b..0000000 --- a/docs/roadmap/implementation.md +++ /dev/null @@ -1,445 +0,0 @@ -# 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. diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md deleted file mode 100644 index 4d6ff2d..0000000 --- a/docs/roadmap/remediation.md +++ /dev/null @@ -1,293 +0,0 @@ -# Automatic Usage Reporting Review - -Status: R1–R4 complete. Each remediation was verified and committed separately. -Historical audit evidence and findings are retained below. - -## 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. Current dependency guidance records that unreleased -ckconfig now also requires local core until release alignment. - -**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:** complete. **Plan coverage:** Stages 2–4. - -Partitioned canonical occurrences once by input owner, with dense relative -positions. Interleaved captured occurrence flags, aliases, local inputs and a -flagless feature are covered by regression tests. All workspace suites passed. - -**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:** complete. **Plan coverage:** Stages 1–2. - -Collision validation now indexes invocation spellings once and walks local -spellings. Alias contexts share one invocation map through a combined lookup. -Regressions cover inactive-alias activation, scoped/global and short aliases, -discovery help, collisions and rollback. All workspace suites passed. - -**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.