The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Add beacon token-usage --coverage
Claude70c0f44429a9
diff --git a/cli/beacon/cmd/token_usage.go b/cli/beacon/cmd/token_usage.goindex 1feecb35..11075c9a 100644--- a/cli/beacon/cmd/token_usage.go+++ b/cli/beacon/cmd/token_usage.go@@ -8,6 +8,7 @@ import ("github.com/spf13/cobra""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"+ endpointinventory "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens")@@ -26,6 +27,7 @@ type tokenUsageOptions struct {runID stringbucket stringtop int+ coverage bool}var tokenUsageOpts tokenUsageOptions@@ -63,6 +65,9 @@ func runTokenUsage(cmd *cobra.Command, args []string) error {}query.Until = parsed}+ if tokenUsageOpts.coverage {+ return runTokenCoverage(cmd, runtimeLog.EffectiveLogPath, query)+ }events, contexts, err := dashboard.ReadTokenEventsAppendOrder(runtimeLog.EffectiveLogPath, query)if err != nil {return err@@ -89,6 +94,44 @@ func runTokenUsage(cmd *cobra.Command, args []string) error {return nil}+// runTokenCoverage answers "is this total all of it", which the usage report itself cannot: a+// runtime whose telemetry never arrives is indistinguishable from one nobody used, since both are+// simply absent from every rollup.+//+// It deliberately drops the session, model, repository and run filters and keeps only the time+// window and the harness scope. Those filters select usage-bearing events almost by definition --+// an event carries no model unless it carried a model call -- so a coverage report computed over+// them would find every runtime covered and prove nothing. The window is what a reader is+// actually asking about.+func runTokenCoverage(cmd *cobra.Command, logPath string, query dashboard.EventQuery) error {+ scoped := dashboard.EventQuery{+ Since: query.Since,+ Until: query.Until,+ Harness: query.Harness,+ }+ events, _, err := dashboard.ReadTokenEventsAppendOrder(logPath, scoped)+ if err != nil {+ return err+ }+ // Installed runtimes come from the config scanner rather than from the log, because the+ // whole question is which installed runtime is missing from the log.+ installed := []string{}+ for _, config := range endpointinventory.Scan(endpointinventory.Options{}).Configs {+ if config.Exists {+ installed = append(installed, config.Runtime)+ }+ }+ report := tokens.Coverage(events, installed)+ out := cmd.OutOrStdout()+ if tokenUsageOpts.jsonOutput {+ encoder := json.NewEncoder(out)+ encoder.SetIndent("", " ")+ return encoder.Encode(report)+ }+ tokens.RenderCoverageText(out, report)+ return nil+}+func init() {rootCmd.AddCommand(tokenUsageCmd)tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.userMode, "user", true, "Use per-user endpoint paths")@@ -104,4 +147,5 @@ func init() {tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.runID, "run-id", "", "Filter by CI run id")tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.bucket, "bucket", "", "Time-series bucket size (for example 1h or 15m)")tokenUsageCmd.Flags().IntVar(&tokenUsageOpts.top, "top", 0, "Limit each grouping to the top N entries (0 keeps all)")+ tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.coverage, "coverage", false, "Report which runtimes contributed token telemetry instead of the usage totals")}diff --git a/cli/beacon/cmd/token_usage_test.go b/cli/beacon/cmd/token_usage_test.goindex a061bf96..7218c501 100644--- a/cli/beacon/cmd/token_usage_test.go+++ b/cli/beacon/cmd/token_usage_test.go@@ -19,7 +19,7 @@ func TestTokenUsageCommandRegistered(t *testing.T) {if cmd == nil || cmd.Use != "token-usage" {t.Fatalf("token-usage command not registered: %#v", cmd)}- for _, flag := range []string{"log-path", "json", "since", "until", "session", "model", "harness", "repository", "run-id", "bucket", "top"} {+ for _, flag := range []string{"log-path", "json", "since", "until", "session", "model", "harness", "repository", "run-id", "bucket", "top", "coverage"} {if cmd.Flags().Lookup(flag) == nil {t.Fatalf("token-usage command missing --%s flag", flag)}@@ -140,3 +140,54 @@ func TestTokenUsageEmptyLogSucceeds(t *testing.T) {t.Fatalf("empty report = %q", output)}}++func TestTokenUsageCoverageReportsSilentAndNotInstrumentedRuntimes(t *testing.T) {+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ lines := []string{+ // Reported usage: covered.+ `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"hostname":"h"},"harness":{"name":"claude_code"},"model":"claude-opus-5","session":{"id":"s1"},"gen_ai":{"usage":{"input_tokens":1200,"output_tokens":340}},"message":"usage"}`,+ // Ran but reported nothing, and Beacon is built to read usage from it: silent.+ `{"timestamp":"2026-06-11T10:02:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"command.executed","category":"command"},"severity":"info","endpoint":{"hostname":"h"},"harness":{"name":"codex_cli"},"session":{"id":"s3"},"message":"ls"}`,+ // Ran and cannot report usage at all: expected, not a fault.+ `{"timestamp":"2026-06-11T10:01:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"command.executed","category":"command"},"severity":"info","endpoint":{"hostname":"h"},"harness":{"name":"cursor"},"session":{"id":"s2"},"message":"ls"}`,+ }+ if err := os.WriteFile(logPath, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {+ t.Fatalf("write log: %v", err)+ }++ output := runTokenUsageCommand(t, "--log-path", logPath, "--coverage", "--json")+ var report tokens.CoverageReport+ if err := json.Unmarshal([]byte(output), &report); err != nil {+ t.Fatalf("unmarshal coverage report: %v\n%s", err, output)+ }++ status := map[string]string{}+ for _, runtime := range report.Runtimes {+ status[runtime.Harness] = runtime.Status+ }+ if status["claude_code"] != tokens.CoverageCovered {+ t.Errorf("claude_code = %q, want covered", status["claude_code"])+ }+ if status["codex_cli"] != tokens.CoverageSilent {+ t.Errorf("codex_cli = %q, want silent", status["codex_cli"])+ }+ if status["cursor"] != tokens.CoverageNotInstrumented {+ t.Errorf("cursor = %q, want not_instrumented -- Cursor cannot report usage", status["cursor"])+ }+ if report.Silent != 1 {+ t.Errorf("silent = %d, want 1", report.Silent)+ }+}++// A model or session filter selects usage-bearing events almost by definition, so applying one to+// a coverage report would find every runtime covered and prove nothing. Coverage keeps only the+// time window and the harness scope.+func TestTokenUsageCoverageIgnoresFiltersThatWouldHideSilentRuntimes(t *testing.T) {+ logPath := writeTokensFixtureLog(t)+ unfiltered := runTokenUsageCommand(t, "--log-path", logPath, "--coverage", "--json")+ filtered := runTokenUsageCommand(t, "--log-path", logPath, "--coverage", "--json", "--model", "claude-sonnet-4-5")+ if unfiltered != filtered {+ t.Fatalf("--model changed the coverage report:\nwithout:\n%s\nwith:\n%s", unfiltered, filtered)+ }+}diff --git a/cli/beacon/internal/tokens/coverage.go b/cli/beacon/internal/tokens/coverage.gonew file mode 100644index 00000000..3a7f292f--- /dev/null+++ b/cli/beacon/internal/tokens/coverage.go@@ -0,0 +1,245 @@+package tokens++import (+ "sort"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// Token spend coverage: which runtimes on this machine are contributing token telemetry, and+// which are not.+//+// A token report answers "what did I spend". It cannot answer "is this all of it", and that is+// the question that matters before anyone treats a number as a bill. A runtime whose usage never+// arrives is indistinguishable, in every rollup Beacon prints, from a runtime nobody used: both+// are simply absent. So a total can quietly omit an entire agent and still look complete.+//+// Coverage answers the second question by joining what is installed against what actually+// reported, and it exists because the alternative is a reader inferring coverage from a docs+// table. The table describes what Beacon is built to read; only the log knows what this machine+// produced.+//+// The expectation table below is what keeps the report from crying wolf. Cursor's hooks carry no+// token counts at all, so Cursor contributing nothing is correct behavior, not a fault -- reported+// as NotInstrumented rather than Silent. Silent is reserved for the case worth investigating: a+// runtime that ran, that Beacon is built to read tokens from, and that reported none anyway.++// Coverage status values.+const (+ // CoverageCovered: the runtime reported usage in the window. Nothing to do.+ CoverageCovered = "covered"+ // CoverageSilent: the runtime produced events but no usage, and Beacon is built to read+ // usage from it. This is the actionable one -- a broken hook, an old runtime build, or a+ // capture path that regressed.+ CoverageSilent = "silent"+ // CoverageInactive: the runtime is installed but produced no events at all in the window.+ // Usually means it was not used; can also mean its hooks are not installed.+ CoverageInactive = "inactive"+ // CoverageNotInstrumented: the runtime produced events, and Beacon cannot read token usage+ // from it. Absence of tokens here is expected and is not a fault to chase.+ CoverageNotInstrumented = "not_instrumented"+)++// Expectation values: what Beacon can read from a runtime, independent of what it did read.+const (+ // ExpectReported: usage is collected from this runtime and verified against captured+ // payloads.+ ExpectReported = "reported"+ // ExpectGenericOTLP: usage is collected only if the runtime emits the OpenTelemetry GenAI+ // semconv names. The generic path is tested; these runtimes' own payloads are not pinned,+ // so silence here may mean the runtime spells its attributes differently rather than that+ // anything is broken.+ ExpectGenericOTLP = "generic_otlp"+ // ExpectNone: the runtime exposes no token counts on the surface Beacon collects from.+ ExpectNone = "none"+)++// usageExpectation records, per canonical harness name, whether Beacon can read token usage from+// that runtime and why. Keys are canonical harness names, so callers must normalize before+// looking up.+//+// This duplicates the per-runtime table in docs/cli/token-usage.mdx by necessity: the docs are for+// a reader deciding whether to expect numbers, this is for the report deciding whether silence is+// a fault. They must be kept in step, and the reason strings are written to be printed.+var usageExpectation = map[string]struct {+ expect string+ reason string+}{+ "claude_code": {ExpectReported, "OTLP token and cost telemetry"},+ "codex_cli": {ExpectReported, "per-turn usage trace; Codex emits no cost"},+ "claude_cowork": {ExpectReported, "OTLP token and cost telemetry"},+ "cline": {ExpectReported, "plugin reports usage once per task"},+ "opencode": {ExpectReported, "plugin reports usage per assistant message"},+ "pi_cli": {ExpectReported, "extension reports usage and cost"},+ "omp": {ExpectReported, "extension reports usage and cost"},+ "vercel_fx": {ExpectReported, "session store carries cumulative usage and cost"},+ "asymptote_observe": {ExpectReported, "SDK spans carry semconv usage"},++ "gemini_cli": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},+ "copilot_cli": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},+ "vscode_copilot": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},+ "factory": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},+ "factory_droid": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},+ "openclaw_gateway": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},++ "cursor": {ExpectNone, "Cursor hook payloads carry no token counts"},+ "antigravity_cli": {ExpectNone, "hook payloads carry no token counts"},+ "grok": {ExpectNone, "hook payloads carry no token counts"},+ "hermes": {ExpectNone, "hook payloads carry no token counts"},+ "devin": {ExpectNone, "hook payloads carry no token counts"},+ "muse_code": {ExpectNone, "usage arrives on PostLLMCall, which Beacon does not subscribe to"},+ "qwen_code": {ExpectNone, "Stop carries session context counters, not per-call usage"},+ "prime_agent": {ExpectNone, "no managed extension ships yet"},+ "claude_web": {ExpectNone, "no recorded claude.ai stream has carried a usage object"},+ "chatgpt_web": {ExpectNone, "the chat stream reports no token counts"},+ "openhands": {ExpectNone, "hook payloads carry no token counts"},+}++// RuntimeCoverage is one runtime's line in the coverage report.+type RuntimeCoverage struct {+ Harness string `json:"harness"`+ Status string `json:"status"`+ Expectation string `json:"expectation"`+ Reason string `json:"reason,omitempty"`+ Installed bool `json:"installed"`+ Events int `json:"events"`+ UsageEvents int `json:"usage_events"`+ Tokens int64 `json:"tokens"`+}++// CoverageReport is the whole join: one line per runtime that is either installed or seen in the+// log, plus the counts a reader needs to judge the window itself.+type CoverageReport struct {+ Runtimes []RuntimeCoverage `json:"runtimes"`+ // Silent counts runtimes worth investigating. Zero is the good state.+ Silent int `json:"silent"`+ // Covered counts runtimes that contributed usage.+ Covered int `json:"covered"`+ // TotalEvents is the size of the window the join was computed over. A coverage report over+ // an empty window says nothing, and a reader needs to be able to see that.+ TotalEvents int `json:"total_events"`+}++// Coverage joins installed runtimes against the runtimes that actually reported token usage.+//+// installed carries runtime identifiers as the inventory scanner spells them; they are normalized+// here, so callers pass them through unchanged. A runtime seen in the log but not installed is+// still reported -- telemetry can arrive from a runtime whose config the scanner does not know,+// and dropping it would hide exactly the coverage a reader is looking for.+func Coverage(events []schema.Event, installed []string) CoverageReport {+ type counters struct {+ events int+ usageEvents int+ tokens int64+ installed bool+ }+ byHarness := map[string]*counters{}+ get := func(name string) *counters {+ if byHarness[name] == nil {+ byHarness[name] = &counters{}+ }+ return byHarness[name]+ }++ for _, name := range installed {+ normalized := asymptoteobserve.NormalizeHarnessName(strings.TrimSpace(name))+ if normalized == "" {+ continue+ }+ get(normalized).installed = true+ }++ // Usage is counted through the same collector the report uses, so a runtime counts as+ // covered on exactly the events that would contribute to its totals -- including the+ // dedupe and cumulative-delta handling. Counting raw gen_ai.usage blocks here instead+ // would report a runtime as covered whose usage the report then discards.+ usageEvents := collectUsageEvents(events, sessionUserContexts(events))+ usageEvents = preferCodexTurnSpans(usageEvents)+ usageEvents = dedupeOverlappingChannels(usageEvents)+ resolveCumulativeSeries(usageEvents)++ for _, event := range events {+ name := asymptoteobserve.NormalizeHarnessName(strings.TrimSpace(event.Harness.Name))+ if name == "" {+ continue+ }+ get(name).events+++ }+ for _, ue := range usageEvents {+ name := asymptoteobserve.NormalizeHarnessName(strings.TrimSpace(ue.harness))+ if name == "" {+ continue+ }+ c := get(name)+ c.usageEvents+++ c.tokens += ue.usage.TotalTokens()+ }++ report := CoverageReport{TotalEvents: len(events)}+ for name, c := range byHarness {+ expectation, reason := expectationFor(name)+ line := RuntimeCoverage{+ Harness: name,+ Expectation: expectation,+ Reason: reason,+ Installed: c.installed,+ Events: c.events,+ UsageEvents: c.usageEvents,+ Tokens: c.tokens,+ }+ switch {+ case c.usageEvents > 0:+ line.Status = CoverageCovered+ report.Covered+++ case c.events == 0:+ line.Status = CoverageInactive+ case expectation == ExpectNone:+ line.Status = CoverageNotInstrumented+ default:+ line.Status = CoverageSilent+ report.Silent+++ }+ report.Runtimes = append(report.Runtimes, line)+ }++ // Silent first, because that is the only status anyone has to act on; then by spend, so the+ // runtimes that matter most sit at the top of each group.+ sort.SliceStable(report.Runtimes, func(i, j int) bool {+ left, right := report.Runtimes[i], report.Runtimes[j]+ if rank := statusRank(left.Status) - statusRank(right.Status); rank != 0 {+ return rank < 0+ }+ if left.Tokens != right.Tokens {+ return left.Tokens > right.Tokens+ }+ return left.Harness < right.Harness+ })+ return report+}++func statusRank(status string) int {+ switch status {+ case CoverageSilent:+ return 0+ case CoverageCovered:+ return 1+ case CoverageInactive:+ return 2+ default:+ return 3+ }+}++// expectationFor reports what Beacon can read from a harness. An unrecognized harness is treated+// as generic OTLP rather than as "none": a runtime Beacon has never heard of reaching the log at+// all means something is exporting semconv telemetry, and reporting it as silent when it carries+// no usage is the honest answer -- calling it not_instrumented would assert knowledge about a+// runtime nobody has looked at.+func expectationFor(harness string) (string, string) {+ if entry, ok := usageExpectation[harness]; ok {+ return entry.expect, entry.reason+ }+ return ExpectGenericOTLP, "unrecognized runtime; usage is read only from OTel GenAI semconv names"+}diff --git a/cli/beacon/internal/tokens/coverage_test.go b/cli/beacon/internal/tokens/coverage_test.gonew file mode 100644index 00000000..4d750879--- /dev/null+++ b/cli/beacon/internal/tokens/coverage_test.go@@ -0,0 +1,198 @@+package tokens++import (+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++func normalizedHarnessForTest(name string) string {+ return asymptoteobserve.NormalizeHarnessName(name)+}++// plainEvent is an event with no usage: it proves a runtime ran without contributing tokens,+// which is the distinction the whole report turns on.+func plainEvent(harness string) schema.Event {+ return schema.Event{+ Timestamp: "2026-06-11T10:00:00Z",+ Event: schema.EventInfo{Kind: "agent_runtime", Action: "command.executed", Category: "command"},+ Harness: schema.HarnessInfo{Name: harness},+ }+}++func lineFor(t *testing.T, report CoverageReport, harness string) RuntimeCoverage {+ t.Helper()+ for _, runtime := range report.Runtimes {+ if runtime.Harness == harness {+ return runtime+ }+ }+ t.Fatalf("no coverage line for %q in %+v", harness, report.Runtimes)+ return RuntimeCoverage{}+}++func TestCoverageMarksReportingRuntimesCovered(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-opus-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ e.GenAI.Usage.OutputTokens = int64Ptr(20)+ }),+ }+ report := Coverage(events, []string{"claude_code"})+ line := lineFor(t, report, "claude_code")+ if line.Status != CoverageCovered {+ t.Fatalf("status = %q, want covered", line.Status)+ }+ if line.Tokens != 120 {+ t.Fatalf("tokens = %d, want 120", line.Tokens)+ }+ if report.Covered != 1 || report.Silent != 0 {+ t.Fatalf("covered=%d silent=%d, want 1/0", report.Covered, report.Silent)+ }+}++// The case the report exists for: a runtime Beacon is built to read tokens from ran, and reported+// none. That is a broken capture path, not a quiet week, and it must be surfaced.+func TestCoverageFlagsARuntimeThatShouldHaveReportedUsage(t *testing.T) {+ report := Coverage([]schema.Event{plainEvent("claude_code")}, []string{"claude_code"})+ line := lineFor(t, report, "claude_code")+ if line.Status != CoverageSilent {+ t.Fatalf("status = %q, want silent", line.Status)+ }+ if report.Silent != 1 {+ t.Fatalf("silent = %d, want 1", report.Silent)+ }+}++// The case that keeps the report from crying wolf. Cursor's hooks carry no token counts, so+// Cursor contributing nothing is correct behavior. Reporting it as silent every week would train+// a reader to ignore the column that matters.+func TestCoverageDoesNotFlagRuntimesThatCannotReportUsage(t *testing.T) {+ events := []schema.Event{plainEvent("cursor"), plainEvent("qwen_code"), plainEvent("muse_code")}+ report := Coverage(events, []string{"cursor", "qwen_code", "muse_code"})+ for _, harness := range []string{"cursor", "qwen_code", "muse_code"} {+ line := lineFor(t, report, harness)+ if line.Status != CoverageNotInstrumented {+ t.Errorf("%s status = %q, want not_instrumented", harness, line.Status)+ }+ if line.Reason == "" {+ t.Errorf("%s has no reason; the reason is what stops a reader chasing it", harness)+ }+ }+ if report.Silent != 0 {+ t.Fatalf("silent = %d, want 0 -- none of these can report usage", report.Silent)+ }+}++// Installed but never run is not the same as installed and broken, and conflating them would+// make every machine look faulty on the day someone did not use one of their agents.+func TestCoverageSeparatesInactiveFromSilent(t *testing.T) {+ report := Coverage([]schema.Event{plainEvent("claude_code")}, []string{"claude_code", "codex_cli"})+ if got := lineFor(t, report, "codex_cli").Status; got != CoverageInactive {+ t.Fatalf("codex_cli status = %q, want inactive", got)+ }+ if got := lineFor(t, report, "claude_code").Status; got != CoverageSilent {+ t.Fatalf("claude_code status = %q, want silent", got)+ }+ if report.Silent != 1 {+ t.Fatalf("silent = %d, want 1 -- an unused runtime is not a fault", report.Silent)+ }+}++// A runtime can reach the log without the scanner knowing its config: cloud agents, CI, a+// runtime installed somewhere the scanner does not look. Dropping those rows would hide exactly+// the coverage the reader came for.+func TestCoverageReportsRuntimesSeenButNotInstalled(t *testing.T) {+ report := Coverage([]schema.Event{plainEvent("claude_code")}, nil)+ line := lineFor(t, report, "claude_code")+ if line.Installed {+ t.Fatal("claude_code reported as installed when the scanner never saw it")+ }+ if line.Status != CoverageSilent {+ t.Fatalf("status = %q, want silent", line.Status)+ }+}++// Installed names are the inventory scanner's spellings, which are not always harness names.+// Without normalization vscode would never join to vscode_copilot and would be reported as+// inactive alongside a covered vscode_copilot -- one runtime shown twice, once wrongly.+func TestCoverageNormalizesInstalledRuntimeNames(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "vscode_copilot", "s1", "gpt-4o", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(10)+ }),+ }+ report := Coverage(events, []string{"vscode"})+ if len(report.Runtimes) != 1 {+ t.Fatalf("got %d runtimes, want 1 -- vscode and vscode_copilot are one runtime: %+v", len(report.Runtimes), report.Runtimes)+ }+ line := lineFor(t, report, "vscode_copilot")+ if !line.Installed || line.Status != CoverageCovered {+ t.Fatalf("line = %+v, want installed and covered", line)+ }+}++// Coverage counts usage through the same pipeline the report totals use. Claude Code emits the+// same tokens on both a log record and a metric; if coverage counted raw gen_ai.usage blocks it+// would credit a runtime for usage the report then discards as a duplicate.+func TestCoverageCountsUsageThroughTheSamePipelineAsTheReport(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-opus-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ }),+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-opus-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ e.Raw = map[string]interface{}{"metric_name": "claude_code.token.usage"}+ }),+ }+ report := Coverage(events, []string{"claude_code"})+ aggregate := Aggregate(events, Options{})+ if got := lineFor(t, report, "claude_code").Tokens; got != aggregate.Totals.TotalTokens() {+ t.Fatalf("coverage tokens = %d, report totals = %d; they must agree", got, aggregate.Totals.TotalTokens())+ }+}++// Silent rows are the only ones anyone acts on, so they sort first regardless of spend.+func TestCoverageSortsSilentRuntimesFirst(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-opus-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(1_000_000)+ }),+ plainEvent("codex_cli"),+ }+ report := Coverage(events, nil)+ if report.Runtimes[0].Harness != "codex_cli" {+ t.Fatalf("first row = %q, want the silent codex_cli ahead of the high-spend covered row", report.Runtimes[0].Harness)+ }+}++// A coverage report over an empty window says nothing at all, and must say so rather than+// rendering an empty table that reads like a clean bill of health.+func TestRenderCoverageTextSaysWhenTheWindowIsEmpty(t *testing.T) {+ var sb strings.Builder+ RenderCoverageText(&sb, Coverage(nil, nil))+ if !strings.Contains(sb.String(), "No events in this window") {+ t.Fatalf("empty-window report did not say so:\n%s", sb.String())+ }+}++func TestRenderCoverageTextExplainsSilentRuntimes(t *testing.T) {+ var sb strings.Builder+ RenderCoverageText(&sb, Coverage([]schema.Event{plainEvent("claude_code")}, nil))+ out := sb.String()+ if !strings.Contains(out, "silent") || !strings.Contains(out, "beacon endpoint diagnostics") {+ t.Fatalf("silent report did not tell the reader what to do:\n%s", out)+ }+}++// Every expectation entry must key on a name that survives normalization, or the lookup silently+// misses and the runtime is reported as an unrecognized generic-OTLP one.+func TestUsageExpectationKeysAreCanonicalHarnessNames(t *testing.T) {+ for name := range usageExpectation {+ if got := normalizedHarnessForTest(name); got != name {+ t.Errorf("expectation key %q normalizes to %q; the lookup would never hit it", name, got)+ }+ }+}diff --git a/cli/beacon/internal/tokens/report.go b/cli/beacon/internal/tokens/report.goindex c4800d07..b2325f99 100644--- a/cli/beacon/internal/tokens/report.go+++ b/cli/beacon/internal/tokens/report.go@@ -119,3 +119,37 @@ func formatCost(cost float64) string {}return fmt.Sprintf("%.4f", cost)}++// RenderCoverageText writes the token coverage report: which runtimes contributed token telemetry+// in the window and which did not.+//+// Silent rows are the point of the report, so the summary line leads with them and the table is+// sorted to put them first. A reader who only reads one line should learn whether anything needs+// investigating.+func RenderCoverageText(w io.Writer, report CoverageReport) {+ fmt.Fprintf(w, "Token coverage over %d events: %d runtime(s) reporting usage, %d silent\n",+ report.TotalEvents, report.Covered, report.Silent)+ if report.TotalEvents == 0 {+ fmt.Fprintln(w, "\nNo events in this window, so coverage cannot be judged. Widen --since/--until.")+ return+ }+ fmt.Fprintln(w)+ tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "RUNTIME\tSTATUS\tINSTALLED\tEVENTS\tUSAGE EVENTS\tTOKENS\tNOTE")+ for _, runtime := range report.Runtimes {+ installed := "no"+ if runtime.Installed {+ installed = "yes"+ }+ fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%d\t%d\t%s\n",+ runtime.Harness, runtime.Status, installed, runtime.Events,+ runtime.UsageEvents, runtime.Tokens, runtime.Reason)+ }+ tw.Flush()++ if report.Silent > 0 {+ fmt.Fprintln(w, "\nSilent runtimes produced events but no token usage, and Beacon is built to read")+ fmt.Fprintln(w, "usage from them. Check that the runtime is current and its hooks or OTLP export")+ fmt.Fprintln(w, "are still configured: beacon endpoint status, beacon endpoint diagnostics.")+ }+}diff --git a/docs/cli/token-usage.mdx b/docs/cli/token-usage.mdxindex 604ec8a8..e313d1af 100644--- a/docs/cli/token-usage.mdx+++ b/docs/cli/token-usage.mdx@@ -41,6 +41,39 @@ A few rules shape how the numbers read:Beacon does not turn Codex token counts into `cost_usd`. A future report may show a separately labeled estimate with the pricing source, effective date, model, and service tier. Unknown models must remain unknown rather than reading as zero cost, and reasoning tokens must not be charged a second time because they are already included in output.+## Checking coverage++A usage report answers "what did I spend". It cannot answer "is this all of it", and that is the question to settle before treating a number as a bill. A runtime whose telemetry never arrives looks exactly like a runtime nobody used: both are simply absent from every rollup, so a total can omit an entire agent and still look complete.++```bash title="Check which runtimes are contributing token telemetry"+beacon token-usage --coverage+```++```+Token coverage over 4812 events: 3 runtime(s) reporting usage, 1 silent++RUNTIME STATUS INSTALLED EVENTS USAGE EVENTS TOKENS NOTE+codex_cli silent yes 412 0 0 per-turn usage trace; Codex emits no cost+claude_code covered yes 3106 288 4271883 OTLP token and cost telemetry+cline covered yes 190 12 283740 plugin reports usage once per task+cursor not_instrumented yes 1104 0 0 Cursor hook payloads carry no token counts+```++The status column is the report:++| Status | Meaning |+|--------|---------|+| `covered` | The runtime reported usage in the window. Nothing to do |+| `silent` | The runtime produced events but no usage, and Beacon is built to read usage from it. **This is the one to investigate** — a stale runtime build, a hook that stopped firing, or an OTLP export that is no longer configured |+| `inactive` | Installed, but produced no events at all in the window. Usually means it was not used |+| `not_instrumented` | The runtime ran, and Beacon cannot read token usage from it. Expected, not a fault. The note column says why |++The `not_instrumented` distinction is what makes the report worth reading. Without it Cursor would appear as a problem on every run, and a column that always shows a problem is a column people stop reading.++Coverage applies the `--since`, `--until` and `--harness` scopes, and deliberately ignores `--session`, `--model`, `--repository` and `--run-id`. Those filters select usage-bearing events almost by definition — an event carries no model unless it carried a model call — so a coverage report computed over them would find every runtime covered and prove nothing.++Add `--json` for the machine-readable form, which carries the same per-runtime rows plus `silent`, `covered` and `total_events` counts. A `silent` count above zero is the alertable condition.+## ExamplesShow token usage from the default per-user endpoint log: