Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(factory): emit settings token usage as deltas, not running totals

Claude5fd037111697
diff --git a/cli/beacon/internal/factorysession/collect.go b/cli/beacon/internal/factorysession/collect.go
index 8ec6935b..e82c87ab 100644
--- a/cli/beacon/internal/factorysession/collect.go
+++ b/cli/beacon/internal/factorysession/collect.go
@@ -22,6 +22,9 @@ type Cursor struct {
ModTimeUnixMS int64 `json:"mtime_ms,omitempty"`
SizeBytes int64 `json:"size_bytes,omitempty"`
SettingsUnixMS int64 `json:"settings_mtime_ms,omitempty"`
+ // Usage is the cumulative settings usage Beacon has already emitted for this session, the
+ // baseline the next token.usage delta is measured from. Nil means none has been emitted yet.
+ Usage *UsageTotals `json:"usage_totals,omitempty"`
}
type State struct {
@@ -157,7 +160,10 @@ func collectSession(store *Store, ref SessionRef, state *State, opts CollectOpti
cursor.LastLine = 0
cursor.Started = false
cursor.SettingsUnixMS = 0
+ // Usage stays: the session id is the same session, and its settings totals are still
+ // cumulative from the same start, so forgetting them would count them again.
}
+ seedLegacyUsageBaseline(cursor, ref)
if cursor.LastLine > 0 &&
cursor.ModTimeUnixMS == ref.ModTimeUnixMS &&
cursor.SizeBytes == ref.SizeBytes &&
@@ -177,6 +183,7 @@ func collectSession(store *Store, ref SessionRef, state *State, opts CollectOpti
MinLine: cursor.LastLine,
SkipSessionStarted: cursor.Started,
EmitSettingsUsage: emitSettingsUsage,
+ PreviousUsage: cursor.Usage,
})
for i, item := range mapped {
if err := emitEvent(item.Event, opts); err != nil {
@@ -189,9 +196,29 @@ func collectSession(store *Store, ref SessionRef, state *State, opts CollectOpti
}
}
advanceCursor(cursor, ref, stats)
+ // Committed only once every event is on disk, so a failed write retries the same delta. A
+ // settings file with no usable totals keeps the baseline it had.
+ if emitSettingsUsage {
+ if totals := SettingsUsageTotals(ref.Settings); totals != nil {
+ cursor.Usage = totals
+ }
+ }
return len(mapped) > 0 || stats.Lines != cursor.LastLine || emitSettingsUsage, nil
}
+// seedLegacyUsageBaseline upgrades state written before Beacon kept usage totals. That release
+// emitted the whole cumulative total each time the settings mtime changed, so a cursor that has a
+// settings mtime but no totals already holds a token.usage event for exactly the settings it
+// recorded. When the file is still at that mtime, its totals are what was emitted, and they become
+// the baseline instead of being counted again. A file that changed since then cannot be told
+// apart from first sight, so it is counted from zero, as that release would have.
+func seedLegacyUsageBaseline(cursor *Cursor, ref SessionRef) {
+ if cursor.Usage != nil || cursor.SettingsUnixMS == 0 || cursor.SettingsUnixMS != ref.SettingsUnixMS {
+ return
+ }
+ cursor.Usage = SettingsUsageTotals(ref.Settings)
+}
+
func advanceCursor(cursor *Cursor, ref SessionRef, stats ReadStats) {
cursor.SourcePath = ref.Path
cursor.LastLine = stats.Lines
diff --git a/cli/beacon/internal/factorysession/mapper.go b/cli/beacon/internal/factorysession/mapper.go
index b870f109..5f0116cd 100644
--- a/cli/beacon/internal/factorysession/mapper.go
+++ b/cli/beacon/internal/factorysession/mapper.go
@@ -17,6 +17,10 @@ type MapOptions struct {
MinLine int
SkipSessionStarted bool
EmitSettingsUsage bool
+ // PreviousUsage is the cumulative settings usage already emitted for the session; the
+ // token.usage event carries only what was added since. Nil emits the whole total, which is
+ // the delta from zero.
+ PreviousUsage *UsageTotals
}
func MapSession(ref SessionRef, records []Record, opts MapOptions) []MappedEvent {
@@ -193,26 +197,45 @@ func (m *mapper) rememberToolCalls(msg *Message) {
}
}
+// emitSettingsUsage reports what the session's settings totals grew by since the totals Beacon
+// last emitted. Factory rewrites <session-id>.settings.json with running session totals, not
+// per-turn usage, so emitting the totals themselves counted everything spent so far again on
+// every rewrite.
func (m *mapper) emitSettingsUsage(line int) {
- usage := m.ref.Settings.TokenUsage
- if usage == nil {
- usage = m.ref.Settings.InclusiveTokenUsage
+ current := SettingsUsageTotals(m.ref.Settings)
+ if current == nil {
+ return
+ }
+ var previous UsageTotals
+ if m.opts.PreviousUsage != nil {
+ previous = *m.opts.PreviousUsage
}
- if usage == nil {
+ delta := current.since(previous)
+ if delta.empty() {
return
}
record := &Record{Line: line, Type: "settings", Timestamp: unixMilliToRFC3339(m.ref.SettingsUnixMS)}
ev := m.base(record, "token.usage", "metric", schema.SeverityInfo, "Factory Droid token usage")
- ev.GenAI = &schema.GenAIInfo{Usage: usageInfo(usage)}
- raw := map[string]any{"source": "factory_settings"}
+ ev.GenAI = &schema.GenAIInfo{Usage: usageInfo(delta)}
+ raw := map[string]any{"token_source": "settings_totals_delta"}
if m.ref.Settings.AssistantActiveTimeMs > 0 {
raw["assistant_active_time_ms"] = m.ref.Settings.AssistantActiveTimeMs
}
- if usage.FactoryCredits > 0 {
- raw["factory_credits"] = usage.FactoryCredits
+ // Credits are Factory's own billing unit, not USD, so they stay in raw rather than
+ // gen_ai.usage.cost_usd. The delta sums like the tokens beside it; the total is the session's
+ // running figure as Factory stored it.
+ if delta.FactoryCredits > 0 {
+ raw["factory_credits_delta"] = delta.FactoryCredits
+ }
+ if current.FactoryCredits > 0 {
+ raw["factory_credits_total"] = current.FactoryCredits
}
ev.Raw = raw
- m.append(record, fmt.Sprintf("settings.usage.%d", m.ref.SettingsUnixMS), ev)
+ // Keyed on the totals rather than the settings mtime: the same totals always name the same
+ // event, however many times the file is rewritten around them.
+ m.append(record, fmt.Sprintf("settings.usage.%d.%d.%d.%d.%d.%g",
+ current.InputTokens, current.OutputTokens, current.CacheCreationTokens,
+ current.CacheReadTokens, current.ThinkingTokens, current.FactoryCredits), ev)
}
func (m *mapper) base(record *Record, action, category string, severity schema.Severity, message string) schema.Event {
@@ -374,7 +397,7 @@ func rawString(raw json.RawMessage) string {
return string(raw)
}
-func usageInfo(usage *TokenUsage) *schema.GenAIUsageInfo {
+func usageInfo(usage UsageTotals) *schema.GenAIUsageInfo {
info := &schema.GenAIUsageInfo{}
if usage.InputTokens > 0 {
info.InputTokens = int64Ptr(usage.InputTokens)
diff --git a/cli/beacon/internal/factorysession/types.go b/cli/beacon/internal/factorysession/types.go
index 5f38d105..b2a852c0 100644
--- a/cli/beacon/internal/factorysession/types.go
+++ b/cli/beacon/internal/factorysession/types.go
@@ -94,6 +94,81 @@ type TokenUsage struct {
FactoryCredits float64 `json:"factoryCredits"`
}
+// UsageTotals is one cumulative reading of a session's settings usage. It is also the shape of
+// the baseline the collector keeps per session.
+//
+// The fields follow Factory's own split, which is the Anthropic one: inputTokens counts uncached
+// input only, with cache reads and cache writes in fields of their own, so the canonical usage
+// carries them side by side without subtracting one from another.
+type UsageTotals struct {
+ InputTokens int64 `json:"input_tokens,omitempty"`
+ OutputTokens int64 `json:"output_tokens,omitempty"`
+ CacheCreationTokens int64 `json:"cache_creation_tokens,omitempty"`
+ CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
+ ThinkingTokens int64 `json:"thinking_tokens,omitempty"`
+ FactoryCredits float64 `json:"factory_credits,omitempty"`
+}
+
+// SettingsUsageTotals picks the session's own cumulative usage out of its settings.
+//
+// tokenUsage is the session's own usage. inclusiveTokenUsage adds the usage of the child sessions
+// listed in childInclusiveTokenUsageBySessionId; those children are Factory sessions with settings
+// of their own, which Beacon collects separately, so counting the inclusive total on the parent
+// would count each child twice. The inclusive total is used only when tokenUsage is absent and no
+// child is listed, the one case in which it is the session's own usage. Both readings are then the
+// same quantity, so a session whose settings move from one field to the other keeps one consistent
+// baseline.
+func SettingsUsageTotals(settings *Settings) *UsageTotals {
+ if settings == nil {
+ return nil
+ }
+ usage := settings.TokenUsage
+ if usage == nil && len(settings.ChildInclusiveTokenUsage) == 0 {
+ usage = settings.InclusiveTokenUsage
+ }
+ if usage == nil {
+ return nil
+ }
+ return &UsageTotals{
+ InputTokens: usage.InputTokens,
+ OutputTokens: usage.OutputTokens,
+ CacheCreationTokens: usage.CacheCreationTokens,
+ CacheReadTokens: usage.CacheReadTokens,
+ ThinkingTokens: usage.ThinkingTokens,
+ FactoryCredits: usage.FactoryCredits,
+ }
+}
+
+// since is how much each field grew from previous. A field that went down means the settings
+// were rewritten rather than that usage was refunded: it contributes nothing, and because the
+// collector then stores the lower reading as the new baseline, growth after the rewrite is still
+// counted. That is the per-field rule the Codex and Copilot session readers apply to their
+// cumulative totals; it can undercount across a rewrite but never double counts one.
+func (u UsageTotals) since(previous UsageTotals) UsageTotals {
+ grow := func(current, prior int64) int64 {
+ if current <= prior {
+ return 0
+ }
+ return current - prior
+ }
+ credits := u.FactoryCredits - previous.FactoryCredits
+ if credits < 0 {
+ credits = 0
+ }
+ return UsageTotals{
+ InputTokens: grow(u.InputTokens, previous.InputTokens),
+ OutputTokens: grow(u.OutputTokens, previous.OutputTokens),
+ CacheCreationTokens: grow(u.CacheCreationTokens, previous.CacheCreationTokens),
+ CacheReadTokens: grow(u.CacheReadTokens, previous.CacheReadTokens),
+ ThinkingTokens: grow(u.ThinkingTokens, previous.ThinkingTokens),
+ FactoryCredits: credits,
+ }
+}
+
+func (u UsageTotals) empty() bool {
+ return u == UsageTotals{}
+}
+
type MappedEvent struct {
SourceLine int
DedupID string
diff --git a/cli/beacon/internal/factorysession/usage_test.go b/cli/beacon/internal/factorysession/usage_test.go
new file mode 100644
index 00000000..660d0e82
--- /dev/null
+++ b/cli/beacon/internal/factorysession/usage_test.go
@@ -0,0 +1,282 @@
+package factorysession
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
+)
+
+// usageFixture is one Factory session on disk whose settings file a test rewrites between sweeps,
+// the way Droid rewrites <session-id>.settings.json with new cumulative totals after each turn.
+type usageFixture struct {
+ t *testing.T
+ root string
+ sessionPath string
+ settingsPath string
+ statePath string
+ out bytes.Buffer
+ settingsTick time.Time
+}
+
+func newUsageFixture(t *testing.T) *usageFixture {
+ t.Helper()
+ root := t.TempDir()
+ project := filepath.Join(root, "-repo")
+ if err := os.MkdirAll(project, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ f := &usageFixture{
+ t: t,
+ root: root,
+ sessionPath: filepath.Join(project, "session-1.jsonl"),
+ settingsPath: filepath.Join(project, "session-1.settings.json"),
+ statePath: filepath.Join(t.TempDir(), "factory-state.json"),
+ settingsTick: time.Unix(1770000000, 0),
+ }
+ writeFile(t, f.sessionPath,
+ `{"type":"session_start","id":"session-1","title":"hi","cwd":"/repo"}`+"\n"+
+ `{"type":"message","id":"u1","timestamp":"2026-05-16T22:11:04.611Z","message":{"role":"user","content":[{"type":"text","text":"hello"}]}}`+"\n")
+ return f
+}
+
+// writeSettings replaces the settings file and moves its mtime forward a second, so every
+// rewrite is visible to the collector even on filesystems with coarse timestamps.
+func (f *usageFixture) writeSettings(body string) {
+ f.t.Helper()
+ writeFile(f.t, f.settingsPath, body)
+ f.settingsTick = f.settingsTick.Add(time.Second)
+ if err := os.Chtimes(f.settingsPath, f.settingsTick, f.settingsTick); err != nil {
+ f.t.Fatal(err)
+ }
+}
+
+func (f *usageFixture) sweep() Summary {
+ f.t.Helper()
+ summary, err := CollectOnce(CollectOptions{SessionsDir: f.root, StatePath: f.statePath, Print: true, Out: &f.out})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return summary
+}
+
+func (f *usageFixture) events() []schema.Event {
+ f.t.Helper()
+ var events []schema.Event
+ scanner := bufio.NewScanner(bytes.NewReader(f.out.Bytes()))
+ scanner.Buffer(make([]byte, 0, 64*1024), 4<<20)
+ for scanner.Scan() {
+ var ev schema.Event
+ if err := json.Unmarshal(scanner.Bytes(), &ev); err != nil {
+ f.t.Fatal(err)
+ }
+ events = append(events, ev)
+ }
+ return events
+}
+
+func (f *usageFixture) usageEvents() []schema.Event {
+ var out []schema.Event
+ for _, ev := range f.events() {
+ if ev.Event.Action == "token.usage" {
+ out = append(out, ev)
+ }
+ }
+ return out
+}
+
+// Factory keeps tokenUsage as the session's running total, so the sum of what Beacon emits across
+// several settings rewrites must equal the final total, not the sum of every total it saw.
+func TestCollectOnceEmitsFactorySettingsUsageAsDeltas(t *testing.T) {
+ f := newUsageFixture(t)
+ f.writeSettings(`{"model":"claude-opus-4-7","tokenUsage":{"inputTokens":100,"outputTokens":10,"cacheCreationTokens":1000,"cacheReadTokens":5000,"thinkingTokens":4,"factoryCredits":1.5}}`)
+ f.sweep()
+ f.writeSettings(`{"model":"claude-opus-4-7","tokenUsage":{"inputTokens":250,"outputTokens":30,"cacheCreationTokens":1200,"cacheReadTokens":12000,"thinkingTokens":9,"factoryCredits":3.25}}`)
+ f.sweep()
+ // A rewrite that leaves the totals alone (Droid also stores the model, active time and
+ // other settings there) is not new spend.
+ f.writeSettings(`{"model":"claude-opus-4-7","assistantActiveTimeMs":900,"tokenUsage":{"inputTokens":250,"outputTokens":30,"cacheCreationTokens":1200,"cacheReadTokens":12000,"thinkingTokens":9,"factoryCredits":3.25}}`)
+ if summary := f.sweep(); summary.EventsEmitted != 0 {
+ t.Fatalf("unchanged totals emitted %d events, want 0", summary.EventsEmitted)
+ }
+ f.writeSettings(`{"model":"claude-opus-4-7","tokenUsage":{"inputTokens":400,"outputTokens":75,"cacheCreationTokens":1500,"cacheReadTokens":20000,"thinkingTokens":20,"factoryCredits":6}}`)
+ f.sweep()
+ // A re-run over a store that has not changed emits nothing.
+ if summary := f.sweep(); summary.EventsEmitted != 0 {
+ t.Fatalf("idempotent re-run emitted %d events, want 0", summary.EventsEmitted)
+ }
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ want := tokens.Usage{
+ InputTokens: 400,
+ OutputTokens: 75,
+ CacheCreationInputTokens: 1500,
+ CacheReadInputTokens: 20000,
+ ReasoningOutputTokens: 20,
+ Events: 3,
+ }
+ if report.Totals != want {
+ t.Fatalf("aggregated totals = %+v, want the final cumulative value %+v", report.Totals, want)
+ }
+
+ usage := f.usageEvents()
+ if len(usage) != 3 {
+ t.Fatalf("token.usage events = %d, want 3", len(usage))
+ }
+ ids := map[string]bool{}
+ var credits float64
+ for _, ev := range usage {
+ if ids[ev.Event.ID] {
+ t.Fatalf("duplicate event id %s", ev.Event.ID)
+ }
+ ids[ev.Event.ID] = true
+ if ev.GenAI.Usage.CostUSD != nil {
+ t.Fatalf("Factory credits are not USD; cost_usd = %v", *ev.GenAI.Usage.CostUSD)
+ }
+ credits += ev.Raw["factory_credits_delta"].(float64)
+ }
+ if credits != 6 {
+ t.Fatalf("summed factory_credits_delta = %v, want the final total 6", credits)
+ }
+ last := usage[len(usage)-1]
+ if got := last.Raw["factory_credits_total"]; got != 6.0 {
+ t.Fatalf("factory_credits_total = %v, want 6", got)
+ }
+ if got := *last.GenAI.Usage.InputTokens; got != 150 {
+ t.Fatalf("last delta input = %d, want 150", got)
+ }
+}
+
+// A field that goes down is a rewritten settings file, not negative spend. It emits nothing for
+// that field and the lower value becomes the baseline, so growth after the rewrite still counts.
+func TestCollectOnceFactoryUsageDecreaseRebases(t *testing.T) {
+ f := newUsageFixture(t)
+ f.writeSettings(`{"tokenUsage":{"inputTokens":100,"outputTokens":50}}`)
+ f.sweep()
+ f.writeSettings(`{"tokenUsage":{"inputTokens":40,"outputTokens":60}}`)
+ f.sweep()
+ f.writeSettings(`{"tokenUsage":{"inputTokens":70,"outputTokens":60}}`)
+ f.sweep()
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ if report.Totals.InputTokens != 130 || report.Totals.OutputTokens != 60 {
+ t.Fatalf("totals = %+v, want input 100+0+30=130 and output 50+10=60", report.Totals)
+ }
+ for _, ev := range f.usageEvents() {
+ u := ev.GenAI.Usage
+ if (u.InputTokens != nil && *u.InputTokens < 0) || (u.OutputTokens != nil && *u.OutputTokens < 0) {
+ t.Fatalf("negative delta emitted: %+v", u)
+ }
+ }
+}
+
+// inclusiveTokenUsage adds the usage of the session's child (subagent) sessions, which Factory
+// stores as sessions of their own and Beacon collects separately. Counting it on the parent would
+// count every child twice, so it is used only when it cannot include a child.
+func TestCollectOnceFactoryInclusiveUsageNeverDoubleCountsChildren(t *testing.T) {
+ f := newUsageFixture(t)
+ // Older settings without tokenUsage and no children: inclusive is the session's own usage.
+ f.writeSettings(`{"inclusiveTokenUsage":{"inputTokens":100,"outputTokens":10}}`)
+ f.sweep()
+ // tokenUsage appears alongside an inclusive total that now counts a child session.
+ f.writeSettings(`{"tokenUsage":{"inputTokens":150,"outputTokens":20},"inclusiveTokenUsage":{"inputTokens":900,"outputTokens":90},"childInclusiveTokenUsageBySessionId":{"child-1":{"inputTokens":750,"outputTokens":70}}}`)
+ f.sweep()
+ // Only the inclusive total is present while a child is: nothing of the parent's own usage
+ // can be separated out, so nothing is emitted and the baseline stays.
+ f.writeSettings(`{"inclusiveTokenUsage":{"inputTokens":1000,"outputTokens":100},"childInclusiveTokenUsageBySessionId":{"child-1":{"inputTokens":800,"outputTokens":75}}}`)
+ if summary := f.sweep(); summary.EventsEmitted != 0 {
+ t.Fatalf("inclusive-with-children sweep emitted %d events, want 0", summary.EventsEmitted)
+ }
+ f.writeSettings(`{"tokenUsage":{"inputTokens":200,"outputTokens":25},"inclusiveTokenUsage":{"inputTokens":1000,"outputTokens":100},"childInclusiveTokenUsageBySessionId":{"child-1":{"inputTokens":800,"outputTokens":75}}}`)
+ f.sweep()
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ if report.Totals.InputTokens != 200 || report.Totals.OutputTokens != 25 {
+ t.Fatalf("totals = %+v, want the session's own final usage 200/25", report.Totals)
+ }
+}
+
+// State written before Beacon tracked the totals already holds a token.usage event for the
+// settings it last saw. Upgrading must not count that total a second time.
+func TestCollectOnceFactoryUsageUpgradeSeedsBaselineFromUnchangedSettings(t *testing.T) {
+ f := newUsageFixture(t)
+ f.writeSettings(`{"tokenUsage":{"inputTokens":100,"outputTokens":10}}`)
+ f.sweep()
+
+ state, err := LoadState(f.statePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // What the previous release stored: the settings mtime, no totals.
+ state.Sessions["session-1"].Usage = nil
+ if err := state.Save(f.statePath); err != nil {
+ t.Fatal(err)
+ }
+ if summary := f.sweep(); summary.EventsEmitted != 0 {
+ t.Fatalf("upgrade sweep emitted %d events, want 0", summary.EventsEmitted)
+ }
+ f.writeSettings(`{"tokenUsage":{"inputTokens":160,"outputTokens":12}}`)
+ f.sweep()
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ if report.Totals.InputTokens != 160 || report.Totals.OutputTokens != 12 {
+ t.Fatalf("totals = %+v, want 160/12", report.Totals)
+ }
+}
+
+// The collector re-reads a session whose file moved (a renamed working directory) from the top,
+// but its settings totals are the same running figure, so they are not counted again.
+func TestCollectOnceFactoryUsageSurvivesAMovedSession(t *testing.T) {
+ f := newUsageFixture(t)
+ f.writeSettings(`{"tokenUsage":{"inputTokens":100,"outputTokens":10}}`)
+ f.sweep()
+
+ moved := filepath.Join(f.root, "-repo2")
+ if err := os.Rename(filepath.Dir(f.sessionPath), moved); err != nil {
+ t.Fatal(err)
+ }
+ f.sessionPath = filepath.Join(moved, "session-1.jsonl")
+ f.settingsPath = filepath.Join(moved, "session-1.settings.json")
+ f.sweep()
+ f.writeSettings(`{"tokenUsage":{"inputTokens":130,"outputTokens":10}}`)
+ f.sweep()
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ if report.Totals.InputTokens != 130 || report.Totals.OutputTokens != 10 {
+ t.Fatalf("totals = %+v, want 130/10", report.Totals)
+ }
+}
+
+// A write that fails leaves the totals uncommitted, so the retry emits the same delta again
+// rather than losing it.
+func TestCollectOnceFactoryUsageRetriesAfterFailedWrite(t *testing.T) {
+ f := newUsageFixture(t)
+ f.writeSettings(`{"tokenUsage":{"inputTokens":100,"outputTokens":10}}`)
+ f.sweep()
+ f.writeSettings(`{"tokenUsage":{"inputTokens":180,"outputTokens":15}}`)
+
+ original := emitEvent
+ emitEvent = func(event schema.Event, opts CollectOptions) error {
+ if event.Event.Action == "token.usage" {
+ return os.ErrPermission
+ }
+ return original(event, opts)
+ }
+ _, err := CollectOnce(CollectOptions{SessionsDir: f.root, StatePath: f.statePath, Print: true, Out: &f.out})
+ emitEvent = original
+ if err == nil {
+ t.Fatal("expected the failed write to surface")
+ }
+ f.sweep()
+
+ report := tokens.Aggregate(f.events(), tokens.Options{})
+ if report.Totals.InputTokens != 180 || report.Totals.OutputTokens != 15 {
+ t.Fatalf("totals = %+v, want 180/15", report.Totals)
+ }
+}
diff --git a/docs/runtimes/factory-droid.mdx b/docs/runtimes/factory-droid.mdx
index fa1e3d60..f283c246 100644
--- a/docs/runtimes/factory-droid.mdx
+++ b/docs/runtimes/factory-droid.mdx
@@ -57,6 +57,7 @@ For scheduled collection, run `beacon endpoint factory sync --watch`, or run one
| Prompt telemetry | Supported through `UserPromptSubmit` hooks |
| Command, tool, and file telemetry | Supported for session, write/edit/create hook payloads, committed session tool calls/results, stop, session-end, and available OTLP telemetry |
| Historical sessions | Supported through `beacon endpoint factory sync`, which reads `~/.factory/sessions` locally and offline |
+| Token usage | `sync` reads the running totals Factory keeps in each session's `.settings.json` and emits a `token.usage` event with only what they grew by since the last sync, so `beacon token-usage` sums to the session's final total. It counts the session's own `tokenUsage`; `inclusiveTokenUsage` is used only when `tokenUsage` is absent and no child session is listed, because it adds child sessions, which are synced on their own. A total that goes down is treated as a rewritten file and counts nothing. Factory credits are not USD, so they stay in `raw` (`factory_credits_delta`, `factory_credits_total`) rather than `cost_usd` |
| Local JSONL and dashboard | Supported |
| MDM deployment | Supported for the endpoint agent. Factory launch environment and user/project hooks are managed in the user's Droid context |