Public: anyone can read this; the crew can change it.

Traces 1: one normalized trace for every Talk conversation and crew run, read from the raw record #17999

opened this in answer to

Parked 11h 5m ago

scout/forge:scout/17991-traces-1-one-normalized-trace-for-every → main 11 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
34 files changed +1163 −152
docs/features/trace-index.md added +28
@@ -0,0 +1,28 @@
1 ---
2 topic: Your apps
3 row: Trace list and tree: every Talk conversation and crew run over the API and in the terminal
4 ---
5 # Trace list and tree: every Talk conversation and crew run (#17991)
6
7 A trace is a thread of turns, each turn a list of steps (a model call, a tool call, a subagent), with
8 start and end, model, account, tokens in, cached and out, cost and outcome. It is **rebuilt from the raw
9 record on every read** (a Talk conversation's turns and logs, a crew run's row, usage-ledger line and
10 log); nothing keeps a second copy of the content. Nothing here deletes anything.
11
12 - **List.** `GET /api/v1/traces`, newest first, `?limit=` up to 100 and `?cursor=` (the previous
13 `next_cursor`); filters `?repository=owner/name`, `?kind=talk|run`, `?model=`,
14 `?outcome=ok|error|stopped|unknown`, `?from=` and `?to=` as `YYYY-MM-DD` (UTC). Any token scope.
15 - **Tree.** `GET /api/v1/traces/:id` (`run-<id>` or `talk-<id>`): the thread, its turns and their steps,
16 with totals.
17 - **Terminal.** The Traces command in the palette (`src/tui/screens/traces.ts`) lists the same rows;
18 Enter opens one as a tree. Both read `src/actions/traces.ts`.
19 - **Who sees what.** A Talk conversation is its person's alone. A crew run's trace is read by whoever may
20 read its log; its cost only by whoever sees the owner's facts, as on the run page.
21 - **The index.** `trace_index` holds one summary row per trace so the list never opens a log. A sweep
22 (`src/trace/sweep.ts`, started at boot) walks runs and Talk turns by id, 20 at a time, giving the loop
23 back between slices: the first pass backfills what exists, later passes pick up what finished. A row
24 follows within about a minute of a run or turn finishing.
25
26 What the log does not carry: a run's log has no clock per line and no tokens per call, so a run is one
27 model step with its recorded totals and its tool calls take the run's own span; cached tokens read 0
28 where the ledger does not say. Reviews are not traced yet.
docs/features/traces.md +2
@@ -19,3 +19,5 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu
1919 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: storing an import, tokens and cost per step (the file holds none), compare, share.
2020
2121 The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step.
22
23 Talk conversations and crew runs are traces too: see `docs/features/trace-index.md`.
src/actions/traces.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * Traces for every door (#17991): the list `GET /api/v1/traces` answers and the tree behind
3 * `GET /api/v1/traces/:id`, the same rows for the terminal (`tui/screens/traces.ts`). A Talk
4 * conversation is its person's alone; a crew run's trace is read by whoever may read its log
5 * (`mayReadRunLog`), and its cost only by whoever sees the owner's facts, as a run's own page.
6 */
7 import type { App } from "../app.ts";
8 import { canSeeOwnerFacts, getRepoById, type Repo } from "../core/repos.ts";
9 import type { User } from "../core/users.ts";
10 import { buildRunTrace, buildTalkTrace } from "../trace/build.ts";
11 import { totalsOf, type Trace } from "../trace/model.ts";
12 import { getTraceRow, listTraces, type TraceFilter, type TraceRow } from "../trace/store.ts";
13 import { mayReadRunLog, runForReader } from "./runs.ts";
14 import { getRun } from "../core/runs.ts";
15
16 export interface TraceSummary {
17 readonly id: string;
18 readonly kind: "talk" | "run";
19 readonly repository: string | null;
20 readonly title: string;
21 readonly model: string | null;
22 readonly account: string | null;
23 readonly steps: number;
24 readonly tokens_in: number;
25 readonly tokens_cached: number;
26 readonly tokens_out: number;
27 readonly cost_usd: number;
28 readonly outcome: string;
29 readonly started_at: string;
30 readonly ended_at: string;
31 }
32
33 const iso = (ms: number): string => new Date(ms).toISOString();
34 const orNull = (s: string): string | null => (s === "" ? null : s);
35
36 /** Whether this person may read a trace row, and whether its cost is theirs to see. */
37 function gateFor(app: App, user: User): (row: TraceRow) => { read: boolean; cost: boolean } {
38 const repos = new Map<string, { repo: Repo | undefined; read: boolean; cost: boolean }>();
39 return (row) => {
40 if (row.kind === "talk") return { read: row.user_id === user.id, cost: true };
41 let known = repos.get(row.repo_id);
42 if (known === undefined) {
43 const repo = getRepoById(app.db, row.repo_id);
44 known = { repo, read: repo !== undefined && mayReadRunLog(app, user, repo), cost: repo !== undefined && canSeeOwnerFacts(app.db, repo, user) };
45 repos.set(row.repo_id, known);
46 }
47 return known;
48 };
49 }
50
51 function summaryOf(row: TraceRow, cost: boolean): TraceSummary {
52 return {
53 id: row.id,
54 kind: row.kind,
55 repository: orNull(row.repository),
56 title: row.title,
57 model: orNull(row.model),
58 account: orNull(row.account),
59 steps: row.steps,
60 tokens_in: row.tokens_in,
61 tokens_cached: row.tokens_cached,
62 tokens_out: row.tokens_out,
63 cost_usd: cost ? row.cost_usd : 0,
64 outcome: row.outcome,
65 started_at: iso(row.started),
66 ended_at: iso(row.ended),
67 };
68 }
69
70 /** A page of the person's traces, newest first. */
71 export function traceList(app: App, user: User, filter: TraceFilter, limit: number, cursor: string | null): { items: TraceSummary[]; next_cursor: string | null } {
72 const gate = gateFor(app, user);
73 const page = listTraces(app.db, filter, (row) => gate(row).read, limit, cursor);
74 return { items: page.rows.map((row) => summaryOf(row, gate(row).cost)), next_cursor: page.next };
75 }
76
77 export interface TraceTree {
78 readonly id: string;
79 readonly kind: "talk" | "run";
80 readonly repository: string | null;
81 readonly title: string;
82 readonly model: string | null;
83 readonly account: string | null;
84 readonly outcome: string;
85 readonly totals: { steps: number; tokens_in: number; tokens_cached: number; tokens_out: number; cost_usd: number; errors: number; started_at: string; ended_at: string };
86 readonly turns: readonly {
87 index: number;
88 prompt: string;
89 started_at: string;
90 steps: readonly { id: string; kind: string; name: string; line: string; started_at: string; ended_at: string; model: string | null; account: string | null; tokens_in: number; tokens_cached: number; tokens_out: number; cost_usd: number; outcome: string }[];
91 }[];
92 }
93
94 export function treeOf(trace: Trace, cost: boolean): TraceTree {
95 const t = totalsOf(trace);
96 return {
97 id: trace.id,
98 kind: trace.source === "talk" ? "talk" : "run",
99 repository: trace.repository ?? null,
100 title: trace.title,
101 model: trace.model ?? null,
102 account: trace.account ?? null,
103 outcome: trace.outcome,
104 totals: { steps: t.steps, tokens_in: t.tokensIn, tokens_cached: t.tokensCached, tokens_out: t.tokensOut, cost_usd: cost ? t.costUsd : 0, errors: t.errors, started_at: iso(t.startMs), ended_at: iso(t.endMs) },
105 turns: trace.turns.map((turn) => ({
106 index: turn.index,
107 prompt: turn.prompt,
108 started_at: iso(turn.startMs),
109 steps: turn.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, started_at: iso(s.startMs), ended_at: iso(s.endMs), model: s.model ?? null, account: s.account ?? null, tokens_in: s.tokensIn, tokens_cached: s.tokensCached, tokens_out: s.tokensOut, cost_usd: cost ? s.costUsd : 0, outcome: s.outcome })),
110 })),
111 };
112 }
113
114 /**
115 * The tree of one trace, rebuilt from the raw record; undefined when there is none the person may
116 * read.
117 */
118 export async function traceTree(app: App, user: User, id: string): Promise<TraceTree | undefined> {
119 const row = getTraceRow(app.db, id);
120 if (row === undefined) return undefined;
121 const gate = gateFor(app, user)(row);
122 if (!gate.read) return undefined;
123 const dataDir = app.config.dataDir;
124 if (row.kind === "talk") {
125 const trace = await buildTalkTrace(app.db, dataDir, id.slice("talk-".length));
126 return trace === undefined ? undefined : treeOf(trace, true);
127 }
128 const run = getRun(app.db, id.slice("run-".length));
129 const repo = run === undefined ? undefined : getRepoById(app.db, run.repoId);
130 if (run === undefined || repo === undefined) return undefined;
131 const trace = await buildRunTrace(app.db, dataDir, runForReader(app, user, repo)(run));
132 return trace === undefined ? undefined : treeOf(trace, gate.cost);
133 }
src/contract/openapi/routes/getApiV1Traces.ts added +17
@@ -0,0 +1,17 @@
1 import { limitTo, type Route } from "../shared.ts";
2
3 const ITEM = ["id", "kind", "repository", "title", "model", "account", "steps", "tokens_in", "tokens_cached", "tokens_out", "cost_usd", "outcome", "started_at", "ended_at"] as const;
4
5 export const route: Route = {
6 method: "get",
7 path: "/api/v1/traces",
8 summary: "Your Talk conversations and the crew runs you may read, as normalized traces",
9 detail:
10 "One summary per Talk conversation (yours alone) and per crew run whose log you may read, newest first (?limit= up to 100, ?cursor= the previous next_cursor; filters ?repository=owner/name, ?kind=talk|run, ?model=, ?outcome=ok|error|stopped|unknown, ?from= and ?to= as YYYY-MM-DD, UTC); answers { items: [{ id, kind, repository, title, model, account, steps, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started_at, ended_at }], next_cursor }. Cost is the owner's own fact: 0 where you may not see it. Tokens cached are 0 where the record does not say.",
11 auth: true,
12 role: "member",
13 query: { limit: limitTo(100), cursor: "string", repository: "string", kind: "string", model: "string", outcome: "string", from: "string", to: "string" },
14 itemKeys: ITEM,
15 refuses: [401],
16 refusals: { invalid_query: "a filter is malformed", invalid_limit: "limit is a whole number from 1 to 100", invalid_cursor: "cursor is not a next_cursor of this list" },
17 };
src/contract/openapi/routes/getApiV1TracesId.ts added +12
@@ -0,0 +1,12 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/traces/{id}",
6 summary: "One trace as a tree: thread, turns, steps",
7 detail:
8 "A trace rebuilt from the raw record (a Talk conversation, or a crew run's row, ledger line and log): answers { id, kind, repository, title, model, account, outcome, totals: { steps, tokens_in, tokens_cached, tokens_out, cost_usd, errors, started_at, ended_at }, turns: [{ index, prompt, started_at, steps: [{ id, kind: model|tool|subagent, name, line, started_at, ended_at, model, account, tokens_in, tokens_cached, tokens_out, cost_usd, outcome }] }] }. A run's log carries no clock per line or tokens per call, so its tool steps take the run's own span and the model step its recorded totals.",
9 auth: true,
10 role: "member",
11 refuses: [401, 404],
12 };
src/contract/openapi/routes/index.ts +2
@@ -262,6 +262,8 @@ export { route as getApiV1TelemetrySources } from "./getApiV1TelemetrySources.ts
262262 export { route as getApiV1TelemetrySystem } from "./getApiV1TelemetrySystem.ts";
263263 export { route as getApiV1Templates } from "./getApiV1Templates.ts";
264264 export { route as getApiV1Tokens } from "./getApiV1Tokens.ts";
265 export { route as getApiV1Traces } from "./getApiV1Traces.ts";
266 export { route as getApiV1TracesId } from "./getApiV1TracesId.ts";
265267 export { route as getApiV1Usage } from "./getApiV1Usage.ts";
266268 export { route as getApiV1User } from "./getApiV1User.ts";
267269 export { route as getApiV1UserAssigned } from "./getApiV1UserAssigned.ts";
src/contract/tags.ts +1
@@ -119,6 +119,7 @@ const ALIAS: Readonly<Record<string, string>> = {
119119 envelope: "apps",
120120 otlp: "apps",
121121 dependencies: "repos",
122 traces: "runs",
122123 };
123124
124125 /** One line on each tag the document lists. */
src/core/account_purge.ts +3
@@ -68,6 +68,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
6868 "degraded_span.touched_by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
6969 "dep_accept.by_name": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
7070 "repo_review.by": FORMER,
71 // A summary row of a trace: the record it points at is the history; the row names the placeholder
72 // once the account is gone.
73 "trace_index.user_id": FORMER,
7174 "review_request.requested_by": FORMER,
7275 "review_request.reviewer_id": FORMER,
7376 "account_notice.user_id": DELETE,
src/core/migration-pins/20261204020000-trace-index.pin added +1
@@ -0,0 +1,1 @@
1 f0b4bc87dee9b0920da3244e14dd478c4a90eac4f3d303b29d7b46fb4736d5cf
src/core/migrations/20261204020000-trace-index.ts added +32
@@ -0,0 +1,32 @@
1 // The list of traces (#17991): one summary row per Talk conversation and per crew run, so
2 // `GET /api/v1/traces` never opens a log. It holds no content (the raw record stays the record;
3 // the tree is rebuilt from it on read) and is rebuilt from it by `src/trace/sweep.ts`, which keeps
4 // its place in `trace_mark`. The list walks `trace_index_started` (newest first, keyset) or
5 // `trace_index_kind`. Additive: new tables.
6 export default `
7 CREATE TABLE IF NOT EXISTS trace_index (
8 id TEXT PRIMARY KEY,
9 kind TEXT NOT NULL CHECK (kind IN ('talk','run')),
10 repo_id TEXT NOT NULL DEFAULT '',
11 user_id TEXT NOT NULL DEFAULT '',
12 repository TEXT NOT NULL DEFAULT '',
13 title TEXT NOT NULL DEFAULT '',
14 model TEXT NOT NULL DEFAULT '',
15 account TEXT NOT NULL DEFAULT '',
16 steps INTEGER NOT NULL DEFAULT 0,
17 tokens_in INTEGER NOT NULL DEFAULT 0,
18 tokens_cached INTEGER NOT NULL DEFAULT 0,
19 tokens_out INTEGER NOT NULL DEFAULT 0,
20 cost_usd REAL NOT NULL DEFAULT 0,
21 outcome TEXT NOT NULL DEFAULT 'unknown',
22 started INTEGER NOT NULL DEFAULT 0,
23 ended INTEGER NOT NULL DEFAULT 0,
24 stamp TEXT NOT NULL DEFAULT ''
25 );
26 CREATE INDEX IF NOT EXISTS trace_index_started ON trace_index (started DESC, id DESC);
27 CREATE INDEX IF NOT EXISTS trace_index_kind ON trace_index (kind, started DESC, id DESC);
28 CREATE TABLE IF NOT EXISTS trace_mark (
29 source TEXT PRIMARY KEY,
30 after TEXT NOT NULL DEFAULT ''
31 );
32 `;
src/generated/marks.ts +136 −134
@@ -78,140 +78,141 @@ import k73 from "../http/marks/api-v1-templates.json";
7878 import k74 from "../http/marks/api-v1-thoughts.json";
7979 import k75 from "../http/marks/api-v1-timers.json";
8080 import k76 from "../http/marks/api-v1-tokens.json";
81 import k77 from "../http/marks/api-v1-usage.json";
82 import k78 from "../http/marks/api-v1-user.json";
83 import k79 from "../http/marks/api-v1-users.json";
84 import k80 from "../http/marks/api-v1-version.json";
85 import k81 from "../http/marks/api-v1.json";
86 import k82 from "../http/marks/api.json";
87 import k83 from "../http/marks/apple-touch-icon-precomposed.png.json";
88 import k84 from "../http/marks/apple-touch-icon.png.json";
89 import k85 from "../http/marks/apps.json";
90 import k86 from "../http/marks/archive.json";
91 import k87 from "../http/marks/asked.json";
92 import k88 from "../http/marks/asks.json";
93 import k89 from "../http/marks/assets.json";
94 import k90 from "../http/marks/audit.csv.json";
95 import k91 from "../http/marks/audit.json";
96 import k92 from "../http/marks/big.json";
97 import k93 from "../http/marks/board.json";
98 import k94 from "../http/marks/boards.json";
99 import k95 from "../http/marks/bring.json";
100 import k96 from "../http/marks/broker.json";
101 import k97 from "../http/marks/changelog.atom.json";
102 import k98 from "../http/marks/changelog.json";
103 import k99 from "../http/marks/claim.json";
104 import k100 from "../http/marks/client-clouds.json";
105 import k101 from "../http/marks/cloud.json";
106 import k102 from "../http/marks/cockpit.json";
107 import k103 from "../http/marks/contract.json";
108 import k104 from "../http/marks/contribute.json";
109 import k105 from "../http/marks/csp-report.json";
110 import k106 from "../http/marks/dash.json";
111 import k107 from "../http/marks/data.json";
112 import k108 from "../http/marks/dataset.json";
113 import k109 from "../http/marks/deploy-to.json";
114 import k110 from "../http/marks/design.json";
115 import k111 from "../http/marks/desk.json";
116 import k112 from "../http/marks/displays.json";
117 import k113 from "../http/marks/docs.json";
118 import k114 from "../http/marks/edge.json";
119 import k115 from "../http/marks/edition.json";
120 import k116 from "../http/marks/events.json";
121 import k117 from "../http/marks/explore.atom.json";
122 import k118 from "../http/marks/explore.json";
123 import k119 from "../http/marks/explore.json.json";
124 import k120 from "../http/marks/family.json";
125 import k121 from "../http/marks/favicon.ico.json";
126 import k122 from "../http/marks/feed.json";
127 import k123 from "../http/marks/feed.json.json";
128 import k124 from "../http/marks/first-admin.json";
129 import k125 from "../http/marks/fleet.json";
130 import k126 from "../http/marks/flow.json";
131 import k127 from "../http/marks/forge.json";
132 import k128 from "../http/marks/forges.json";
133 import k129 from "../http/marks/forks.json";
134 import k130 from "../http/marks/front.json";
135 import k131 from "../http/marks/funnel.json";
136 import k132 from "../http/marks/games.json";
137 import k133 from "../http/marks/go.json";
138 import k134 from "../http/marks/health.json";
139 import k135 from "../http/marks/home.json";
140 import k136 from "../http/marks/hooks.json";
141 import k137 from "../http/marks/icons.json";
142 import k138 from "../http/marks/infra.json";
143 import k139 from "../http/marks/join.json";
144 import k140 from "../http/marks/live.json";
145 import k141 from "../http/marks/llms-full.txt.json";
146 import k142 from "../http/marks/llms.txt.json";
147 import k143 from "../http/marks/login.json";
148 import k144 from "../http/marks/logout.json";
149 import k145 from "../http/marks/maintenance-json.json";
150 import k146 from "../http/marks/maintenance.json";
151 import k147 from "../http/marks/manifest.webmanifest.json";
152 import k148 from "../http/marks/map.json";
153 import k149 from "../http/marks/mcp.json";
154 import k150 from "../http/marks/measure.json";
155 import k151 from "../http/marks/metrics.json";
156 import k152 from "../http/marks/migrate.json";
157 import k153 from "../http/marks/new.json";
158 import k154 from "../http/marks/next.json";
159 import k155 from "../http/marks/notes.json";
160 import k156 from "../http/marks/now.json";
161 import k157 from "../http/marks/oauth.json";
162 import k158 from "../http/marks/oembed.json";
163 import k159 from "../http/marks/offers.json";
164 import k160 from "../http/marks/offline.json";
165 import k161 from "../http/marks/og.json";
166 import k162 from "../http/marks/openapi.json.json";
167 import k163 from "../http/marks/opensearch.xml.json";
168 import k164 from "../http/marks/organizations.json";
169 import k165 from "../http/marks/origins.json";
170 import k166 from "../http/marks/owner.atom.json";
171 import k167 from "../http/marks/owner.json";
172 import k168 from "../http/marks/packs.json";
173 import k169 from "../http/marks/peek.json";
174 import k170 from "../http/marks/pinned.json";
175 import k171 from "../http/marks/pipeline.json";
176 import k172 from "../http/marks/plugins.json";
177 import k173 from "../http/marks/pricing.json";
178 import k174 from "../http/marks/privacy.json";
179 import k175 from "../http/marks/r.json";
180 import k176 from "../http/marks/recover.json";
181 import k177 from "../http/marks/releases.json";
182 import k178 from "../http/marks/releases.json.json";
183 import k179 from "../http/marks/repos.json";
184 import k180 from "../http/marks/resilience.json";
185 import k181 from "../http/marks/review.json";
186 import k182 from "../http/marks/robots.txt.json";
187 import k183 from "../http/marks/root.json";
188 import k184 from "../http/marks/runs.json";
189 import k185 from "../http/marks/script-error.json";
190 import k186 from "../http/marks/search.json";
191 import k187 from "../http/marks/security.json";
192 import k188 from "../http/marks/settings.json";
193 import k189 from "../http/marks/sign-in.json";
194 import k190 from "../http/marks/signin.json";
195 import k191 from "../http/marks/signup.json";
196 import k192 from "../http/marks/sitemap.xml.json";
197 import k193 from "../http/marks/status.json";
198 import k194 from "../http/marks/support.json";
199 import k195 from "../http/marks/sw.js.json";
200 import k196 from "../http/marks/system.json";
201 import k197 from "../http/marks/tab.json";
202 import k198 from "../http/marks/tabforge.json";
203 import k199 from "../http/marks/talk.json";
204 import k200 from "../http/marks/tell.json";
205 import k201 from "../http/marks/templates.json";
206 import k202 from "../http/marks/templates.json.json";
207 import k203 from "../http/marks/terms.json";
208 import k204 from "../http/marks/theme.json";
209 import k205 from "../http/marks/toolbar-lab.js.json";
210 import k206 from "../http/marks/toolbar-lab.json";
211 import k207 from "../http/marks/traces.json";
212 import k208 from "../http/marks/verify.json";
213 import k209 from "../http/marks/welcome.json";
214 import k210 from "../http/marks/well-known.json";
81 import k77 from "../http/marks/api-v1-traces.json";
82 import k78 from "../http/marks/api-v1-usage.json";
83 import k79 from "../http/marks/api-v1-user.json";
84 import k80 from "../http/marks/api-v1-users.json";
85 import k81 from "../http/marks/api-v1-version.json";
86 import k82 from "../http/marks/api-v1.json";
87 import k83 from "../http/marks/api.json";
88 import k84 from "../http/marks/apple-touch-icon-precomposed.png.json";
89 import k85 from "../http/marks/apple-touch-icon.png.json";
90 import k86 from "../http/marks/apps.json";
91 import k87 from "../http/marks/archive.json";
92 import k88 from "../http/marks/asked.json";
93 import k89 from "../http/marks/asks.json";
94 import k90 from "../http/marks/assets.json";
95 import k91 from "../http/marks/audit.csv.json";
96 import k92 from "../http/marks/audit.json";
97 import k93 from "../http/marks/big.json";
98 import k94 from "../http/marks/board.json";
99 import k95 from "../http/marks/boards.json";
100 import k96 from "../http/marks/bring.json";
101 import k97 from "../http/marks/broker.json";
102 import k98 from "../http/marks/changelog.atom.json";
103 import k99 from "../http/marks/changelog.json";
104 import k100 from "../http/marks/claim.json";
105 import k101 from "../http/marks/client-clouds.json";
106 import k102 from "../http/marks/cloud.json";
107 import k103 from "../http/marks/cockpit.json";
108 import k104 from "../http/marks/contract.json";
109 import k105 from "../http/marks/contribute.json";
110 import k106 from "../http/marks/csp-report.json";
111 import k107 from "../http/marks/dash.json";
112 import k108 from "../http/marks/data.json";
113 import k109 from "../http/marks/dataset.json";
114 import k110 from "../http/marks/deploy-to.json";
115 import k111 from "../http/marks/design.json";
116 import k112 from "../http/marks/desk.json";
117 import k113 from "../http/marks/displays.json";
118 import k114 from "../http/marks/docs.json";
119 import k115 from "../http/marks/edge.json";
120 import k116 from "../http/marks/edition.json";
121 import k117 from "../http/marks/events.json";
122 import k118 from "../http/marks/explore.atom.json";
123 import k119 from "../http/marks/explore.json";
124 import k120 from "../http/marks/explore.json.json";
125 import k121 from "../http/marks/family.json";
126 import k122 from "../http/marks/favicon.ico.json";
127 import k123 from "../http/marks/feed.json";
128 import k124 from "../http/marks/feed.json.json";
129 import k125 from "../http/marks/first-admin.json";
130 import k126 from "../http/marks/fleet.json";
131 import k127 from "../http/marks/flow.json";
132 import k128 from "../http/marks/forge.json";
133 import k129 from "../http/marks/forges.json";
134 import k130 from "../http/marks/forks.json";
135 import k131 from "../http/marks/front.json";
136 import k132 from "../http/marks/funnel.json";
137 import k133 from "../http/marks/games.json";
138 import k134 from "../http/marks/go.json";
139 import k135 from "../http/marks/health.json";
140 import k136 from "../http/marks/home.json";
141 import k137 from "../http/marks/hooks.json";
142 import k138 from "../http/marks/icons.json";
143 import k139 from "../http/marks/infra.json";
144 import k140 from "../http/marks/join.json";
145 import k141 from "../http/marks/live.json";
146 import k142 from "../http/marks/llms-full.txt.json";
147 import k143 from "../http/marks/llms.txt.json";
148 import k144 from "../http/marks/login.json";
149 import k145 from "../http/marks/logout.json";
150 import k146 from "../http/marks/maintenance-json.json";
151 import k147 from "../http/marks/maintenance.json";
152 import k148 from "../http/marks/manifest.webmanifest.json";
153 import k149 from "../http/marks/map.json";
154 import k150 from "../http/marks/mcp.json";
155 import k151 from "../http/marks/measure.json";
156 import k152 from "../http/marks/metrics.json";
157 import k153 from "../http/marks/migrate.json";
158 import k154 from "../http/marks/new.json";
159 import k155 from "../http/marks/next.json";
160 import k156 from "../http/marks/notes.json";
161 import k157 from "../http/marks/now.json";
162 import k158 from "../http/marks/oauth.json";
163 import k159 from "../http/marks/oembed.json";
164 import k160 from "../http/marks/offers.json";
165 import k161 from "../http/marks/offline.json";
166 import k162 from "../http/marks/og.json";
167 import k163 from "../http/marks/openapi.json.json";
168 import k164 from "../http/marks/opensearch.xml.json";
169 import k165 from "../http/marks/organizations.json";
170 import k166 from "../http/marks/origins.json";
171 import k167 from "../http/marks/owner.atom.json";
172 import k168 from "../http/marks/owner.json";
173 import k169 from "../http/marks/packs.json";
174 import k170 from "../http/marks/peek.json";
175 import k171 from "../http/marks/pinned.json";
176 import k172 from "../http/marks/pipeline.json";
177 import k173 from "../http/marks/plugins.json";
178 import k174 from "../http/marks/pricing.json";
179 import k175 from "../http/marks/privacy.json";
180 import k176 from "../http/marks/r.json";
181 import k177 from "../http/marks/recover.json";
182 import k178 from "../http/marks/releases.json";
183 import k179 from "../http/marks/releases.json.json";
184 import k180 from "../http/marks/repos.json";
185 import k181 from "../http/marks/resilience.json";
186 import k182 from "../http/marks/review.json";
187 import k183 from "../http/marks/robots.txt.json";
188 import k184 from "../http/marks/root.json";
189 import k185 from "../http/marks/runs.json";
190 import k186 from "../http/marks/script-error.json";
191 import k187 from "../http/marks/search.json";
192 import k188 from "../http/marks/security.json";
193 import k189 from "../http/marks/settings.json";
194 import k190 from "../http/marks/sign-in.json";
195 import k191 from "../http/marks/signin.json";
196 import k192 from "../http/marks/signup.json";
197 import k193 from "../http/marks/sitemap.xml.json";
198 import k194 from "../http/marks/status.json";
199 import k195 from "../http/marks/support.json";
200 import k196 from "../http/marks/sw.js.json";
201 import k197 from "../http/marks/system.json";
202 import k198 from "../http/marks/tab.json";
203 import k199 from "../http/marks/tabforge.json";
204 import k200 from "../http/marks/talk.json";
205 import k201 from "../http/marks/tell.json";
206 import k202 from "../http/marks/templates.json";
207 import k203 from "../http/marks/templates.json.json";
208 import k204 from "../http/marks/terms.json";
209 import k205 from "../http/marks/theme.json";
210 import k206 from "../http/marks/toolbar-lab.js.json";
211 import k207 from "../http/marks/toolbar-lab.json";
212 import k208 from "../http/marks/traces.json";
213 import k209 from "../http/marks/verify.json";
214 import k210 from "../http/marks/welcome.json";
215 import k211 from "../http/marks/well-known.json";
215216
216217 /** Each file of `http/marks/`, parsed, in name order. */
217218 export const MARK_FILES: readonly unknown[] = [
@@ -426,4 +427,5 @@ export const MARK_FILES: readonly unknown[] = [
426427 k208,
427428 k209,
428429 k210,
430 k211,
429431 ];
src/generated/screens.ts +9 −7
@@ -127,13 +127,14 @@ import * as s122 from "../tui/screens/tab.ts";
127127 import * as s123 from "../tui/screens/teams.ts";
128128 import * as s124 from "../tui/screens/telemetry.ts";
129129 import * as s125 from "../tui/screens/tell_undo.ts";
130 import * as s126 from "../tui/screens/traffic.ts";
131 import * as s127 from "../tui/screens/trafficview.ts";
132 import * as s128 from "../tui/screens/valves.ts";
133 import * as s129 from "../tui/screens/waiting.ts";
134 import * as s130 from "../tui/screens/waiting_for_me.ts";
135 import * as s131 from "../tui/screens/wayback.ts";
136 import * as s132 from "../tui/screens/weekcard.ts";
130 import * as s126 from "../tui/screens/traces.ts";
131 import * as s127 from "../tui/screens/traffic.ts";
132 import * as s128 from "../tui/screens/trafficview.ts";
133 import * as s129 from "../tui/screens/valves.ts";
134 import * as s130 from "../tui/screens/waiting.ts";
135 import * as s131 from "../tui/screens/waiting_for_me.ts";
136 import * as s132 from "../tui/screens/wayback.ts";
137 import * as s133 from "../tui/screens/weekcard.ts";
137138
138139 /** Each screen file that declares palette entries: its module and the export names. */
139140 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -270,4 +271,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
270271 [s130, ["entry"]],
271272 [s131, ["entry"]],
272273 [s132, ["entry"]],
274 [s133, ["entry"]],
273275 ];
src/http/api.ts +2
@@ -350,6 +350,7 @@ import { accountAdmin, adminRoutes } from "./api/admin.ts";
350350 import { runnerRoutes } from "./api/runners.ts";
351351 import { maintenanceRoutes } from "./api/maintenance.ts";
352352 import { maintenanceRunsRoutes } from "./api/maintenance_runs.ts";
353 import { tracesRoutes } from "./api/traces.ts";
353354 import { diskReadingRoutes } from "./api/disk_readings.ts";
354355 import { TEMPLATE_ERRORS } from "../apps/template_tip.ts";
355356 import { flagsRoutes } from "./api/flags.ts";
@@ -1276,6 +1277,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12761277 gamesApiRoutes(router);
12771278 maintenanceRoutes(router);
12781279 maintenanceRunsRoutes(router);
1280 tracesRoutes(router);
12791281 diskReadingRoutes(router);
12801282 flagsRoutes(router);
12811283 appTemplateRoutes(router);
src/http/api/traces.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * `GET /api/v1/traces` and `GET /api/v1/traces/:id` (#17991): every Talk conversation and crew run
3 * as one normalized trace, thread → turns → steps. The list reads the small index
4 * (`trace/store.ts`); the tree is rebuilt from the raw record on each read, so nothing but the raw
5 * bytes holds the content. Who may read what is `actions/traces.ts`'s rule.
6 */
7 import { traceList, traceTree } from "../../actions/traces.ts";
8 import { cursorRefusal, limitRefusal, parseCursor, parseLimit } from "../../contract/page_query.ts";
9 import { CURSOR_SHAPE, type TraceFilter } from "../../trace/store.ts";
10 import type { Handler } from "../context.ts";
11 import { apiError, json, notFound, requireScope, unauthorized } from "../respond.ts";
12 import type { Router } from "../router.ts";
13
14 export const TRACES_MAX = 100;
15 const KINDS = ["talk", "run"] as const;
16 const OUTCOMES = ["ok", "error", "stopped", "unknown"] as const;
17 const REPOSITORY = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
18 const MODEL = /^[A-Za-z0-9_.:\/@-]{1,100}$/;
19 const DAY = /^\d{4}-\d{2}-\d{2}$/;
20 const ID = /^(?:run|talk)-[a-z0-9]{1,40}$/;
21
22 const refuse = (field: string, says: string): Response => apiError("invalid_query", 422, `${field}: ${says}`);
23
24 /**
25 * A `YYYY-MM-DD` as the start (or, with `end`, the last millisecond) of that UTC day; undefined
26 * when it is not a real date.
27 */
28 function dayMs(text: string, end: boolean): number | undefined {
29 if (!DAY.test(text)) return undefined;
30 const start = Date.parse(`${text}T00:00:00.000Z`);
31 if (!Number.isFinite(start) || new Date(start).toISOString().slice(0, 10) !== text) return undefined;
32 return end ? start + 86_400_000 - 1 : start;
33 }
34
35 export function tracesRoutes(router: Router<Handler>): void {
36 router.add("GET", "/api/v1/traces", (ctx) => {
37 if (!ctx.auth.user) return unauthorized();
38 const denied = requireScope(ctx, "ro");
39 if (denied) return denied;
40 const q = ctx.url.searchParams;
41 const limit = parseLimit(q.get("limit"), TRACES_MAX, 50);
42 if (limit === undefined) return limitRefusal(TRACES_MAX);
43 const cursor = parseCursor(q.get("cursor"), CURSOR_SHAPE);
44 if (cursor === undefined) return cursorRefusal();
45 const kind = q.get("kind");
46 if (kind !== null && !(KINDS as readonly string[]).includes(kind)) return refuse("kind", `one of ${KINDS.join(", ")}`);
47 const outcome = q.get("outcome");
48 if (outcome !== null && !(OUTCOMES as readonly string[]).includes(outcome)) return refuse("outcome", `one of ${OUTCOMES.join(", ")}`);
49 const repository = q.get("repository");
50 if (repository !== null && !REPOSITORY.test(repository)) return refuse("repository", "owner/name");
51 const model = q.get("model");
52 if (model !== null && !MODEL.test(model)) return refuse("model", "a model name");
53 const from = q.get("from");
54 const to = q.get("to");
55 const fromMs = from === null ? undefined : dayMs(from, false);
56 const toMs = to === null ? undefined : dayMs(to, true);
57 if (from !== null && fromMs === undefined) return refuse("from", "a date, YYYY-MM-DD");
58 if (to !== null && toMs === undefined) return refuse("to", "a date, YYYY-MM-DD");
59 const filter: TraceFilter = { kind: (kind ?? undefined) as TraceFilter["kind"], outcome: outcome ?? undefined, repository: repository ?? undefined, model: model ?? undefined, from: fromMs, to: toMs };
60 return json(traceList(ctx.app, ctx.auth.user, filter, limit, cursor));
61 });
62 router.add("GET", "/api/v1/traces/:id", async (ctx) => {
63 if (!ctx.auth.user) return unauthorized();
64 const denied = requireScope(ctx, "ro");
65 if (denied) return denied;
66 const id = ctx.params["id"] ?? "";
67 if (!ID.test(id)) return notFound();
68 const tree = await traceTree(ctx.app, ctx.auth.user, id);
69 return tree === undefined ? notFound() : json(tree);
70 });
71 }
src/http/lazy_lists.ts +2
@@ -1314,6 +1314,8 @@ export const API_ROUTES = [
13141314 ["GET", "/api/v1/maintenance/runs"],
13151315 ["GET", "/api/v1/maintenance/duties"],
13161316 ["POST", "/api/v1/maintenance/duties/:name"],
1317 ["GET", "/api/v1/traces"],
1318 ["GET", "/api/v1/traces/:id"],
13171319 ["GET", "/api/v1/admin/machines/:machine/disks"],
13181320 ["PUT", "/api/v1/admin/machines/:machine/disks/:device"],
13191321 ["GET", "/api/v1/flags"],
src/http/marks/api-v1-traces.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/traces",
3 "mark": "open"
4 }
src/main.ts +2
@@ -668,6 +668,8 @@ void backfillChildren(app)
668668 if (Object.keys(done).length > 0) app.log.info("forge-code backfill", { done: JSON.stringify(done) });
669669 })
670670 .catch((error) => app.log.error("could not backfill children's forge code", { error: String(error) }));
671 // The trace list follows the runs and Talk turns that are kept, a slice at a time (#17991).
672 void import("./trace/schedule.ts").then((m) => m.startTraceSweep(app.db, app.config.dataDir, app.log));
671673 // A forge still draining on this database keeps writing for its gates and
672674 // runs; starting ours beside it stalls the listener behind its write lock
673675 // (#6957). The listener answers meanwhile; a signal now stops what is up.
src/trace/build.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * A trace rebuilt from the raw record that is already kept (#17991): a crew run (its row, its usage
3 * ledger line and its log) or a Talk conversation (its turns' rows and each turn's log). Nothing is
4 * stored in place of them; the index (`index.ts`) holds a summary, never the content. The log
5 * carries no per-line clock or per-call tokens, so a run is one model step with its recorded
6 * totals, and its tool calls take the run's own span, in the order the agent made them.
7 */
8 import type { Database } from "bun:sqlite";
9 import { getRepoById } from "../core/repos.ts";
10 import { getIssueById } from "../core/issues.ts";
11 import type { Run } from "../core/runs.ts";
12 import { getUsage } from "../core/usage.ts";
13 import { PLATFORM } from "../core/subscriptions.ts";
14 import { readRunLog } from "../runs/log.ts";
15 import { restoreRunLog } from "../runs/archive.ts";
16 import { oneLine } from "./claude_code.ts";
17 import { readLog } from "./from_log.ts";
18 import type { Outcome, Step, Trace, Turn } from "./model.ts";
19
20 export const runTraceId = (runId: string): string => `run-${runId}`;
21 export const talkTraceId = (conversationId: string): string => `talk-${conversationId}`;
22
23 const SUBAGENT = new Set(["Task", "Agent"]);
24 const ms = (iso: string | null | undefined): number => {
25 const t = Date.parse(iso ?? "");
26 return Number.isFinite(t) ? t : 0;
27 };
28
29 /** A log's lines, brought back from the archive when the local file is gone (#4545). */
30 async function linesOf(db: Database, dataDir: string, runId: string): Promise<string[]> {
31 let read = readRunLog(dataDir, runId).lines;
32 if (read.length === 0 && (await restoreRunLog(db, dataDir, runId))) read = readRunLog(dataDir, runId).lines;
33 return read;
34 }
35
36 function outcomeOf(state: string): Outcome {
37 if (state === "ok") return "ok";
38 if (state === "failed") return "error";
39 if (state === "cancelled" || state === "stopped") return "stopped";
40 return "unknown";
41 }
42
43 interface Call {
44 readonly id: string;
45 readonly prompt: string;
46 readonly startMs: number;
47 readonly endMs: number;
48 readonly state: string;
49 readonly model: string;
50 readonly account: string | undefined;
51 readonly tokensIn: number;
52 readonly tokensOut: number;
53 readonly costUsd: number;
54 readonly lines: readonly string[];
55 }
56
57 /** One turn: its model step with the recorded totals, then each tool the log names. */
58 function turnOf(index: number, call: Call): Turn {
59 const read = readLog(call.lines);
60 const model = call.model || read.model;
61 const account = call.account ?? read.account;
62 const end = Math.max(call.endMs, call.startMs);
63 const outcome = outcomeOf(call.state);
64 const steps: Step[] = [
65 { id: call.id, kind: "model", name: model ?? "unknown", line: oneLine(`${model ?? "model"} ${call.prompt}`), startMs: call.startMs, endMs: end, model, tokensIn: call.tokensIn, tokensCached: 0, tokensOut: call.tokensOut, costUsd: call.costUsd, account, outcome },
66 ];
67 read.tools.forEach((t, i) =>
68 steps.push({ id: `${call.id}:${i}`, kind: SUBAGENT.has(t.name) ? "subagent" : "tool", name: t.name, line: t.line, startMs: call.startMs, endMs: end, model: undefined, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, account: undefined, outcome: "unknown" }),
69 );
70 return { index, prompt: oneLine(call.prompt, 300), startMs: call.startMs, steps };
71 }
72
73 function traceOf(source: "run" | "talk", id: string, title: string, repository: string | undefined, turns: Turn[], states: string[]): Trace {
74 const models = turns.flatMap((t) => t.steps.flatMap((s) => (s.kind === "model" && s.model !== undefined ? [s.model] : [])));
75 const accounts = turns.flatMap((t) => t.steps.flatMap((s) => (s.account !== undefined ? [s.account] : [])));
76 const outcomes = states.map(outcomeOf);
77 const outcome: Outcome = outcomes.includes("error") ? "error" : outcomes.length > 0 && outcomes.every((o) => o === "ok") ? "ok" : outcomes.includes("stopped") ? "stopped" : "unknown";
78 return { source, id, cwd: undefined, title: oneLine(title, 120), repository, model: models.at(-1), account: accounts.at(-1), outcome, turns, skipped: 0 };
79 }
80
81 /** A crew run as a trace, or undefined for a run that is not an agent's. */
82 export async function buildRunTrace(db: Database, dataDir: string, run: Run): Promise<Trace | undefined> {
83 if (run.kind !== "agent") return undefined;
84 const repo = getRepoById(db, run.repoId);
85 const issue = run.issueId === null ? undefined : getIssueById(db, run.issueId);
86 const used = getUsage(db, run.id);
87 const lines = await linesOf(db, dataDir, run.id);
88 const start = ms(run.startedAt ?? run.createdAt);
89 const call: Call = {
90 id: run.id,
91 prompt: issue?.title ?? run.summary,
92 startMs: start,
93 endMs: run.finishedAt === null ? start : ms(run.finishedAt),
94 state: run.state,
95 model: run.model,
96 account: undefined,
97 tokensIn: used?.tokensIn ?? run.tokensIn ?? 0,
98 tokensOut: used?.tokensOut ?? run.tokensOut ?? 0,
99 costUsd: run.costUsd,
100 lines,
101 };
102 const title = issue === undefined ? run.summary || run.reason : `#${issue.number} ${issue.title}`;
103 return traceOf("run", runTraceId(run.id), title, repo === undefined ? undefined : `${repo.ownerName}/${repo.name}`, [turnOf(0, call)], [run.state]);
104 }
105
106 interface TalkRunRow {
107 id: string;
108 prompt: string;
109 state: string;
110 model: string;
111 subscription_id: string | null;
112 tokens_in: number;
113 tokens_out: number;
114 cost_usd: number;
115 started_at: string;
116 finished_at: string | null;
117 }
118
119 /** A Talk conversation as a trace: one turn per answered message, in the order they were asked. */
120 export async function buildTalkTrace(db: Database, dataDir: string, conversationId: string): Promise<Trace | undefined> {
121 const conv = db.query<{ title: string }, [string]>("SELECT title FROM conversation WHERE id = ?1").get(conversationId);
122 if (conv === null) return undefined;
123 const rows = db
124 .query<TalkRunRow, [string]>("SELECT id, prompt, state, model, subscription_id, tokens_in, tokens_out, cost_usd, started_at, finished_at FROM conversation_run WHERE conversation_id = ?1 ORDER BY id")
125 .all(conversationId);
126 const names = new Map(db.query<{ id: string; name: string }, []>("SELECT id, name FROM subscription").all().map((s) => [s.id, s.name]));
127 const turns: Turn[] = [];
128 for (const [i, r] of rows.entries()) {
129 const start = ms(r.started_at);
130 const account = r.subscription_id === null ? undefined : r.subscription_id === PLATFORM ? "platform" : names.get(r.subscription_id);
131 turns.push(turnOf(i, { id: r.id, prompt: r.prompt, startMs: start, endMs: r.finished_at === null ? start : ms(r.finished_at), state: r.state, model: r.model, account, tokensIn: r.tokens_in, tokensOut: r.tokens_out, costUsd: r.cost_usd, lines: await linesOf(db, dataDir, r.id) }));
132 }
133 return traceOf("talk", talkTraceId(conversationId), conv.title || rows[0]?.prompt || "Talk", undefined, turns, rows.map((r) => r.state));
134 }
135
src/trace/claude_code.ts +4 −2
@@ -41,7 +41,7 @@ const textOf = (content: unknown): string => {
4141 };
4242
4343 export function parseClaudeSession(text: string): Trace {
44 const trace: Trace = { source: "claude-code", id: "", cwd: undefined, turns: [], skipped: 0 };
44 const trace: Trace = { source: "claude-code", id: "", cwd: undefined, title: "", repository: undefined, model: undefined, account: undefined, outcome: "unknown", turns: [], skipped: 0 };
4545 const open = new Map<string, Step>();
4646 const replies = new Map<string, Step>();
4747 let turn: Turn | undefined;
@@ -101,7 +101,7 @@ export function parseClaudeSession(text: string): Trace {
101101 const id = str(message.id) ?? str(rec.uuid) ?? `m${into.steps.length}`;
102102 let reply = replies.get(id);
103103 if (reply === undefined) {
104 reply = { id, kind: "model", name: str(message.model) ?? "unknown", line: "", startMs: ms, endMs: ms, model: str(message.model), tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "ok" };
104 reply = { id, kind: "model", name: str(message.model) ?? "unknown", line: "", startMs: ms, endMs: ms, model: str(message.model), tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, account: undefined, outcome: "ok" };
105105 replies.set(id, reply);
106106 into.steps.push(reply);
107107 }
@@ -129,6 +129,8 @@ export function parseClaudeSession(text: string): Trace {
129129 tokensIn: 0,
130130 tokensCached: 0,
131131 tokensOut: 0,
132 costUsd: 0,
133 account: undefined,
132134 outcome: "unknown" satisfies Outcome,
133135 };
134136 open.set(toolId, step);
src/trace/codex.ts +3 −3
@@ -43,7 +43,7 @@ export function isCodexRecord(rec: Json | undefined): boolean {
4343 }
4444
4545 export function parseCodexSession(text: string): Trace {
46 const trace: Trace = { source: "codex", id: "", cwd: undefined, turns: [], skipped: 0 };
46 const trace: Trace = { source: "codex", id: "", cwd: undefined, title: "", repository: undefined, model: undefined, account: undefined, outcome: "unknown", turns: [], skipped: 0 };
4747 const open = new Map<string, Step>();
4848 let turn: Turn | undefined;
4949 let model: string | undefined;
@@ -106,13 +106,13 @@ export function parseCodexSession(text: string): Trace {
106106 const into = turnAt(ms);
107107 const said = type === "message" ? textOf(p.content) : "";
108108 const name = model ?? "unknown";
109 reply = { id: `m${into.steps.length}:${ms}`, kind: "model", name, line: oneLine(`${name} ${said}`), startMs: ms, endMs: ms, model, tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "ok" };
109 reply = { id: `m${into.steps.length}:${ms}`, kind: "model", name, line: oneLine(`${name} ${said}`), startMs: ms, endMs: ms, model, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, account: undefined, outcome: "ok" };
110110 into.steps.push(reply);
111111 } else if (type === "function_call" || type === "local_shell_call") {
112112 const into = turnAt(ms);
113113 const name = str(p.name) ?? "shell";
114114 const id = str(p.call_id) ?? `c${into.steps.length}`;
115 const step: Step = { id, kind: "tool", name, line: oneLine(`${name} ${callTarget(str(p.arguments))}`), startMs: ms, endMs: ms, model: undefined, tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "unknown" };
115 const step: Step = { id, kind: "tool", name, line: oneLine(`${name} ${callTarget(str(p.arguments))}`), startMs: ms, endMs: ms, model: undefined, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, account: undefined, outcome: "unknown" };
116116 open.set(id, step);
117117 into.steps.push(step);
118118 } else if (type === "function_call_output") {
src/trace/from_log.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * A crew run's or Talk turn's log read into what it says happened (#17991): the model on its
3 * `session <id> (<model>)` line, the account on its `account: <name>, …` line, and one tool call
4 * per `→ Tool detail` line the agent wrote. The log carries no clock per line and no per-call
5 * tokens, so the caller gives the steps the run's own span and its recorded totals. Plain lines in,
6 * plain data out; a line that is none of these is ignored.
7 */
8 import { oneLine } from "./claude_code.ts";
9
10 export interface LogTool {
11 readonly name: string;
12 readonly line: string;
13 }
14
15 export interface LogReading {
16 readonly model: string | undefined;
17 readonly account: string | undefined;
18 readonly tools: LogTool[];
19 }
20
21 const SESSION = /^session \S+ \(([^)]*)\)$/;
22 const ACCOUNT = "account: ";
23 const TOOL = /^→ (\S+)(?: (.*))?$/;
24 const MAX_TOOLS = 5000;
25
26 export function readLog(lines: readonly string[]): LogReading {
27 let model: string | undefined;
28 let account: string | undefined;
29 const tools: LogTool[] = [];
30 for (const raw of lines) {
31 const session = SESSION.exec(raw);
32 if (session !== null) {
33 model ??= session[1] === "" ? undefined : session[1];
34 continue;
35 }
36 if (raw.startsWith(ACCOUNT)) {
37 account ??= raw.slice(ACCOUNT.length).split(",")[0]?.trim() || undefined;
38 continue;
39 }
40 const tool = TOOL.exec(raw);
41 if (tool !== null && tools.length < MAX_TOOLS) tools.push({ name: tool[1]!, line: oneLine(raw.slice(2)) });
42 }
43 return { model, account, tools };
44 }
src/trace/model.ts +26 −3
@@ -5,7 +5,7 @@
55 */
66
77 export type StepKind = "model" | "tool" | "subagent";
8 export type Outcome = "ok" | "error" | "unknown";
8 export type Outcome = "ok" | "error" | "stopped" | "unknown";
99
1010 export interface Step {
1111 id: string;
@@ -20,6 +20,13 @@ export interface Step {
2020 tokensIn: number;
2121 tokensCached: number;
2222 tokensOut: number;
23 /**
24 * What the step cost in dollars; 0 where the record does not say (a tool step costs nothing of
25 * its own).
26 */
27 costUsd: number;
28 /** The account the step ran on, when the record names it. */
29 account: string | undefined;
2330 outcome: Outcome;
2431 }
2532
@@ -30,10 +37,24 @@ export interface Turn {
3037 steps: Step[];
3138 }
3239
40 export type TraceKind = "claude-code" | "codex" | "talk" | "run";
41
3342 export interface Trace {
34 source: "claude-code" | "codex";
43 /**
44 * Where the raw record came from: a Claude Code session file, a Talk conversation, a crew run's
45 * log.
46 */
47 source: TraceKind;
3548 id: string;
3649 cwd: string | undefined;
50 /** What the thread was about, one line. */
51 title: string;
52 /** `owner/name` for a run; none for a conversation or a file. */
53 repository: string | undefined;
54 /** The model the thread mostly ran on; none when unrecorded. */
55 model: string | undefined;
56 account: string | undefined;
57 outcome: Outcome;
3758 turns: Turn[];
3859 /** Lines of the file that were not a record; counted, never fatal. */
3960 skipped: number;
@@ -49,6 +70,7 @@ export interface Totals {
4970 tokensIn: number;
5071 tokensCached: number;
5172 tokensOut: number;
73 costUsd: number;
5274 errors: number;
5375 startMs: number;
5476 endMs: number;
@@ -57,11 +79,12 @@ export interface Totals {
5779 /** The running total the trace page and the terminal state beside the tree. */
5880 export function totalsOf(trace: Trace): Totals {
5981 const all = stepsOf(trace);
60 const t: Totals = { steps: all.length, tokensIn: 0, tokensCached: 0, tokensOut: 0, errors: 0, startMs: 0, endMs: 0 };
82 const t: Totals = { steps: all.length, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, errors: 0, startMs: 0, endMs: 0 };
6183 for (const s of all) {
6284 t.tokensIn += s.tokensIn;
6385 t.tokensCached += s.tokensCached;
6486 t.tokensOut += s.tokensOut;
87 t.costUsd += s.costUsd;
6588 if (s.outcome === "error") t.errors += 1;
6689 }
6790 let start = Infinity;
src/trace/run_log.ts +8 −1
@@ -43,6 +43,8 @@ export function parseRunLog(runId: string, prompt: string, lines: readonly strin
4343 tokensIn: 0,
4444 tokensCached: 0,
4545 tokensOut: 0,
46 costUsd: 0,
47 account: undefined,
4648 outcome: bad ? "error" : "unknown",
4749 });
4850 spans.push({ from, to });
@@ -74,9 +76,14 @@ export function parseRunLog(runId: string, prompt: string, lines: readonly strin
7476 });
7577 }
7678 const trace: Trace = {
77 source: "claude-code",
79 source: "run",
7880 id: runId,
7981 cwd: undefined,
82 title: oneLine(prompt),
83 repository: undefined,
84 model: undefined,
85 account: undefined,
86 outcome: steps.some((s) => s.outcome === "error") ? "error" : "unknown",
8087 turns: [{ index: 0, prompt, startMs: 0, steps }],
8188 skipped: 0,
8289 };
src/trace/schedule.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * Runs the trace sweep (`sweep.ts`, #17991) from the forge's boot: one slice, then the event loop
3 * is given back (a pause between slices while there is more to do, a long one when there is not).
4 * Never two slices at once; a slice that throws is logged and tried again later.
5 */
6 import type { Database } from "bun:sqlite";
7 import { background } from "../perf/jobs.ts";
8 import { sweepSlice } from "./sweep.ts";
9
10 export const BUSY_MS = 250;
11 export const IDLE_MS = 30_000;
12
13 export function startTraceSweep(db: Database, dataDir: string, log: { error(message: string, fields?: Record<string, unknown>): void }): () => void {
14 let timer: ReturnType<typeof setTimeout> | undefined;
15 let stopped = false;
16 const tick = async (): Promise<void> => {
17 let next = IDLE_MS;
18 try {
19 next = (await sweepSlice(db, dataDir)) > 0 ? BUSY_MS : IDLE_MS;
20 } catch (error) {
21 log.error("trace sweep failed", { error: String(error) });
22 }
23 if (!stopped) {
24 timer = setTimeout(() => void background("trace-sweep", tick), next);
25 timer.unref();
26 }
27 };
28 timer = setTimeout(() => void background("trace-sweep", tick), BUSY_MS);
29 timer.unref();
30 return () => {
31 stopped = true;
32 if (timer !== undefined) clearTimeout(timer);
33 };
34 }
src/trace/store.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * The trace list (#17991): a summary row per trace in `trace_index`, written from a built `Trace`
3 * and read newest first by keyset. It holds no content; `GET /api/v1/traces/:id` rebuilds the tree
4 * from the raw record. Who may see a row is the caller's rule (`allow`), asked per row.
5 */
6 import type { Database } from "bun:sqlite";
7 import { totalsOf, type Trace } from "./model.ts";
8
9 export interface TraceRow {
10 readonly id: string;
11 readonly kind: "talk" | "run";
12 readonly repo_id: string;
13 readonly user_id: string;
14 readonly repository: string;
15 readonly title: string;
16 readonly model: string;
17 readonly account: string;
18 readonly steps: number;
19 readonly tokens_in: number;
20 readonly tokens_cached: number;
21 readonly tokens_out: number;
22 readonly cost_usd: number;
23 readonly outcome: string;
24 readonly started: number;
25 readonly ended: number;
26 }
27
28 /**
29 * Write (or replace) a trace's row. `owner` is the repository's id for a run, the person's for a
30 * conversation.
31 */
32 export function putTrace(db: Database, trace: Trace, owner: { readonly repoId?: string; readonly userId?: string }, stamp: string): void {
33 if (trace.source === "claude-code") return;
34 const t = totalsOf(trace);
35 db.query(
36 `INSERT OR REPLACE INTO trace_index (id, kind, repo_id, user_id, repository, title, model, account, steps, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started, ended, stamp)
37 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17)`,
38 ).run(trace.id, trace.source, owner.repoId ?? "", owner.userId ?? "", trace.repository ?? "", trace.title, trace.model ?? "", trace.account ?? "", t.steps, t.tokensIn, t.tokensCached, t.tokensOut, t.costUsd, trace.outcome, t.startMs, t.endMs, stamp);
39 }
40
41 export interface TraceFilter {
42 readonly repository?: string | undefined;
43 readonly kind?: "talk" | "run" | undefined;
44 readonly model?: string | undefined;
45 readonly outcome?: string | undefined;
46 /** Inclusive bounds, in epoch milliseconds. */
47 readonly from?: number | undefined;
48 readonly to?: number | undefined;
49 }
50
51 export const CURSOR_SHAPE = /^\d{1,16}_[a-z0-9-]{1,64}$/;
52 /**
53 * The most rows one request looks at, so a caller who may see few of them cannot make it walk all.
54 */
55 export const SCAN_MAX = 5000;
56 const CHUNK = 500;
57
58 /**
59 * A page of the list, newest first: up to `limit` rows `allow` accepts, after `cursor`
60 * (`<started>_<id>`), and the cursor of the next page or null at the end.
61 */
62 export function listTraces(
63 db: Database,
64 filter: TraceFilter,
65 allow: (row: TraceRow) => boolean,
66 limit: number,
67 cursor: string | null,
68 ): { rows: TraceRow[]; next: string | null } {
69 const where: string[] = [];
70 const args: (string | number)[] = [];
71 const add = (sql: string, v: string | number): void => void (args.push(v), where.push(sql.replace("?", `?${args.length}`)));
72 if (filter.kind !== undefined) add("kind = ?", filter.kind);
73 if (filter.repository !== undefined) add("repository = ? COLLATE NOCASE", filter.repository);
74 if (filter.model !== undefined) add("model = ?", filter.model);
75 if (filter.outcome !== undefined) add("outcome = ?", filter.outcome);
76 if (filter.from !== undefined) add("started >= ?", filter.from);
77 if (filter.to !== undefined) add("started <= ?", filter.to);
78 let after = cursor === null ? undefined : { started: Number(cursor.split("_")[0]), id: cursor.slice(cursor.indexOf("_") + 1) };
79 const rows: TraceRow[] = [];
80 let scanned = 0;
81 let last: TraceRow | undefined;
82 for (;;) {
83 const w = [...where];
84 const a = [...args];
85 if (after !== undefined) {
86 a.push(after.started, after.id);
87 w.push(`(started < ?${a.length - 1} OR (started = ?${a.length - 1} AND id < ?${a.length}))`);
88 }
89 const chunk = db
90 .query<TraceRow, (string | number)[]>(`SELECT * FROM trace_index ${w.length === 0 ? "" : `WHERE ${w.join(" AND ")}`} ORDER BY started DESC, id DESC LIMIT ${CHUNK}`)
91 .all(...a);
92 for (const [i, row] of chunk.entries()) {
93 scanned += 1;
94 last = row;
95 if (allow(row)) rows.push(row);
96 if (rows.length === limit || scanned >= SCAN_MAX) {
97 // Stopped early: another page exists unless this was the table's last row.
98 const more = !(chunk.length < CHUNK && i === chunk.length - 1);
99 return { rows, next: more ? `${row.started}_${row.id}` : null };
100 }
101 }
102 if (chunk.length < CHUNK) return { rows, next: null };
103 after = { started: last!.started, id: last!.id };
104 }
105 }
106
107 export function getTraceRow(db: Database, id: string): TraceRow | undefined {
108 return db.query<TraceRow, [string]>("SELECT * FROM trace_index WHERE id = ?1").get(id) ?? undefined;
109 }
src/trace/sweep.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * Keeps the trace list (#17991) in step with the raw record, in slices that give the serving thread
3 * back between them. Two places in `trace_mark` — the last run id and the last Talk turn id handled
4 * — walk each table by its primary key, so a first pass backfills every existing trace and every
5 * later pass picks up what finished since. A run or turn still running is left, and the walk waits
6 * behind it for `SETTLE_MS` (then skips it as stuck). A Talk conversation is rewritten whenever one
7 * of its turns is handled, so its row follows its last finished turn.
8 */
9 import type { Database } from "bun:sqlite";
10 import { getRun, isTerminal } from "../core/runs.ts";
11 import { buildRunTrace, buildTalkTrace } from "./build.ts";
12 import { putTrace } from "./store.ts";
13
14 /** Rows handled in one slice. */
15 export const SLICE = 20;
16 /** How long a run that has not finished holds the walk before it is skipped. */
17 export const SETTLE_MS = 6 * 3_600_000;
18
19 const markOf = (db: Database, source: string): string => db.query<{ after: string }, [string]>("SELECT after FROM trace_mark WHERE source = ?1").get(source)?.after ?? "";
20 const setMark = (db: Database, source: string, after: string): void => void db.query("INSERT OR REPLACE INTO trace_mark (source, after) VALUES (?1, ?2)").run(source, after);
21
22 /** Index one run; true when it was an agent run that had finished. */
23 export async function indexRun(db: Database, dataDir: string, runId: string): Promise<boolean> {
24 const run = getRun(db, runId);
25 if (run === undefined || run.kind !== "agent" || !isTerminal(run.state)) return false;
26 const trace = await buildRunTrace(db, dataDir, run);
27 if (trace === undefined) return false;
28 putTrace(db, trace, { repoId: run.repoId }, run.finishedAt ?? "");
29 return true;
30 }
31
32 /** Index one conversation from its turns. */
33 export async function indexConversation(db: Database, dataDir: string, conversationId: string): Promise<boolean> {
34 const owner = db.query<{ user_id: string; updated_at: string }, [string]>("SELECT user_id, updated_at FROM conversation WHERE id = ?1").get(conversationId);
35 if (owner === null) return false;
36 const trace = await buildTalkTrace(db, dataDir, conversationId);
37 if (trace === undefined) return false;
38 putTrace(db, trace, { userId: owner.user_id }, owner.updated_at);
39 return true;
40 }
41
42 /** One slice of each walk; how many traces it wrote. */
43 export async function sweepSlice(db: Database, dataDir: string, now: number = Date.now(), slice: number = SLICE): Promise<number> {
44 let written = 0;
45 let after = markOf(db, "run");
46 const runs = db.query<{ id: string; state: string; created_at: string }, [string, number]>("SELECT id, state, created_at FROM run WHERE kind = 'agent' AND id > ?1 ORDER BY id LIMIT ?2").all(after, slice);
47 for (const r of runs) {
48 if (!isTerminal(r.state as never) && now - Date.parse(r.created_at) < SETTLE_MS) break;
49 if (await indexRun(db, dataDir, r.id)) written += 1;
50 after = r.id;
51 }
52 setMark(db, "run", after);
53
54 after = markOf(db, "talk");
55 const turns = db.query<{ id: string; conversation_id: string; state: string; started_at: string }, [string, number]>("SELECT id, conversation_id, state, started_at FROM conversation_run WHERE id > ?1 ORDER BY id LIMIT ?2").all(after, slice);
56 const done = new Set<string>();
57 for (const t of turns) {
58 if (t.state === "running" && now - Date.parse(t.started_at) < SETTLE_MS) break;
59 if (!done.has(t.conversation_id) && (await indexConversation(db, dataDir, t.conversation_id))) {
60 done.add(t.conversation_id);
61 written += 1;
62 }
63 after = t.id;
64 }
65 setMark(db, "talk", after);
66
67 return written;
68 }
src/tui/screens/traces.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * Traces in the terminal (#17991): what `GET /api/v1/traces` lists and `GET /api/v1/traces/:id`
3 * answers, through the same actions (`actions/traces.ts`) and so the same gate: your Talk
4 * conversations and the crew runs whose log you may read. j/k scroll, the row at the top is the one
5 * marked ▸, Enter opens it as a tree (turns, then a step a line), Esc or q goes back.
6 */
7
8 import { traceList, traceTree, type TraceSummary, type TraceTree } from "../../actions/traces.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import { binding } from "../app/keys.ts";
11 import type { Session } from "../session.ts";
12 import { style } from "../term/style.ts";
13 import { pad } from "../term/width.ts";
14 import { Scroll, drawLines, hitScroll } from "./common.ts";
15 import type { PaletteEntry } from "./entries.ts";
16
17 const PAGE = 100;
18 const clock = (iso: string): string => iso.slice(0, 16).replace("T", " ");
19 const span = (ms: number): string => (ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`);
20
21 /** One line of the list: when, kind, outcome, steps, tokens, cost, title. */
22 export const summaryLine = (t: TraceSummary): string =>
23 `${pad(clock(t.started_at), 17)}${pad(t.kind, 5)}${pad(t.outcome, 8)}${pad(String(t.steps), 6)}${pad(`${t.tokens_in}/${t.tokens_out}`, 14)}${pad(`$${t.cost_usd.toFixed(2)}`, 8)}${t.title}`;
24
25 /** The list as lines, header first; empty for someone who is not signed in. */
26 export function traceLines(session: Session): { lines: string[]; ids: string[] } {
27 if (session.user === undefined) return { lines: [], ids: [] };
28 const page = traceList(session.app, session.user, {}, PAGE, null);
29 const head = `${pad("Started (UTC)", 17)}${pad("Kind", 5)}${pad("Outcome", 8)}${pad("Steps", 6)}${pad("In/out", 14)}${pad("Cost", 8)}Title`;
30 return { lines: [head, ...page.items.map(summaryLine)], ids: page.items.map((t) => t.id) };
31 }
32
33 /** A tree as lines: its facts, then each turn and a step under it a line, then the totals. */
34 export function treeLines(tree: TraceTree): string[] {
35 const out = [`${tree.kind} ${tree.title}`, `${tree.repository ?? "-"} · ${tree.model ?? "-"} · ${tree.account ?? "-"} · ${tree.outcome}`];
36 for (const turn of tree.turns) {
37 out.push(`▾ ${turn.index + 1}. ${turn.prompt || "(no prompt)"}`);
38 for (const s of turn.steps) {
39 const tokens = s.kind === "model" ? ` ${s.tokens_in}+${s.tokens_cached}c in ${s.tokens_out} out $${s.cost_usd.toFixed(2)}` : "";
40 out.push(` ${s.kind.padEnd(8)} ${s.line}${tokens} ${span(Date.parse(s.ended_at) - Date.parse(s.started_at))}`);
41 }
42 }
43 const t = tree.totals;
44 out.push(`${t.steps} steps, ${t.tokens_in} in (${t.tokens_cached} cached), ${t.tokens_out} out, $${t.cost_usd.toFixed(2)}, ${t.errors} failed`);
45 return out;
46 }
47
48 function linesScreen(ctx: Ctx, title: string, lines: readonly string[], open?: (row: number) => void): Screen {
49 const scroll = new Scroll();
50 return {
51 title,
52 keys: [binding(["j", "k"], "scroll"), ...(open === undefined ? [] : [binding(["enter"], "open")]), binding(["esc", "q"], "back")],
53 render(area, s) {
54 const c = ctx.theme.c;
55 const spans = lines.map((text, i) => [{ text: open !== undefined && i === scroll.top + 1 ? `▸ ${text}` : text, style: style(i === 0 ? c.fg : c.mutedFg, c.bg) }]);
56 drawLines(s, area, c, scroll, spans);
57 hitScroll(ctx, area, scroll, lines.length);
58 },
59 key(e) {
60 if (scroll.key(e, lines.length)) return true;
61 if (e.key === "enter" && open !== undefined) {
62 open(scroll.top);
63 return true;
64 }
65 if (e.key === "esc" || e.key === "q") {
66 ctx.pop();
67 return true;
68 }
69 return false;
70 },
71 };
72 }
73
74 export function tracesScreen(session: Session, ctx: Ctx): Screen {
75 const { lines, ids } = traceLines(session);
76 return linesScreen(ctx, "Traces", lines, (row) => {
77 const id = ids[row];
78 if (id === undefined || session.user === undefined) return;
79 void traceTree(session.app, session.user, id).then((tree) => {
80 if (tree !== undefined) ctx.push(linesScreen(ctx, tree.title, treeLines(tree)));
81 });
82 });
83 }
84
85 export const entry: PaletteEntry = {
86 rank: 1105,
87 id: "traces",
88 title: "Traces",
89 hint: "every Talk conversation and crew run, as turns and steps",
90 offered: (session) => session.user !== undefined,
91 run: (session, ctx) => ctx.push(tracesScreen(session, ctx)),
92 };
test/budgets/unfixtured/api-v1-traces-id.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/api/v1/traces/:id",
3 "why": "a trace id the index holds, which the page-budget seed has none of (#17991, test/traces.test.ts covers it)"
4 }
test/job-slices.test.ts +1
@@ -300,6 +300,7 @@ function jobs(): Record<string, () => unknown> {
300300 * on.
301301 */
302302 const UNTIMED: Record<string, string> = {
303 "trace-sweep": "a slice of 20 runs and 20 Talk turns every 250 ms while there is backlog, 30 s when idle (trace/schedule.ts): PK-ordered reads and one log file read each, async between slices; traces.test.ts drives sweepSlice",
303304 "job-pack-sweep": "a one-shot timer a minute after a shared runner-job pack is whole (git/pack_share.ts): a walk of at most SHARE_MAX in-memory entries and an async unlink each; runner-fetch-share.test.ts drives the expiry with a clock",
304305 "push": "one event's pushes to Apple (push/watch.ts): a few indexed reads, at most one askLinesFor per person with an alert device, and network answers that are not timed here; push-apns.test.ts drives it with a recording transport",
305306 "decider-shadow": "one call to a second decider after a decision is recorded (crew/snap.ts): a few indexed reads, one insert and a network answer, at most two at once; decider-shadow.test.ts drives it with a fake",
test/palette-roster.test.ts +3
@@ -265,6 +265,7 @@ test("a site-admin person is offered the whole roster", () => {
265265 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],
266266 ["profile", "Your profile", "display name and email"],
267267 ["dotfiles", "Your dotfiles", "the repository every shell you open copies from"],
268 ["traces", "Traces", "every Talk conversation and crew run, as turns and steps"],
268269 ["security", "Security", "what the forge enforces for everyone, and how to report a problem"],
269270 ["family", "Family", "the forge that sent this one, and the forges it sent"],
270271 ["chain", "Chain", "the forges this forge's code descends from, root first"],
@@ -386,6 +387,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
386387 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],
387388 ["front-milestones", "Milestones", "the biggest open milestones: how far, what landed this week"],
388389 ["forge-view", "Forge view", "the forge's counts, and Foundry when it is installed"],
390 ["traces", "Traces", "every Talk conversation and crew run, as turns and steps"],
389391 ["security", "Security", "what the forge enforces for everyone, and how to report a problem"],
390392 ["family", "Family", "the forge that sent this one, and the forges it sent"],
391393 ["chain", "Chain", "the forges this forge's code descends from, root first"],
@@ -512,6 +514,7 @@ test("a member person is offered the signed-in roster without the admin entries"
512514 ["dotfiles", "Your dotfiles", "the repository every shell you open copies from"],
513515 ["front-milestones", "Milestones", "the biggest open milestones: how far, what landed this week"],
514516 ["forge-view", "Forge view", "the forge's counts, and Foundry when it is installed"],
517 ["traces", "Traces", "every Talk conversation and crew run, as turns and steps"],
515518 ["security", "Security", "what the forge enforces for everyone, and how to report a problem"],
516519 ["family", "Family", "the forge that sent this one, and the forges it sent"],
517520 ["chain", "Chain", "the forges this forge's code descends from, root first"],
test/route-timing-coverage.test.ts +1
@@ -26,6 +26,7 @@ const UNTIMED: Record<string, string> = {
2626 "/api/v1/admin/machines/:machine/disks": "an owner's per-machine disk summary, one indexed read; no page to phase",
2727 "/api/v1/repos/:owner/:name/issues/:number/estimates": "an issue's base rate from one indexed read of its history; no page to phase",
2828 "/api/v1/templates": "the marked repositories, one indexed read; no page to phase",
29 "/api/v1/traces": "the trace index, one indexed read; no page to phase (#17991)",
2930 "/api/v1/repos/:owner/:name/drop": "an app's drop listing, one indexed read and a directory scan; no page to phase",
3031 "/api/v1/repos/:owner/:name/crew-devices": "a repository admin's device list, one indexed read; no page to phase",
3132 "/api/v1/repos/:owner/:name/app/registry": "an app's installed registry items, one indexed read; no page to phase",
test/security-floor-routes.test.ts +1
@@ -86,6 +86,7 @@ const UNSEEDED: Record<string, string> = {
8686 "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)",
8787 "/api/v1/repos/:owner/:name/app/errors/:group": "an error group of an app that has been sent an error; the seed app has none (test/error-groups.test.ts covers it)",
8888 "/api/v1/repos/:owner/:name/drop/:file": "a file name in an app's private drop; the seed drops none",
89 "/api/v1/traces/:id": "a trace id the index holds, which the seed has none of (test/traces.test.ts covers it)",
8990 "/api/v1/runner/jobs/:id/git/info/refs": "a job a runner holds, read with that job's own token; the seed offers none (test/checks-runner-placement.test.ts covers it)",
9091 "/api/v1/runner/jobs/:id/seed": "a file a runner's job is seeded with, read with that job's own token; the seed offers none (test/runner-seeds.test.ts covers it)",
9192 "/client-clouds/:id": "needs a client's cloud the signed-in person is named on; the seed has none (test/client-cloud.test.ts covers it)",
test/trace.test.ts +2 −2
@@ -66,9 +66,9 @@ test("forge trace reads a file, and says so when it holds nothing", async () =>
6666 test("a very long session totals and exports without a stack overflow", () => {
6767 const steps = Array.from({ length: 200_000 }, (_, i) => ({
6868 id: `s${i}`, kind: "tool" as const, name: "Edit", line: "Edit a.ts", startMs: 1000 + i, endMs: 1001 + i,
69 model: undefined, tokensIn: 1, tokensCached: 0, tokensOut: 1, outcome: "ok" as const,
69 model: undefined, tokensIn: 1, tokensCached: 0, tokensOut: 1, costUsd: 0, account: undefined, outcome: "ok" as const,
7070 }));
71 const trace = { source: "claude-code" as const, id: "big", cwd: undefined, skipped: 0, turns: [{ index: 0, prompt: "p", startMs: 1000, steps }] };
71 const trace = { source: "claude-code" as const, id: "big", cwd: undefined, title: "", repository: undefined, model: undefined, account: undefined, outcome: "unknown" as const, skipped: 0, turns: [{ index: 0, prompt: "p", startMs: 1000, steps }] };
7272 const totals = totalsOf(trace);
7373 expect(totals).toMatchObject({ steps: 200_000, startMs: 1000, endMs: 1001 + 199_999 });
7474 const doc = toOtlp(trace) as { resourceSpans: { scopeSpans: { spans: unknown[] }[] }[] };
test/traces.test.ts added +171
@@ -0,0 +1,171 @@
1 /**
2 * Traces 1 (#17991): one normalized trace for every Talk conversation and crew run, rebuilt from
3 * the raw record; the list is a small index kept by a sweep; the API and the terminal read the same
4 * rows.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { traceList } from "../src/actions/traces.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { createConversation } from "../src/core/conversations.ts";
15 import { createRun, getRun } from "../src/core/runs.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { recordUsage, getUsage } from "../src/core/usage.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { appendRunLog, flushRunLogs } from "../src/runs/log.ts";
21 import { readLog } from "../src/trace/from_log.ts";
22 import { buildRunTrace, buildTalkTrace } from "../src/trace/build.ts";
23 import { totalsOf } from "../src/trace/model.ts";
24 import { sweepSlice } from "../src/trace/sweep.ts";
25 import { statements } from "./helpers/statements.ts";
26 import { expectWork } from "./helpers/work.ts";
27 import { seedAdmin } from "./helpers/admin.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29
30 quietLogs();
31
32 const LOG = ["account: SubQ, 1st of 2 in order: first in order", "session abc (claude-sonnet-5-5)", "I will read the file.", "→ Read src/a.ts", "→ Edit src/a.ts", "→ Task explore the tests"];
33
34 describe("traces", () => {
35 let dataDir: string;
36 let app: App;
37 let servers: Servers;
38 let ada: User;
39 let bob: User;
40 let adaToken: string;
41 let bobToken: string;
42 let runId: string;
43 let conversationId: string;
44
45 const get = (path: string, token?: string) => fetch(`${servers.url}${path}`, { headers: token === undefined ? {} : { authorization: `Bearer ${token}` } });
46
47 beforeAll(async () => {
48 dataDir = await mkdtemp(join(tmpdir(), "forge-traces-"));
49 app = createApp({ dataDir, port: 0 });
50 servers = await serve(app);
51 const a = await seedAdmin(app, { username: "ada", email: "[email protected]" });
52 if (!a.ok) throw new Error(a.error);
53 ada = a.value;
54 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
55 if (!b.ok) throw new Error(b.error);
56 bob = b.value;
57 adaToken = createToken(app.db, ada.id, "t", "ro").token;
58 bobToken = createToken(app.db, bob.id, "t", "ro").token;
59
60 const repo = await createRepo(app, ada, { name: "hello", visibility: "public" });
61 if (!repo.ok) throw new Error(String(repo.error));
62 const issue = createIssue(app.db, { repoId: repo.value.id, authorId: ada.id, title: "round the corners" });
63 if (!issue.ok) throw new Error("issue");
64 const run = createRun(app.db, { repoId: repo.value.id, kind: "agent", issueId: issue.value.id, reason: "work" });
65 runId = run.id;
66 app.db.query("UPDATE run SET state = 'ok', model = 'claude-sonnet-5-5', cost_usd = 0.42, turns = 3, started_at = '2026-12-01T10:00:00.000Z', finished_at = '2026-12-01T10:05:00.000Z' WHERE id = ?1").run(runId);
67 recordUsage(app.db, { runId, repoId: repo.value.id, issueId: issue.value.id, agentId: null, subscriptionId: null, tokensIn: 1200, tokensOut: 340, costUsd: 0.42, wallMs: 300_000, outcome: "ok", at: "2026-12-01T10:05:00.000Z" });
68 for (const line of LOG) appendRunLog(dataDir, runId, line);
69 flushRunLogs();
70
71 const conv = createConversation(app.db, ada.id);
72 if (!conv.ok) throw new Error("conversation");
73 conversationId = conv.value.id;
74 const turn = (id: string, prompt: string, state: string, at: string, cost: number, lines: string[]) => {
75 app.db.query("INSERT INTO conversation_run (id, conversation_id, user_id, subscription_id, prompt, state, model, tokens_in, tokens_out, cost_usd, started_at, finished_at) VALUES (?1,?2,?3,'platform',?4,?5,'claude-haiku-5-5',100,50,?6,?7,?8)").run(id, conversationId, ada.id, prompt, state, cost, at, at);
76 for (const l of lines) appendRunLog(dataDir, id, l);
77 };
78 turn("0turn1", "list my apps", "ok", "2026-12-02T09:00:00.000Z", 0.01, ["session s1 (claude-haiku-5-5)", "→ mcp__forge__apps"]);
79 turn("0turn2", "fix the typo", "failed", "2026-12-02T09:05:00.000Z", 0.02, ["session s1 (claude-haiku-5-5)"]);
80 flushRunLogs();
81 });
82 afterAll(async () => {
83 await servers.stop();
84 app.close();
85 await rm(dataDir, { recursive: true, force: true });
86 });
87
88 test("a log is read for its model, account and tool calls", () => {
89 const read = readLog(LOG);
90 expect(read.model).toBe("claude-sonnet-5-5");
91 expect(read.account).toBe("SubQ");
92 expect(read.tools.map((t) => t.name)).toEqual(["Read", "Edit", "Task"]);
93 });
94
95 test("a crew run's trace has the steps, tokens and cost the run page shows", async () => {
96 const run = getRun(app.db, runId)!;
97 const trace = (await buildRunTrace(app.db, dataDir, run))!;
98 const used = getUsage(app.db, runId)!;
99 const t = totalsOf(trace);
100 expect(t.steps).toBe(1 + 3);
101 expect([t.tokensIn, t.tokensOut]).toEqual([used.tokensIn, used.tokensOut]);
102 expect(t.costUsd).toBe(run.costUsd);
103 expect(trace).toMatchObject({ source: "run", repository: "ada/hello", model: "claude-sonnet-5-5", account: "SubQ", outcome: "ok" });
104 expect(trace.turns[0]!.steps.map((s) => s.kind)).toEqual(["model", "tool", "tool", "subagent"]);
105 expect(trace.title).toContain("round the corners");
106 });
107
108 test("a Talk conversation's trace has a turn per answered message", async () => {
109 const trace = (await buildTalkTrace(app.db, dataDir, conversationId))!;
110 const t = totalsOf(trace);
111 expect(trace.turns.map((x) => x.prompt)).toEqual(["list my apps", "fix the typo"]);
112 expect(t.steps).toBe(2 + 1);
113 expect([t.tokensIn, t.tokensOut]).toEqual([200, 100]);
114 expect(t.costUsd).toBeCloseTo(0.03, 10);
115 expect(trace).toMatchObject({ source: "talk", outcome: "error", account: "platform" });
116 });
117
118 test("the sweep indexes what exists, once, in slices", async () => {
119 expect(await sweepSlice(app.db, dataDir, Date.now(), 1)).toBeGreaterThan(0);
120 while ((await sweepSlice(app.db, dataDir)) > 0);
121 const n = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM trace_index").get()!.n;
122 expect(n).toBe(2);
123 expect(await sweepSlice(app.db, dataDir)).toBe(0);
124 });
125
126 test("the list answers newest first with filters and a cursor, and the tree rebuilds", async () => {
127 expect((await get("/api/v1/traces")).status).toBe(401);
128 const all = (await (await get("/api/v1/traces", adaToken)).json()) as any;
129 expect(all.items.map((i: any) => i.kind)).toEqual(["talk", "run"]);
130 expect(all.items[1]).toMatchObject({ id: `run-${runId}`, repository: "ada/hello", steps: 4, tokens_in: 1200, tokens_out: 340, cost_usd: 0.42, outcome: "ok", model: "claude-sonnet-5-5", account: "SubQ" });
131 const one = (await (await get("/api/v1/traces?limit=1", adaToken)).json()) as any;
132 expect(one.items.length).toBe(1);
133 const rest = (await (await get(`/api/v1/traces?limit=1&cursor=${one.next_cursor}`, adaToken)).json()) as any;
134 expect(rest.items[0].kind).toBe("run");
135 const cases: [string, string[]][] = [["kind=run", ["run"]], ["outcome=error", ["talk"]], ["repository=ada/hello", ["run"]], ["model=claude-haiku-5-5", ["talk"]], ["from=2026-12-02", ["talk"]], ["to=2026-12-01", ["run"]]];
136 for (const [q, kinds] of cases) {
137 const r = (await (await get(`/api/v1/traces?${q}`, adaToken)).json()) as any;
138 expect(r.items.map((i: any) => i.kind)).toEqual(kinds);
139 }
140 const tree = (await (await get(`/api/v1/traces/run-${runId}`, adaToken)).json()) as any;
141 expect(tree.totals).toMatchObject({ steps: 4, tokens_in: 1200, tokens_out: 340, cost_usd: 0.42 });
142 expect(tree.turns[0].steps.length).toBe(4);
143 const talk = (await (await get(`/api/v1/traces/talk-${conversationId}`, adaToken)).json()) as any;
144 expect(talk.turns.length).toBe(2);
145 });
146
147 test("a bad query is refused, and a Talk conversation is its person's alone", async () => {
148 for (const q of ["kind=x", "outcome=x", "repository=nope", "from=2026-13-40", "limit=0", "cursor=zz"]) expect((await get(`/api/v1/traces?${q}`, adaToken)).status).toBe(422);
149 const bobs = (await (await get("/api/v1/traces", bobToken)).json()) as any;
150 // Bob reads a public repository but not the crew's log: neither trace is his.
151 expect(bobs.items).toEqual([]);
152 expect((await get(`/api/v1/traces/talk-${conversationId}`, bobToken)).status).toBe(404);
153 expect((await get(`/api/v1/traces/run-${runId}`, bobToken)).status).toBe(404);
154 expect((await get("/api/v1/traces/..%2Fx", adaToken)).status).toBe(404);
155 });
156
157 test("the list answers in a few statements with 10,000 rows, and walks an index", async () => {
158 const insert = app.db.query("INSERT INTO trace_index (id, kind, user_id, title, model, outcome, started, ended) VALUES (?1,'talk',?2,'t','m','ok',?3,?3)");
159 app.db.transaction(() => {
160 for (let i = 0; i < 10_000; i++) insert.run(`talk-bulk${String(i).padStart(6, "0")}`, ada.id, 1_700_000_000_000 + i);
161 })();
162 let page = traceList(app, ada, { kind: "talk", outcome: "ok" }, 50, null);
163 expect(page.items.length).toBe(50);
164 expect(page.next_cursor).not.toBeNull();
165 expectWork(await statements(app.db, () => void (page = traceList(app, ada, { kind: "talk", outcome: "ok" }, 50, null))), { max: 2 });
166 for (const sql of ["SELECT * FROM trace_index ORDER BY started DESC, id DESC LIMIT 500", "SELECT * FROM trace_index WHERE kind = 'talk' ORDER BY started DESC, id DESC LIMIT 500"]) {
167 const plan = app.db.query<{ detail: string }, []>(`EXPLAIN QUERY PLAN ${sql}`).all().map((r) => r.detail).join(" ");
168 expect(plan).not.toMatch(/SCAN trace_index(?! USING)|TEMP B-TREE/);
169 }
170 });
171 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs