From 07cc832f4a915333486faab04e81bcf3714a7e51 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sun, 22 Nov 2026 20:59:23 +0000 Subject: [PATCH] Report observed PromptKit invocation usage --- docs/roadmap/implementation.md | 5 ++ integrations/ckprompt/command.go | 2 +- integrations/ckprompt/usage_report.go | 83 ++++++++++++++++++++++ integrations/ckprompt/usage_report_test.go | 47 ++++++++++++ 4 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 integrations/ckprompt/usage_report.go create mode 100644 integrations/ckprompt/usage_report_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index cd49e34..9d45d2d 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -302,6 +302,11 @@ single/aggregate text, JSON, and YAML. Run affected ckprompt tests in the worksp ## 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 diff --git a/integrations/ckprompt/command.go b/integrations/ckprompt/command.go index 61de6d2..ac93767 100644 --- a/integrations/ckprompt/command.go +++ b/integrations/ckprompt/command.go @@ -129,7 +129,7 @@ func buildCommand[I, S any](suite Suite[I, S], aliases *[]commandkit.Declaration for _, issue := range suite.issues { command = commandkit.WithError(command, issue) } - return command + return commandkit.WithInvocationFeature(command, usageFeature()) } func newCatalogListCommand[I, S any](suite Suite[I, S], name string) commandkit.Command { diff --git a/integrations/ckprompt/usage_report.go b/integrations/ckprompt/usage_report.go new file mode 100644 index 0000000..d57c34f --- /dev/null +++ b/integrations/ckprompt/usage_report.go @@ -0,0 +1,83 @@ +package ckprompt + +import ( + "context" + "fmt" + "text/template" + + commandkit "go.maximumdirect.net/commandkit" + promptkit "go.maximumdirect.net/promptkit" +) + +type usageInput struct{ ShowTokens bool } + +type usageSummary struct { + Prompts int + RepairCalls uint64 + CoverageComplete bool + Usage promptkit.ObservedTokenUsage + Cost promptkit.ObservedCost + CacheHitRatio *float64 + Smoke bool +} + +func usageFeature() commandkit.InvocationFeature { + return 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(i *usageInput, v commandkit.Supplied[bool]) { i.ShowTokens = v.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) } + }, + }) +} + +func usageReport(summary promptkit.ExecutionGroupSummary, smoke bool) commandkit.Report { + value := usageSummary{Prompts: len(summary.Members), RepairCalls: summary.RepairCalls, CoverageComplete: summary.TerminalCoverageComplete, Usage: summary.Usage, Cost: summary.CostUSD, Smoke: smoke} + if ratio, ok := summary.Usage.CacheHitRatio(); ok { + value.CacheHitRatio = &ratio + } + return commandkit.Report{Value: value, TextTemplate: usageTextTemplate} +} + +func usageCount(count promptkit.ObservedTokenCount) string { + if !count.Known { + return "unknown" + } + if !count.Complete { + return fmt.Sprintf("%d (incomplete)", count.Value) + } + return fmt.Sprint(count.Value) +} +func usageCost(cost promptkit.ObservedCost) string { + if !cost.Known { + return "unknown" + } + result := fmt.Sprintf("USD %.6g", cost.Value) + if !cost.Complete { + result += " (incomplete subtotal)" + } + if cost.Source != "" { + result += fmt.Sprintf(" [%s]", cost.Source) + } + return result +} + +var usageTextTemplate = template.Must(commandkit.ParseTextTemplate("observed usage", `Observed PromptKit execution usage +Prompts: {{.Prompts}} +{{if .RepairCalls}} Repair calls: {{.RepairCalls}} +{{end}}Prompt tokens: {{count .Usage.PromptTokens}} +Completion tokens: {{count .Usage.CompletionTokens}} + Reasoning tokens: {{count .Usage.ReasoningTokens}} +Total tokens: {{count .Usage.TotalTokens}} + Cached tokens: {{count .Usage.CachedTokens}} + Cache-write tokens: {{count .Usage.CacheWriteTokens}} +{{with .CacheHitRatio}}Cache hit ratio: {{printf "%.1f" (percent .)}}% +{{end}}Cost: {{cost .Cost}} +Terminal coverage: {{if .CoverageComplete}}complete{{else}}incomplete{{end}} +{{if .Smoke}}Smoke-test usage is reported separately in the command report. +{{end}}`, template.FuncMap{"count": usageCount, "cost": usageCost, "percent": func(value *float64) float64 { return *value * 100 }})) diff --git a/integrations/ckprompt/usage_report_test.go b/integrations/ckprompt/usage_report_test.go new file mode 100644 index 0000000..8824241 --- /dev/null +++ b/integrations/ckprompt/usage_report_test.go @@ -0,0 +1,47 @@ +package ckprompt + +import ( + "bytes" + "strings" + "testing" + + commandkit "go.maximumdirect.net/commandkit" + promptkit "go.maximumdirect.net/promptkit" +) + +func TestUsageSummaryPreservesNativeEvidence(t *testing.T) { + count := func(n int, known, complete bool) promptkit.ObservedTokenCount { + return promptkit.ObservedTokenCount{Value: n, Known: known, Complete: complete} + } + for _, tc := range []struct { + name string + summary promptkit.ExecutionGroupSummary + smoke bool + want []string + absent []string + }{ + {name: "empty", summary: new(promptkit.ExecutionGroup).Snapshot(), want: []string{"Prompts: 0", "Prompt tokens: 0", "Cost: USD 0", "Terminal coverage: complete"}, absent: []string{"Repair calls:", "Cache hit ratio:", "[provider]"}}, + {name: "unknown", summary: promptkit.ExecutionGroupSummary{Members: []promptkit.ExecutionGroupMember{{RunID: "a"}}}, smoke: true, want: []string{"Prompts: 1", "Prompt tokens: unknown", "Cost: unknown", "Terminal coverage: incomplete", "Smoke-test usage is reported separately"}}, + {name: "known", summary: promptkit.ExecutionGroupSummary{Members: []promptkit.ExecutionGroupMember{{}, {}}, TerminalCoverageComplete: true, RepairCalls: 2, Usage: promptkit.ObservedTokenUsage{PromptTokens: count(8, true, true), CompletionTokens: count(9, true, false), ReasoningTokens: count(0, true, true), CachedTokens: count(1, true, true)}, CostUSD: promptkit.ObservedCost{Value: 0.012345678, Known: true, Source: promptkit.CostSource("mixed")}}, want: []string{"Prompts: 2", "Repair calls: 2", "Completion tokens: 9 (incomplete)", "Reasoning tokens: 0", "Cache hit ratio: 12.5%", "Cost: USD 0.0123457 (incomplete subtotal) [mixed]"}}, + {name: "configured zero", summary: promptkit.ExecutionGroupSummary{CostUSD: promptkit.ObservedCost{Known: true, Complete: true, Source: promptkit.CostSource("configured_zero")}}, want: []string{"Cost: USD 0 [configured_zero]"}}, + {name: "provider zero", summary: promptkit.ExecutionGroupSummary{CostUSD: promptkit.ObservedCost{Known: true, Complete: true, Source: promptkit.CostSource("provider")}}, want: []string{"Cost: USD 0 [provider]"}}, + } { + t.Run(tc.name, func(t *testing.T) { + report := usageReport(tc.summary, tc.smoke) + var out bytes.Buffer + if err := commandkit.RenderReport(&out, report, commandkit.FormatText); err != nil { + t.Fatal(err) + } + for _, want := range tc.want { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q in %q", want, out.String()) + } + } + for _, absent := range tc.absent { + if strings.Contains(out.String(), absent) { + t.Errorf("unexpected %q in %q", absent, out.String()) + } + } + }) + } +}