fix(workflow): net cache hits from token totals, trim gate-retry output

Confirmed in production (task 6, 2026-09-02): dashboard/PR summaries
showed raw prompt-token sums with no cache accounting -- 360,018 of a
reported 400,021 "prompt tokens" were cache hits billed at a steep
discount, not full price. Real fresh spend was ~40,003 tokens, roughly
10x less than the headline number implied. Nothing was double-counted;
the totals were internally consistent, just presented misleadingly.

Adds TaskContext.RunUsage (in-memory, presentation-only) and
formatTokenUsage, rendering "N tokens (F fresh + C cached)" in PR
bodies and the dashboard timeline instead of a raw sum, falling back
to the plain total when no breakdown is available.

Also trims StageBaselineGate's retry-mission prompt to failing-only
go test output via extractFailingGateOutput -- the full passing-
package listing was a direct, mechanical contributor to the growing
per-iteration prompt sizes on every gate-repair retry, not just a
display problem. Degrades to unchanged output for non-Go gates or
unrecognized shapes.
This commit is contained in:
sam committed 2026-09-02 21:28:49 +10:00
1 parent 1bead14717
commit 322e081365
8 files changed
+227 -11

No files matched your search

+2
View File
@@ -91,6 +91,8 @@
{"_type":"issue","id":"archie-core-g7tm","title":"telegram: finalize the reply through a live context, matching the error branch","description":"The success path calls live.finalize(turnCtx, reply) with the raw cancellable turn context (telegram.go:582), while the error branch two lines above deliberately uses context.WithoutCancel(turnCtx). If /stop lands during finalize, the rich edit, the plain-text retry, and the split-send fallback all abort with context.Canceled (go-telegram/bot builds requests with NewRequestWithContext), so the authoritative reply is never delivered and the live message keeps the ▌ cursor forever. The reply is persisted to the ledger, so the loss is delivery-level — but the user sees a frozen half-answer.\n\nFailure: a long tool-using turn is /stop-ped as it completes; turnCtx is cancelled mid-finalize; every send fails on the dead context; the chat shows the last live frame with a blinking cursor and no final answer.\n\nFound by code-review of PR #476 (feat/467, merged 98e8dda).","design":"live.finalize(context.WithoutCancel(turnCtx), reply) — the one-liner the error branch already uses. Consider making finalize take a live context internally rather than trusting each caller to remember.","acceptance_criteria":"A /stop landing mid-finalize still delivers the authoritative reply and drops the cursor; a test covers the cancellable-context finalize path.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:08Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:07:36Z","started_at":"2026-08-14T14:53:28Z","closed_at":"2026-08-14T15:03:28Z","close_reason":"Fixed in internal/channels/telegram/live.go and telegram.go: finalize/abandon strip context cancellation before sending (mirroring each other), ToolCall escapes Markdown metacharacters via bot.EscapeMarkdown, splitLongMessage splits on rune boundaries. All new/changed tests verified red-then-green; task check clean; adversarial review pass found no blocking issues.","external_ref":"https://github.com/samcharles93/archie-core/issues/484","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-tb3a","title":"Fix streaming review blockers for inline tool calls","description":"Resolve the four evidence-gated findings in merged inline tool-call streaming: preserve the authoritative Telegram reply when final edits fail; keep Telegram network I/O off the model FullStream consumer and cancellable; correlate tool inputs with results and render a bounded redacted parameter summary; snapshot show_tool_calls per live reply to avoid reload races. Add regression tests for every path and run task check plus lint/race validation.","acceptance_criteria":"Regression tests fail on the merged implementation and pass after the fix. Final edit failure falls back to normal split delivery. Delta and ToolCall callbacks do not wait on Telegram HTTP and stop cancels in-flight rendering. Completed tool events include bounded redacted parameters correlated by tool-call ID. Reload cannot race an in-flight reply's show_tool_calls setting. task check passes, golangci-lint reports no new findings, and focused race tests pass.","notes":"Implemented in worktree /tmp/archie-core-tb3a on branch fix/archie-core-tb3a. Added cancellable async Telegram rendering, final edit failure fallback through normal split delivery, call-ID-correlated bounded conservative parameter summaries, atomic per-reply show_tool_calls snapshots, SSE/UI parameter rendering, rebuilt ui/dist, and regression tests. Validation: GOFLAGS=-buildvcs=false task check passed; golangci-lint --new-from-rev=HEAD ./... reported 0 issues; focused race suite passed; fresh adversarial reviewer reported PASS with zero findings. Plain task check is blocked in linked worktrees by Go VCS stamping exit 128, hence buildvcs override.\n2026-08-24 reconciliation: the close reason's 'worktree left uncommitted' is stale. The work did land on main via ba33527 (Merge pull request #477 from samcharles93/fix/archie-core-tb3a); verified on main: gateway/stream.go sensitiveParameterKey+redactToolParameters, telegram/live.go per-reply showToolCalls snapshot, webui/api_chat.go gating. The /tmp/archie-core-tb3a worktree and its branch are gone, as expected.\n","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T18:05:35Z","created_by":"Sam Catlow","updated_at":"2026-08-24T07:29:09Z","started_at":"2026-08-13T18:05:39Z","closed_at":"2026-08-13T18:35:26Z","close_reason":"Completed and independently reviewed; worktree left uncommitted per conservative repository policy.","external_ref":"https://github.com/samcharles93/archie-core/issues/485","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-dzx","title":"Remove duplicate archie-agent safe.directory setup","description":"## Problem\\ncmd/archie-agent/main.go configures git safe.directory inline and then calls markWorktreeSafe, so startup writes the same global git configuration twice.\\n\\n## Scope\\nKeep markWorktreeSafe as the single tested production path and remove the older inline exec.Command block/import. Add regression coverage proving startup wiring has exactly one authoritative safe-directory call.\\n\\n## Acceptance\\n- archie-agent startup invokes markWorktreeSafe exactly once\\n- no second inline safe.directory command remains in main.go\\n- cmd/archie-agent tests and repository quality gate pass","acceptance_criteria":"Single tested safe.directory setup path remains; duplicate inline command is removed; tests and task check pass","notes":"Red proof: TestMainConfiguresWorktreeSafetyOnce failed with 2 setup paths before implementation. Green proof: go test/vet/build ./cmd/archie-agent/... passed; golangci-lint --new-from-rev=HEAD reported 0 issues. Fresh adversarial review found no blockers. Full task check was not run because the working tree contains unrelated in-progress changes and task check rewrites files; scoped package gate used per repository protocol.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:09Z","created_by":"Sam Catlow","updated_at":"2026-08-13T16:13:48Z","started_at":"2026-08-13T16:10:24Z","closed_at":"2026-08-13T16:13:48Z","close_reason":"Removed duplicate inline safe.directory setup; markWorktreeSafe is now the single tested production path","external_ref":"https://github.com/samcharles93/archie-core/issues/470","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-rwzo","title":"Token usage totals mislead: raw prompt sum not netted against cache hits","description":"Confirmed on production task 6 (2026-09-02, carina): dashboard/PR summary showed '14 iterations · 405,004 tokens · 400,021 prompt · 4,983 completion · 360,018 cached'. Cross-checked against the per-iteration daemon log: nothing is double-counted or hardcoded -- the totals are the correct sum of 14 real, separately-billed API calls with growing context. But 360,018 of the 400,021 'prompt tokens' shown were cache hits (billed at a steep discount), not full price -- real fresh spend was ~40,003 tokens. Showing only the raw prompt-token sum makes every agent run's cost read roughly 10x worse than what was actually billed, everywhere this aggregate surfaces (PR body, dashboard timeline).\n\nSeparately (real, not just cosmetic cost): StageBaselineGate's retry-mission prompt re-injected the ENTIRE go test ./... output -- hundreds of lines covering every passing package -- into every retry iteration's prompt, not just the failing ones. Direct mechanical contributor to the growing per-iteration prompt sizes.","design":"TaskContext.RunUsage (in-memory, not persisted -- Task.TokensUsed remains authoritative) accumulates agentexec.Usage across every agent run in one workflow execution. formatTokenUsage(total, usage) renders 'N tokens (F fresh + C cached)' with a plain fallback. extractFailingGateOutput(s) strips go test 'ok' package lines, only when it recognizes --- FAIL:/FAIL\\t markers, else returns input unchanged. Known gap: a task resumed after a daemon restart mid-workflow loses RunUsage and falls back to the plain total -- an honest degrade, not a bug; persisting the breakdown would need a store migration for a purely presentational value, not worth it yet.","acceptance_criteria":"PR bodies and the dashboard timeline show a fresh-vs-cached breakdown (or an equivalent net figure) instead of a raw prompt-token sum, falling back gracefully when no usage breakdown is available. Gate-retry mission prompts drop passing-package output, keeping only failure-relevant content, with graceful degradation for non-Go gates or unrecognized output shapes. task check passes.","status":"closed","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-02T11:28:39Z","created_by":"Sam Catlow","updated_at":"2026-09-02T11:28:49Z","closed_at":"2026-09-02T11:28:49Z","close_reason":"Added TaskContext.RunUsage + accumulateUsage (agent.go, implement.go's baseline-fix branch) and formatTokenUsage (workflow.go), wired into implement.go's and tdd.go's PR-body footers plus ui/src/tasks/timeline-event.js's agent_finish rendering (raw prompt replaced with computed fresh = prompt - cached). Added extractFailingGateOutput (workflow.go) trimming go test 'ok' package lines from StageBaselineGate's retry mission, degrading to unchanged output when no --- FAIL:/FAIL\\t marker survives the filter. 5 new Go tests, 1 updated JS test. task check clean, 100/100 JS tests.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-n2pv","title":"Dashboard Logs page never surfaces per-task attempt-log detail","description":"internal/webui/api_tasks_logs.go's handleTaskLogs (GET /api/tasks/{id}/logs) was fully working -- internal/logging/reader.go's decode() already captures every JSON field generically into Entry.Fields (stage, tokens, iterations, model, stop_reason, everything). But no frontend code called it: ui/src/logs/logs.js (the dashboard's only Logs page) exclusively called api.logs(), the daemon-wide feed, which only carries the daemon's own component-scoped Info/Warn/Error lines -- never the rich per-stage/per-agent-run detail that lives in a task's own per-attempt log file. An operator could never see why a specific task took as long as it did, what each workflow stage did, or its token spend breakdown from the dashboard, even though the daemon already recorded and could already serve all of it. Discovered while investigating production task 6 (2026-09-02, archie-core-95dj).","acceptance_criteria":"A task's persisted attempt log (stage timings, iteration counts, token/prompt/completion/cached breakdowns, model) is visible from the dashboard task view. Reuses the daemon-wide log page's row-rendering logic rather than duplicating it. Handles disabled/empty/error states without crashing. task check (including task test:ui) passes.","status":"closed","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-02T11:26:44Z","created_by":"Sam Catlow","updated_at":"2026-09-02T11:26:52Z","closed_at":"2026-09-02T11:26:52Z","close_reason":"Added ui/src/base/log-row.js (row rendering extracted out of logs.js, shared -- second consumer per CLAUDE.md), ui/src/tasks/task-logs.js (taskLogPanel handling loading/error/disabled/empty/populated states), api.taskLogs() in ui/src/base/api.js, and a collapsible 'Attempt log' section wired into each task's existing timeline drill-down in ui/src/tasks/tasks.js -- lazily fetched on first expand. New tests: ui/test/log-row.test.js, ui/test/task-logs.test.js. task check clean, 100/100 JS tests.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-1786637499161-356-e424e40d.1","title":"setupMemory never calls RegisterExternal; cfg.Memory.Provider is silently inert","description":"internal/app/archied/bootstrap.go:setupMemory's own doc comment says\n\"External providers from config are added via RegisterExternal when\ncfg.Memory.Provider is set\" -- no such branch exists in the function body.\nToday, an operator who sets [memory] provider = \"...\" in config.toml gets\nno error and no effect: the builtin file-backed provider is the only one\nthat ever runs. config.example.toml already documents this as a known gap\n(\"[memory] exists to register an EXTERNAL provider alongside it, but as of\nthis writing that wiring ... is not called\").\n\nSeparately, internal/config.MemoryConfig (config.go:287) has no `toml`\nstruct tag on any field (yaml/json only), so even fixing the wiring call\nmay not bind values from config.toml, the format operators actually use --\nverify this before or as part of the fix.\n\nThis sits ahead of the typed engine-family work (archie-core-...-11-e245c170)\nin the sense that it's a bug in the CURRENT ad-hoc MemoryProvider wiring,\nnot a gap in the future engine contract -- decide whether it's worth fixing\nin the legacy path or superseded once the conforming memory engine family\nlands, rather than fixing both.","status":"closed","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-01T15:50:52Z","created_by":"Sam Catlow","updated_at":"2026-09-01T16:51:00Z","closed_at":"2026-09-01T16:51:00Z","close_reason":"Fixed, but not as originally framed. Investigated wiring RegisterExternal\nfor real: there is no external MemoryProvider implementation anywhere in\nthe repo to construct and pass to it (only internal/memory/builtin.Provider\nexists) -- calling RegisterExternal would be dead plumbing to nothing, not\na fix.\n\nThe actual fix: configuration.validateMemory now rejects memory.provider\nbeing set at all, with a clear reason, instead of accepting it and doing\nnothing. Turns the silent no-op into a loud one. setupMemory's doc comment\nand config.example.toml updated to match; the now-pointless\nprovider_config example section removed.\n\ntoml struct tags (the other half of this bug) were already fixed in\narchie-core-1786637490043's commit.\n\nDrop the rejection once a real external provider (or the domain/memory\nengine family's Honcho proof, archie-core-1786637492031) gives the field\nan effect again.\n\nTestValidateMemoryRejectsProviderSetToAnything covers it. task check is\ngreen.","external_ref":"https://github.com/samcharles93/archie-core/issues/649","labels":["epic"],"dependencies":[{"issue_id":"archie-core-1786637499161-356-e424e40d.1","depends_on_id":"archie-core-1786637499161-356-e424e40d","type":"parent-child","created_at":"2026-09-01T15:50:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-r3gh","title":"Harden task origin response assertions","description":"Replace brittle prose substring assertions in internal/webui/api_tasks_origin_test.go with stable structural checks for HTTP error responses while preserving origin and media-type coverage.","acceptance_criteria":"The origin test does not assert human-readable response text; rejected cases verify stable HTTP error response structure; focused tests and task check pass.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-31T12:49:20Z","created_by":"Sam Catlow","updated_at":"2026-09-02T09:49:05Z","started_at":"2026-08-31T12:49:27Z","lease_expires_at":"2026-08-31T12:54:27Z","heartbeat_at":"2026-08-31T12:49:27Z","external_ref":"https://github.com/samcharles93/archie-core/issues/664","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-h3w2","title":"Migrate email/webhook channels onto domain/messaging types","description":"Update remaining gateway-based channels (email, webhook) to use domain/messaging types, completing the migration described in migration-decisions.md section 2.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-31T10:12:16Z","created_by":"Sam Catlow","updated_at":"2026-09-02T09:49:06Z","external_ref":"https://github.com/samcharles93/archie-core/issues/665","labels":["messaging-migration"],"dependencies":[{"issue_id":"archie-core-h3w2","depends_on_id":"archie-core-d9dv","type":"blocks","created_at":"2026-08-31T10:12:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
+12
View File
@@ -179,6 +179,7 @@ func (a AgentStage) handleResult(
}
tc.Task.TokensUsed += res.TokensUsed
tc.Task.Iterations += res.Iterations
accumulateUsage(&tc.RunUsage, res.Usage)
if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, a.Name, res.Summary, agentFinishData(res, modelRef)); emitErr != nil {
return fmt.Errorf("persist agent finish: %w", emitErr)
}
@@ -245,6 +246,17 @@ func modelContextBudget(cfg config.Config, modelRef string) int {
return limits.ContextWindow - limits.MaxOutputTokens
}
// accumulateUsage adds a single agent run's token breakdown onto a
// workflow-run running total. Extracted so every accumulation site (agent.go
// and implement.go's baseline-fix repair loop) stays in sync.
func accumulateUsage(total *agentexec.Usage, delta agentexec.Usage) {
total.PromptTokens += delta.PromptTokens
total.CompletionTokens += delta.CompletionTokens
total.TotalTokens += delta.TotalTokens
total.CachedTokens += delta.CachedTokens
total.CacheCreationTokens += delta.CacheCreationTokens
}
func agentFinishData(res agentexec.Result, modelRef string) map[string]any {
return map[string]any{
"status": res.Status, "stop_reason": res.StopReason,
+14 -5
View File
@@ -62,7 +62,8 @@ func StageBaselineGate() Stage {
"5. Repeat until the gate `%s` passes for all packages\n\n"+
"Gate output:\n%s\n\n"+
"When the gate passes, call finish with status \"passed\".",
strings.Join(argv, " "), tc.Repo.FullName(), strings.Join(argv, " "), clip(string(out), baselineMissionBytes),
strings.Join(argv, " "), tc.Repo.FullName(), strings.Join(argv, " "),
clip(extractFailingGateOutput(string(out)), baselineMissionBytes),
)
modelRef := tc.Cfg.Models["builder"]
@@ -89,6 +90,7 @@ func StageBaselineGate() Stage {
}
tc.Task.TokensUsed += res.TokensUsed
tc.Task.Iterations += res.Iterations
accumulateUsage(&tc.RunUsage, res.Usage)
if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, "baseline-fix", res.Summary, agentFinishData(res, modelRef)); emitErr != nil {
return fmt.Errorf("persist baseline-fix agent finish: %w", emitErr)
}
@@ -188,10 +190,17 @@ func Implement() Workflow {
StageYaegiGate(),
StageDiffCap(),
StageReview(),
StageOpenPR(func(tc *TaskContext) string {
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %d tokens*",
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
}),
StageOpenPR(implementPRBody),
},
}
}
// implementPRBody is the PR summary footer for the implement workflow. It
// reports the fresh-vs-cached breakdown of tc.Task.TokensUsed (see
// formatTokenUsage) so the operator isn't misled by the raw prompt-token sum
// -- most of it is typically prefix-cache hits billed at a steep discount,
// not full price.
func implementPRBody(tc *TaskContext) string {
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %s*",
tc.BuildSummary, tc.Task.Iterations, formatTokenUsage(tc.Task.TokensUsed, tc.RunUsage))
}
+121
View File
@@ -46,6 +46,127 @@ func TestStageBaselineGateAccountsForRepairAgentUsage(t *testing.T) {
if task.TokensUsed != 120 || task.Iterations != 3 {
t.Fatalf("baseline usage = %d tokens/%d iterations, want 120/3", task.TokensUsed, task.Iterations)
}
if tc.RunUsage.PromptTokens != 100 || tc.RunUsage.CompletionTokens != 20 || tc.RunUsage.CachedTokens != 80 {
t.Fatalf("RunUsage = %+v, want prompt=100 completion=20 cached=80", tc.RunUsage)
}
}
// TestImplementPRBodyShowsFreshVsCachedTokens pins problem 1: a PR body
// built from a heavily-cached run must surface how much of the reported
// prompt-token sum was a cache hit, not read as the full-price total.
func TestImplementPRBodyShowsFreshVsCachedTokens(t *testing.T) {
tc := &TaskContext{
Task: &store.Task{Iterations: 14, TokensUsed: 405004},
BuildSummary: "did the thing",
RunUsage: agentexec.Usage{
PromptTokens: 400021, CompletionTokens: 4983, CachedTokens: 360018,
},
}
body := implementPRBody(tc)
if !strings.Contains(body, "405004 tokens") {
t.Fatalf("PR body missing the raw total: %s", body)
}
if !strings.Contains(body, "cached") {
t.Fatalf("PR body does not disclose cache hits: %s", body)
}
// fresh = prompt - cached + completion = 400021 - 360018 + 4983 = 44986
if !strings.Contains(body, "44986 fresh") {
t.Fatalf("PR body missing the fresh/net figure: %s", body)
}
}
// TestImplementPRBodyFallsBackWithoutUsageBreakdown guards the degrade
// path: a run with no populated Usage (e.g. no agent stage ran) must still
// produce a sane PR body rather than a "0 fresh + 0 cached" line implying
// billed usage was known and zero.
func TestImplementPRBodyFallsBackWithoutUsageBreakdown(t *testing.T) {
tc := &TaskContext{
Task: &store.Task{Iterations: 1, TokensUsed: 500},
BuildSummary: "did the thing",
}
body := implementPRBody(tc)
if !strings.Contains(body, "500 tokens") {
t.Fatalf("PR body missing the total: %s", body)
}
if strings.Contains(body, "fresh") || strings.Contains(body, "cached") {
t.Fatalf("PR body fabricated a breakdown with no usage data: %s", body)
}
}
// TestExtractFailingGateOutputDropsPassingPackages pins problem 2: the
// baseline-fix mission must not re-inject "ok" lines for packages that
// already pass -- those dominate a large repo's `go test ./...` output and
// squeeze the actual failure detail out of clip's size bound on later
// retries.
func TestExtractFailingGateOutputDropsPassingPackages(t *testing.T) {
out := "ok \tgithub.com/example/pkg/a\t0.004s\n" +
"ok \tgithub.com/example/pkg/b\t0.012s\n" +
"--- FAIL: TestSomething (0.00s)\n" +
" something_test.go:12: expected 1, got 2\n" +
"FAIL\tgithub.com/example/pkg/c\t0.010s\n" +
"ok \tgithub.com/example/pkg/d\t0.002s\n"
got := extractFailingGateOutput(out)
if strings.Contains(got, "pkg/a") || strings.Contains(got, "pkg/b") || strings.Contains(got, "pkg/d") {
t.Fatalf("passing-package lines survived extraction: %s", got)
}
if !strings.Contains(got, "--- FAIL: TestSomething") || !strings.Contains(got, "pkg/c") {
t.Fatalf("failure detail was dropped: %s", got)
}
if len(got) >= len(out) {
t.Fatalf("extraction did not reduce output size: got %d bytes, want < %d", len(got), len(out))
}
}
// TestExtractFailingGateOutputDegradesGracefullyForUnrecognizedFormat
// guards against silently dropping real failure information for a gate
// command whose output isn't shaped like `go test` output (a non-Go gate,
// or an unexpected format) -- the full output must be preserved.
func TestExtractFailingGateOutputDegradesGracefullyForUnrecognizedFormat(t *testing.T) {
out := "lint: 3 problems found\nfile.go:10: unused variable\nfile.go:22: missing return\n"
if got := extractFailingGateOutput(out); got != out {
t.Fatalf("extraction altered unrecognized output:\ngot: %q\nwant: %q", got, out)
}
}
// TestStageBaselineGateMissionOmitsPassingPackageOutput is the integration
// pin: a real StageBaselineGate run with go-test-shaped failure output must
// build a mission that omits the passing-package noise.
func TestStageBaselineGateMissionOmitsPassingPackageOutput(t *testing.T) {
dir := t.TempDir()
script := filepath.Join(dir, "gate.sh")
body := "#!/bin/sh\n" +
"echo 'ok \tgithub.com/example/pkg/quietpassingpkg\t0.004s'\n" +
"echo '--- FAIL: TestBroken (0.00s)'\n" +
"echo ' broken_test.go:5: boom'\n" +
"echo 'FAIL\tgithub.com/example/pkg/broken\t0.010s'\n" +
"exit 1\n"
if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
t.Fatal(err)
}
var gotMission string
runner := agentRunnerFunc(func(_ context.Context, _ string, req agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) {
gotMission = req.Mission
return agentexec.Result{Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed}, nil
})
tc := &TaskContext{
Task: &store.Task{ID: 1, Owner: "o", Repo: "r"},
Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}},
Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}},
Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"},
Dir: dir, Log: slog.New(slog.DiscardHandler),
}
if err := StageBaselineGate().Run(t.Context(), tc); err != nil {
t.Fatal(err)
}
if strings.Contains(gotMission, "quietpassingpkg") {
t.Fatalf("mission still contains a passing package's output: %s", gotMission)
}
if !strings.Contains(gotMission, "TestBroken") || !strings.Contains(gotMission, "pkg/broken") {
t.Fatalf("mission lost the actual failure detail: %s", gotMission)
}
}
// TestStageBaselineGateSetsBaselineFixedWhenItCommits is the companion
+2 -2
View File
@@ -149,8 +149,8 @@ func tddFixStage() Stage {
// as evidence the bug was reproduced before the fix.
func tddOpenPRStage() Stage {
return Stage{Name: "open-pr", Run: func(ctx context.Context, tc *TaskContext) error {
body := fmt.Sprintf("%s\n\n---\n*workflow: tdd (failing repro committed first) · %d iterations · %d tokens*",
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
body := fmt.Sprintf("%s\n\n---\n*workflow: tdd (failing repro committed first) · %d iterations · %s*",
tc.BuildSummary, tc.Task.Iterations, formatTokenUsage(tc.Task.TokensUsed, tc.RunUsage))
return OpenPR(ctx, tc, body)
}}
}
+64
View File
@@ -10,7 +10,9 @@ import (
"errors"
"fmt"
"log/slog"
"regexp"
"sort"
"strings"
"time"
"unicode/utf8"
@@ -117,6 +119,14 @@ type TaskContext struct {
// agent stages record tool successes and failures for guardrail
// enforcement. Wired by the composition root from the daemon.
Guardrails *tools.GuardrailEngine
// RunUsage accumulates every agent run's token breakdown (prompt,
// completion, cached) for this workflow execution. It is presentation
// scratch, not persisted -- Task.TokensUsed remains the durable,
// authoritative total. It exists so PR bodies can show how much of the
// reported prompt-token sum was cache hits (billed at a steep discount)
// rather than fresh, full-price tokens; see formatTokenUsage.
RunUsage agentexec.Usage
}
// Emit publishes an observability event stamped with the task's
@@ -365,3 +375,57 @@ func clipTail(s string, n int) string {
}
return "…(truncated)\n" + s[cut:]
}
// formatTokenUsage renders a token total for a human, breaking out how much
// was a cache hit (billed at a steep discount) versus fresh, full-price
// tokens. Without this, a heavily-cached run's raw prompt-token sum reads as
// roughly 10x its actual bill.
//
// It falls back to the plain total when no usage breakdown is available
// (usage is the zero value -- e.g. a workflow that never ran an agent stage,
// or an older code path that hasn't been wired to populate RunUsage), so
// callers never need to special-case an empty Usage themselves.
func formatTokenUsage(total int, usage agentexec.Usage) string {
if usage.PromptTokens == 0 && usage.CompletionTokens == 0 && usage.CachedTokens == 0 {
return fmt.Sprintf("%d tokens", total)
}
fresh := max(usage.PromptTokens-usage.CachedTokens+usage.CompletionTokens, 0)
return fmt.Sprintf("%d tokens (%d fresh + %d cached)", total, fresh, usage.CachedTokens)
}
// extractFailingGateOutput trims a gate command's combined output down to
// the lines relevant to diagnosing a failure, dropping "ok" lines for
// packages that already pass. `go test ./...` output interleaves one
// "ok \t<pkg>\t<time>" line per passing package with the failing packages'
// "--- FAIL:"/"FAIL\t<pkg>" blocks; in a large repo the passing-package
// lines dominate the byte count and get squeezed out by clip's size bound,
// pushing the actual failure detail out of the mission prompt on later
// retries.
//
// It only trims when the output actually looks like recognized `go test`
// failure output (at least one "--- FAIL:" or "FAIL\t" marker survives the
// filter); otherwise it returns s unchanged, so a non-Go gate command or an
// unexpected output shape degrades to the previous full-output behaviour
// instead of silently dropping real failure information.
func extractFailingGateOutput(s string) string {
lines := strings.Split(s, "\n")
kept := make([]string, 0, len(lines))
sawFailureMarker := false
for _, line := range lines {
if goTestOKLine.MatchString(line) {
continue
}
kept = append(kept, line)
if strings.HasPrefix(line, "--- FAIL:") || strings.HasPrefix(line, "FAIL\t") || strings.HasPrefix(line, "FAIL ") {
sawFailureMarker = true
}
}
if !sawFailureMarker {
return s
}
return strings.Join(kept, "\n")
}
// goTestOKLine matches a `go test` passing-package summary line, e.g.
// "ok \tgithub.com/example/pkg\t0.004s".
var goTestOKLine = regexp.MustCompile(`^ok\s+\S+`)
+7 -2
View File
@@ -57,13 +57,18 @@ export function describeTimelineEvent(ev = {}) {
if (ev.kind === "agent_finish") {
const iterations = count(data.iterations);
const total = count(data.tokens);
const prompt = count(data.prompt_tokens);
const cachedRaw = Number(data.cached_tokens) || 0;
// data.prompt_tokens INCLUDES cache hits -- showing it next to "cached"
// reads as two separate charges when it's really one figure containing
// the other. Show the fresh (full-price) remainder instead, so a
// heavily-cached run doesn't look ~10x more expensive than it was billed.
const fresh = count((Number(data.prompt_tokens) || 0) - cachedRaw);
const completion = count(data.completion_tokens);
const cached = count(data.cached_tokens);
const usage = [
iterations && `${iterations} iterations`,
total && `${total} tokens`,
prompt && `${prompt} prompt`,
fresh && `${fresh} fresh prompt`,
completion && `${completion} completion`,
cached && `${cached} cached`,
data.model,
+5 -2
View File
@@ -28,7 +28,10 @@ test("retry events explain which failure caused the retry", () => {
);
});
test("agent events expose stage efficiency and cache usage", () => {
test("agent events expose stage efficiency and cache usage as fresh vs cached", () => {
// prompt_tokens (280,000) INCLUDES the 240,000 cache hits -- showing it
// next to "cached" reads as two separate charges when only 40,000 of it
// was billed at full price. The fresh figure is the disclosed remainder.
assert.deepEqual(
describeTimelineEvent({
kind: "agent_finish",
@@ -46,7 +49,7 @@ test("agent events expose stage efficiency and cache usage", () => {
{
title: "Agent passed: analyse",
detail:
"7 iterations · 282,066 tokens · 280,000 prompt · 2,066 completion · 240,000 cached · openai/gpt-5.6-luna",
"7 iterations · 282,066 tokens · 40,000 fresh prompt · 2,066 completion · 240,000 cached · openai/gpt-5.6-luna",
},
);
});