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

Traces 5c: the trace list and one trace read through MCP tools and a terminal screen compare #18183

opened this

Merged 4h 44m ago, live in production

scout/forge:scout/18085-traces-5c-the-trace-list-and-one-trace-r → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/18085-traces-5c-the-trace-list-and-one-trace-r was merged into main as cc38920.

Review

Sign in to review this change.
6 files changed +377 −161
docs/features/traces.md +4 −2
@@ -18,7 +18,7 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu
1818
1919 ## The list (#17992)
2020
21 `/traces` lists every crew run the viewer may open (a run's log is the crew's and the owner's, as on its run page), newest first, a line each: title, kind, repository, model, cost (for those who may see spend), time, outcome. The search and the facets (repository, model, outcome, person or agent, from and to dates) are query parameters, so a search is a link (`/traces?repo=alice/notes&model=claude-opus&q=footer`); a malformed one is dropped. `q` matches the run's issue title and summary. `j`/`k` move, Enter opens the trace, `/` searches; the first paint holds no script of its own. Older traces follow a cursor (`before`). Terminal door: the Traces command in the palette (`src/tui/screens/traces.ts`: `/` searches, `j`/`k` move, Enter opens, `n` older). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`).
21 `/traces` lists every crew run the viewer may open (a run's log is the crew's and the owner's, as on its run page), newest first, a line each: title, kind, repository, model, cost (for those who may see spend), time, outcome. The search and the facets (repository, model, outcome, person or agent, from and to dates) are query parameters, so a search is a link (`/traces?repo=alice/notes&model=claude-opus&q=footer`); a malformed one is dropped. `q` matches the run's issue title and summary. `j`/`k` move, Enter opens the trace, `/` searches; the first paint holds no script of its own. Older traces follow a cursor (`before`). Terminal door: the Traces command in the palette (`src/tui/screens/traces.ts`: `/` searches, `j`/`k` move, Enter opens, `n` older, `v` marks a row (two at most) and `d` opens the two as the comparison below, #18085; two runs of different issues are told so). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`).
2222
2323 Not yet: Talk conversations and outside imports as rows (they wait for the trace index of #17991), a kind facet (every row is a crew run), archived turns in the search, and a JSON twin of the list.
2424
@@ -28,7 +28,9 @@ Not yet: Talk conversations and outside imports as rows (they wait for the trace
2828
2929 A share link is off until the repository's owner makes one (**Make a share link** on the trace; `POST /traces/<run id>/share`, same-origin). It is `/traces/shared/<secret>`, shown once (only its hash is kept, `src/trace/share.ts`), and read by anyone holding it with no sign-in: the steps and their raw lines, every one passed through the forge's redaction (`redactHeld`) on the way out, so a token the log's writer missed is `[redacted]`; no cost, no people. One live link a run: a new one ends the old, **Stop sharing** ends it, and the link is then the not-found any page gets. The gate is `src/actions/trace_share.ts`; pages `src/web/pages/trace_share.ts`, reader `src/trace/shared.ts`, which keeps the redacted trace for 30 seconds per link and allows one address 60 opens a minute (then a 429 with `Retry-After`).
3030
31 Terminal: on a run's trace (`src/tui/screens/trace.ts`) `c` reads it against the issue's newest other run, `s` makes the link (shown to copy; when one is live a second press confirms, as it ends the old one), `x` ends it; both are on the single-trace screen only, and a non-owner is told only the owner shares. MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `unshare`.
31 Terminal: on a run's trace (`src/tui/screens/trace.ts`) `c` reads it against the issue's newest other run, `s` makes the link (shown to copy; when one is live a second press confirms, as it ends the old one), `x` ends it; both are on the single-trace screen only, and a non-owner is told only the owner shares. In the trace list (`src/tui/screens/traces.ts`) `v` marks a run (a `*` before its row; the header says `marked n/2`; at most two, the older mark drops), `d` opens the comparison of the two marked, by run id, so a mark survives a search, a filter or a later page; two runs of different issues are refused.
32
33 MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `unshare`. `list` is `GET /api/v1/traces` for `repo`: one reader serves both (`readListAsk` and `listSeenTraces` in `src/trace/tree.ts`, gated as a run's log is), so the tool's body is the API's `{ items, next_cursor }` and it takes the API's filters `kind`, `model`, `outcome` (ok, failed, cancelled, stopped), `since`, `until`, `limit` and `cursor`; a malformed one is refused with the API's error code. `read` answers the trace as `rows` and `tree`, the very tree `GET /api/v1/traces/:id` answers (`treeOf` in `src/trace/tree.ts`, built from the one parse that gave the rows, behind the API's gate on the row; `null` where the run is not in the trace index). `compare` answers the API's table. A viewer who may not read a run gets from the tool what the API gives them: not found, an empty list.
3234
3335 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).
3436
src/http/api/traces.ts +19 −147
@@ -1,135 +1,40 @@
11 /**
22 * GET /api/v1/traces (#18021): the trace index newest first, a page at a time, as `{ items,
3 * next_cursor }`. The index (`trace/index_table.ts`) knows nothing of who may see a row, so this is
4 * where it is decided, by the rule that gates the run's log (`mayReadLogOfRun`): a run whose log
5 * the caller may not read is absent, never a hint it exists; a Talk turn is its person's alone.
6 * Only the index is read, never a raw log.
3 * next_cursor }`. Read and gated by `listSeenTraces` (`trace/tree.ts`), the MCP `trace` tool's
4 * `list` too: a run whose log the caller may not read is absent, never a hint it exists; a Talk
5 * turn is its person's alone. Only the index is read, never a raw log.
76 */
87
9 import { mayReadLogOfRun } from "../../actions/runs.ts";
10 import { cursorRefusal, limitRefusal, parseLimit } from "../../contract/page_query.ts";
11 import type { App } from "../../app.ts";
12 import { getRepo, getRepoById, type Repo } from "../../core/repos.ts";
8 import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts";
9 import { getRepoById } from "../../core/repos.ts";
1310 import { getRun } from "../../core/runs.ts";
1411 import { compareViews, sameIssue } from "../../trace/compare.ts";
1512 import { readTrace, type TraceView } from "../../trace/read.ts";
1613 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
17 import type { User } from "../../core/users.ts";
1814 import { importSession } from "../../trace/import.ts";
19 import { readRunLog, readRunTimes } from "../../runs/log.ts";
20 import { MAX_STEPS, parseRunLog } from "../../trace/run_log.ts";
21 import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "../../trace/index_table.ts";
15 import { LIST_PARAMETERS, listSeenTraces, readListAsk, TRACE_ID, traceTree } from "../../trace/tree.ts";
16 import { MAX_LIMIT } from "../../trace/index_table.ts";
2217 import type { Handler } from "../context.ts";
2318 import { BODY_CAPS, readBounded } from "../limits.ts";
2419 import { apiError, json, requireScope } from "../respond.ts";
2520 import type { Router } from "../router.ts";
2621
27 const ACCEPTED = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const;
28 const KINDS: readonly string[] = ["run", "talk", "review", "imported"];
29 const OUTCOMES: readonly string[] = ["ok", "failed", "cancelled", "stopped"];
30 /** An instant: a date, or a date and time with a zone. */
31 const INSTANT = /^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d{1,3})?)?(Z|[+-]\d\d:\d\d))?$/;
32 const WORD = /^[\w./:-]{1,100}$/;
33 /** A repository id no row has (a Talk turn's is empty, which a filter must not match). */
34 const NO_REPOSITORY = "-";
35 /** Rows looked at (in index pages) before a page is answered short with a cursor to go on from. */
36 const SCAN_PAGES = 10;
37
38 const instant = (raw: string): string | undefined => {
39 if (!INSTANT.test(raw)) return undefined;
40 const at = new Date(raw);
41 return Number.isNaN(at.getTime()) ? undefined : at.toISOString();
42 };
43
44 /** Whether `actor` may see this row: the answer for a repository is asked once per request. */
45 function seeing(app: App, actor: User): (row: TraceRow) => boolean {
46 const repos = new Map<string, Repo | undefined>();
47 return (row) => {
48 if (row.kind === "talk") {
49 const owner = app.db.query<{ user_id: string }, [string]>("SELECT user_id FROM conversation_run WHERE id = ?1").get(row.id);
50 return owner?.user_id === actor.id;
51 }
52 if (row.kind === "imported") return app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(row.id)?.owner === actor.id;
53 if (row.kind !== "run") return false;
54 if (!repos.has(row.repository)) repos.set(row.repository, getRepoById(app.db, row.repository));
55 const repo = repos.get(row.repository);
56 return repo !== undefined && mayReadLogOfRun(app, actor, repo, row.id);
57 };
58 }
59
6022 export const listTraces: Handler = (ctx) => {
6123 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
6224 const denied = requireScope(ctx, "ro");
6325 if (denied) return denied;
64 const actor = ctx.auth.user!;
65 const q = ctx.url.searchParams;
66 const unknown = [...new Set(q.keys())].filter((k) => !(ACCEPTED as readonly string[]).includes(k));
67 if (unknown.length > 0)
68 return json(
69 {
70 error: "unknown_parameter",
71 message: `this list does not read ${unknown.map((k) => JSON.stringify(k.slice(0, 40))).join(", ")}; it reads ${ACCEPTED.join(", ")}`,
72 accepted: ACCEPTED,
73 },
74 422,
75 );
76 const limit = parseLimit(q.get("limit"), MAX_LIMIT, DEFAULT_LIMIT);
77 if (limit === undefined) return limitRefusal(MAX_LIMIT);
78 const cursor = q.get("cursor");
79 if (cursor !== null && !TRACE_CURSOR.test(cursor)) return cursorRefusal();
80 const query: TraceQuery = {};
81 const kind = q.get("kind");
82 if (kind !== null) {
83 if (!KINDS.includes(kind)) return apiError("invalid_kind", 400, `kind is ${KINDS.join(", ")}`);
84 query.kind = kind as TraceKind;
26 const ask = readListAsk(ctx.app, ctx.url.searchParams);
27 if (!ask.ok) {
28 if (ask.error === "unknown_parameter") return json({ error: ask.error, message: ask.message, accepted: LIST_PARAMETERS }, 422);
29 if (ask.error === "invalid_limit") return limitRefusal(MAX_LIMIT);
30 if (ask.error === "invalid_cursor") return cursorRefusal();
31 return apiError(ask.error, 400, ask.message);
8532 }
86 const outcome = q.get("outcome");
87 if (outcome !== null) {
88 if (!OUTCOMES.includes(outcome)) return apiError("invalid_outcome", 400, `outcome is ${OUTCOMES.join(", ")}`);
89 query.outcome = outcome;
90 }
91 const model = q.get("model");
92 if (model !== null) {
93 if (!WORD.test(model)) return apiError("invalid_model", 400, "model is a model name of up to 100 characters");
94 query.model = model;
95 }
96 for (const name of ["since", "until"] as const) {
97 const raw = q.get(name);
98 if (raw === null) continue;
99 const at = instant(raw);
100 if (at === undefined) return apiError(`invalid_${name}`, 400, `${name} is a date or an ISO 8601 instant with a zone`);
101 query[name] = at;
102 }
103 const repository = q.get("repository");
104 if (repository !== null) {
105 if (!WORD.test(repository)) return apiError("invalid_repository", 400, "repository is a repository id or owner/name");
106 const [owner, name, ...more] = repository.split("/");
107 // An owner/name that names nothing matches no row, the same empty list a hidden one gives.
108 query.repository = name === undefined ? repository : more.length > 0 ? NO_REPOSITORY : (getRepo(ctx.app.db, owner!, name)?.id ?? NO_REPOSITORY);
109 }
110
111 const may = seeing(ctx.app, actor);
112 const items: TraceRow[] = [];
113 let next: string | null = null;
33 let body: ReturnType<typeof listSeenTraces> = { items: [], next_cursor: null };
11434 timePhase(ctx.request, "traces", () => {
115 let from = cursor ?? undefined;
116 for (let pages = 0; pages < SCAN_PAGES; pages += 1) {
117 const got = listTraceIndex(ctx.app.db, { ...query, ...(from === undefined ? {} : { cursor: from }), limit: MAX_LIMIT });
118 for (const row of got.rows) {
119 if (!may(row)) continue;
120 if (items.length === limit) {
121 next = cursorOf(items[items.length - 1]!);
122 return;
123 }
124 items.push(row);
125 }
126 if (got.next === undefined) return;
127 from = got.next;
128 }
129 // Looked at enough without filling the page: go on from where the look stopped.
130 next = from ?? null;
35 body = listSeenTraces(ctx.app, ctx.auth.user!, ask);
13136 });
132 return new Response(JSON.stringify({ items, next_cursor: next }), {
37 return new Response(JSON.stringify(body), {
13338 headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" },
13439 });
13540 };
@@ -151,9 +56,6 @@ export const importTrace: Handler = async (ctx) => {
15156 return json({ ...done.row, session: done.session, source: done.source, updated: done.updated }, done.updated ? 200 : 201);
15257 };
15358
154 /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */
155 const TRACE_ID = /^[0-9a-z]{1,40}$/;
156
15759 /**
15860 * GET /api/v1/traces/:id (#18022): the thread, its turns and their steps as one tree, rebuilt from
15961 * the raw log with `parseRunLog` (a Talk turn's log is a run log). A trace the caller may not see
@@ -164,41 +66,11 @@ export const readTraceTree: Handler = (ctx) => {
16466 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
16567 const denied = requireScope(ctx, "ro");
16668 if (denied) return denied;
167 const id = ctx.params.id ?? "";
168 const row = TRACE_ID.test(id) ? getTraceRow(ctx.app.db, id) : undefined;
169 if (row === undefined || !seeing(ctx.app, ctx.auth.user!)(row)) return apiError("not_found", 404, "no such trace");
170 let body: object = {};
69 let body: object | undefined;
17170 timePhase(ctx.request, "traces", () => {
172 const dataDir = ctx.app.config.dataDir;
173 const { lines, truncated } = readRunLog(dataDir, row.id);
174 const { trace, timed } = parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length));
175 const steps = trace.turns.reduce((n, t) => n + t.steps.length, 0);
176 body = {
177 id: row.id,
178 kind: row.kind,
179 repository: row.repository,
180 title: row.title,
181 model: row.model,
182 account: row.account,
183 tokensIn: row.tokensIn,
184 tokensCached: row.tokensCached,
185 tokensOut: row.tokensOut,
186 costUsd: row.costUsd,
187 outcome: row.outcome,
188 started: row.started,
189 ended: row.ended,
190 steps,
191 errors: row.errors,
192 timed,
193 truncated: truncated || steps >= MAX_STEPS,
194 turns: trace.turns.map((t) => ({
195 index: t.index,
196 prompt: t.prompt,
197 startMs: t.startMs,
198 steps: t.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, startMs: s.startMs, endMs: s.endMs, model: s.model ?? row.model, tokensIn: s.tokensIn, tokensCached: s.tokensCached, tokensOut: s.tokensOut, outcome: s.outcome })),
199 })),
200 };
71 body = traceTree(ctx.app, ctx.auth.user!, ctx.params.id ?? "");
20172 });
73 if (body === undefined) return apiError("not_found", 404, "no such trace");
20274 return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" } });
20375 };
20476
src/http/mcp/tools/trace.ts +21 −6
@@ -1,7 +1,7 @@
1 import { listRepoRuns } from "../../../actions/runs.ts";
21 import { sharedHref, shareRun, unshareRun } from "../../../actions/trace_share.ts";
32 import { compareRows, compareViews, readCompared } from "../../../trace/compare.ts";
43 import { readTrace, traceHref, traceRows } from "../../../trace/read.ts";
4 import { LIST_OUTCOMES, listSeenTraces, readListAsk, seenTraceRow, treeOf } from "../../../trace/tree.ts";
55 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
66
77 const ID = /^[0-9A-Za-z_-]{1,64}$/;
@@ -9,7 +9,7 @@ const ACTIONS = ["read", "list", "compare", "share", "unshare"] as const;
99
1010 export const tool: Tool = {
1111 name: "trace",
12 doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's recent agent runs, each with its `trace` address; `read` (default with `run`): the trace as lines, one a step, as the page and terminal show; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it",
12 doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's traces as `GET /api/v1/traces` answers them (`{ items, next_cursor }`), newest first, filtered by `kind`, `model`, `outcome`, `since`, `until`, a page of `limit` at a time (`cursor` is the last `next_cursor`); `read` (default with `run`): the trace as lines, one a step, as the page and terminal show, and `tree`, the API's trace tree; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it",
1313 description: "Read, list or compare crew-run traces; an owner makes or ends a redacted share link.",
1414 inputSchema: {
1515 type: "object",
@@ -18,6 +18,13 @@ export const tool: Tool = {
1818 action: { type: "string", enum: [...ACTIONS] },
1919 run: { type: "string" },
2020 with: { type: "string", description: "compare: the other run of the same issue" },
21 kind: { type: "string", enum: ["run", "talk", "review", "imported"], description: "list: only this kind" },
22 model: { type: "string", description: "list: only this model" },
23 outcome: { type: "string", enum: [...LIST_OUTCOMES], description: "list: only this outcome" },
24 since: { type: "string", description: "list: from this date or ISO 8601 instant" },
25 until: { type: "string", description: "list: before this date or ISO 8601 instant" },
26 limit: { type: "integer", description: "list: rows a page, 1 to 200" },
27 cursor: { type: "string", description: "list: the `next_cursor` of the last page" },
2128 },
2229 required: ["repo"],
2330 },
@@ -31,14 +38,22 @@ export const tool: Tool = {
3138 const action = args["action"] ?? (run === undefined ? "list" : "read");
3239 if (typeof action !== "string" || !ACTIONS.some((a) => a === action)) return bad("bad_action", `action is one of ${ACTIONS.join(", ")}`);
3340 if (action === "list") {
34 const runs = listRepoRuns(ctx.app, user, repo, { limit: 20, kind: "agent" });
35 if (!runs.ok) return bad("not_found", "no such app or repository (owner/name)");
36 return good({ runs: runs.value.map((r) => ({ id: r.id, state: r.state, trace: traceHref(r.id) })) });
41 // The API's own parameters, so the API's reader validates them and answers its own body.
42 const params = new URLSearchParams({ repository: `${repo.ownerName}/${repo.name}` });
43 for (const k of ["kind", "model", "outcome", "since", "until", "cursor", "limit"]) {
44 const v = args[k];
45 if (typeof v === "string" || typeof v === "number") params.set(k, String(v));
46 }
47 const ask = readListAsk(ctx.app, params);
outdated

This calls listTraces, while the API route calls listTraceIndex. Make one list reader serve both, so the tool really calls the API's function, and test that the bodies match.

48 return ask.ok ? good(listSeenTraces(ctx.app, user, ask)) : bad(ask.error, ask.message);
3749 }
3850 if (run === undefined) return bad("bad_run", "name the `run`");
3951 if (action === "read") {
4052 const view = await readTrace(ctx.app, user, repo, run);
41 return view === undefined ? bad("not_found", "no such run here") : good({ trace: traceHref(run), rows: traceRows(view) });
53 if (view === undefined) return bad("not_found", "no such run here");
54 // The tree from the log `readTrace` already parsed, behind the API's own gate on the row.
55 const row = seenTraceRow(ctx.app, user, run);
56 return good({ trace: traceHref(run), rows: traceRows(view), tree: row === undefined ? null : treeOf(row, view) });
4257 }
4358 if (action === "compare") {
4459 const other = args["with"];
src/trace/tree.ts added +170
@@ -0,0 +1,170 @@
1 /**
2 * One trace as a tree, the index as a list, and who may see an index row (#18022, #18085): the
3 * API's `GET /api/v1/traces` and `GET /api/v1/traces/:id` and the MCP `trace` tool's `list` and
4 * `read` call these readers, so they cannot drift. Gated by the rule that gates the run's log; a
5 * trace the viewer may not see is `undefined`, a row they may not see is absent.
6 */
7 import { mayReadLogOfRun } from "../actions/runs.ts";
8 import type { App } from "../app.ts";
9 import { parseLimit } from "../contract/page_query.ts";
10 import { getRepo, getRepoById, type Repo } from "../core/repos.ts";
11 import type { User } from "../core/users.ts";
12 import { readRunLog, readRunTimes } from "../runs/log.ts";
13 import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "./index_table.ts";
14 import type { Trace } from "./model.ts";
15 import { MAX_STEPS, parseRunLog } from "./run_log.ts";
16
17 /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */
18 export const TRACE_ID = /^[0-9a-z]{1,40}$/;
19
20 /** Whether `actor` may see this row: the answer for a repository is asked once per request. */
21 function seeing(app: App, actor: User): (row: TraceRow) => boolean {
22 const repos = new Map<string, Repo | undefined>();
23 return (row) => {
24 if (row.kind === "talk") {
25 const owner = app.db.query<{ user_id: string }, [string]>("SELECT user_id FROM conversation_run WHERE id = ?1").get(row.id);
26 return owner?.user_id === actor.id;
27 }
28 if (row.kind === "imported") return app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(row.id)?.owner === actor.id;
29 if (row.kind !== "run") return false;
30 if (!repos.has(row.repository)) repos.set(row.repository, getRepoById(app.db, row.repository));
31 const repo = repos.get(row.repository);
32 return repo !== undefined && mayReadLogOfRun(app, actor, repo, row.id);
33 };
34 }
35
36 /** The parameters the list reads; any other is refused by name. */
37 export const LIST_PARAMETERS = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const;
38 const KINDS: readonly string[] = ["run", "talk", "review", "imported"];
outdated

actor is never undefined for a caller. Take User and drop the extra checks.

39 export const LIST_OUTCOMES = ["ok", "failed", "cancelled", "stopped"] as const;
40 /** An instant: a date, or a date and time with a zone. */
41 const INSTANT = /^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d{1,3})?)?(Z|[+-]\d\d:\d\d))?$/;
42 const WORD = /^[\w./:-]{1,100}$/;
43 /** A repository id no row has (a Talk turn's is empty, which a filter must not match). */
44 const NO_REPOSITORY = "-";
45 /** Rows looked at (in index pages) before a page is answered short with a cursor to go on from. */
46 const SCAN_PAGES = 10;
47
48 /** What a list asks, read from its parameters; or the first one that is wrong. */
49 export type ListAsk = { ok: true; query: TraceQuery; cursor: string | undefined; limit: number } | { ok: false; error: string; message: string };
50
51 const instant = (raw: string): string | undefined => {
52 if (!INSTANT.test(raw)) return undefined;
53 const at = new Date(raw);
54 return Number.isNaN(at.getTime()) ? undefined : at.toISOString();
55 };
56
57 /** The list's parameters, validated: an unknown one, or a malformed value, is refused. */
58 export function readListAsk(app: App, q: URLSearchParams): ListAsk {
59 const unknown = [...new Set(q.keys())].filter((k) => !(LIST_PARAMETERS as readonly string[]).includes(k));
60 if (unknown.length > 0)
61 return { ok: false, error: "unknown_parameter", message: `this list does not read ${unknown.map((k) => JSON.stringify(k.slice(0, 40))).join(", ")}; it reads ${LIST_PARAMETERS.join(", ")}` };
62 const limit = parseLimit(q.get("limit"), MAX_LIMIT, DEFAULT_LIMIT);
63 if (limit === undefined) return { ok: false, error: "invalid_limit", message: `limit is a whole number from 1 to ${MAX_LIMIT}` };
64 const cursor = q.get("cursor");
65 if (cursor !== null && !TRACE_CURSOR.test(cursor)) return { ok: false, error: "invalid_cursor", message: "cursor is the next_cursor of a previous page" };
66 const query: TraceQuery = {};
67 const kind = q.get("kind");
68 if (kind !== null) {
69 if (!KINDS.includes(kind)) return { ok: false, error: "invalid_kind", message: `kind is ${KINDS.join(", ")}` };
70 query.kind = kind as TraceKind;
71 }
72 const outcome = q.get("outcome");
73 if (outcome !== null) {
74 if (!(LIST_OUTCOMES as readonly string[]).includes(outcome)) return { ok: false, error: "invalid_outcome", message: `outcome is ${LIST_OUTCOMES.join(", ")}` };
75 query.outcome = outcome;
76 }
77 const model = q.get("model");
78 if (model !== null) {
79 if (!WORD.test(model)) return { ok: false, error: "invalid_model", message: "model is a model name of up to 100 characters" };
80 query.model = model;
81 }
82 for (const name of ["since", "until"] as const) {
83 const raw = q.get(name);
84 if (raw === null) continue;
85 const at = instant(raw);
86 if (at === undefined) return { ok: false, error: `invalid_${name}`, message: `${name} is a date or an ISO 8601 instant with a zone` };
87 query[name] = at;
88 }
89 const repository = q.get("repository");
90 if (repository !== null) {
91 if (!WORD.test(repository)) return { ok: false, error: "invalid_repository", message: "repository is a repository id or owner/name" };
92 const [owner, name, ...more] = repository.split("/");
93 // An owner/name that names nothing matches no row, the same empty list a hidden one gives.
94 query.repository = name === undefined ? repository : more.length > 0 ? NO_REPOSITORY : (getRepo(app.db, owner!, name)?.id ?? NO_REPOSITORY);
95 }
96 return { ok: true, query, cursor: cursor ?? undefined, limit };
97 }
98
99 /**
100 * One page of the index `actor` may see, newest first, as `{ items, next_cursor }`. Only the index
101 * is read, never a raw log.
102 */
103 export function listSeenTraces(app: App, actor: User, ask: { query: TraceQuery; cursor: string | undefined; limit: number }): { items: TraceRow[]; next_cursor: string | null } {
104 const may = seeing(app, actor);
105 const items: TraceRow[] = [];
106 let from = ask.cursor;
107 for (let pages = 0; pages < SCAN_PAGES; pages += 1) {
108 const got = listTraceIndex(app.db, { ...ask.query, ...(from === undefined ? {} : { cursor: from }), limit: MAX_LIMIT });
109 for (const row of got.rows) {
110 if (!may(row)) continue;
111 if (items.length === ask.limit) return { items, next_cursor: cursorOf(items[items.length - 1]!) };
112 items.push(row);
113 }
114 if (got.next === undefined) return { items, next_cursor: null };
115 from = got.next;
116 }
117 // Looked at enough without filling the page: go on from where the look stopped.
118 return { items, next_cursor: from ?? null };
119 }
120
121 /** The row of a trace `actor` may see, or `undefined`: the gate the tree is behind. */
122 export function seenTraceRow(app: App, actor: User, id: string): TraceRow | undefined {
123 const row = TRACE_ID.test(id) ? getTraceRow(app.db, id) : undefined;
124 return row !== undefined && seeing(app, actor)(row) ? row : undefined;
125 }
126
127 /**
128 * The thread, its turns and their steps; `undefined` for an unknown id or one `actor` may not see.
129 */
130 export function traceTree(app: App, actor: User, id: string): object | undefined {
131 const row = seenTraceRow(app, actor, id);
132 if (row === undefined) return undefined;
133 const dataDir = app.config.dataDir;
134 const { lines, truncated } = readRunLog(dataDir, row.id);
135 return treeOf(row, { ...parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length)), truncated });
136 }
137
138 /**
139 * The tree of a row from a log already parsed: a caller that has read the trace (the MCP `read`)
140 * builds it from that one parse.
141 */
142 export function treeOf(row: TraceRow, parsed: { trace: Trace; timed: boolean; truncated: boolean }): object {
143 const { trace, timed, truncated } = parsed;
144 const steps = trace.turns.reduce((n, t) => n + t.steps.length, 0);
145 return {
146 id: row.id,
147 kind: row.kind,
148 repository: row.repository,
149 title: row.title,
150 model: row.model,
151 account: row.account,
152 tokensIn: row.tokensIn,
153 tokensCached: row.tokensCached,
154 tokensOut: row.tokensOut,
155 costUsd: row.costUsd,
156 outcome: row.outcome,
157 started: row.started,
158 ended: row.ended,
159 steps,
160 errors: row.errors,
161 timed,
162 truncated: truncated || steps >= MAX_STEPS,
163 turns: trace.turns.map((t) => ({
164 index: t.index,
165 prompt: t.prompt,
166 startMs: t.startMs,
167 steps: t.steps.map((s) => ({ id: s.id, kind: s.kind, name: s.name, line: s.line, startMs: s.startMs, endMs: s.endMs, model: s.model ?? row.model, tokensIn: s.tokensIn, tokensCached: s.tokensCached, tokensOut: s.tokensOut, outcome: s.outcome })),
168 })),
169 };
170 }
src/tui/screens/traces.ts +27 −5
@@ -3,12 +3,18 @@
33 * search (the same text as the page's `q`), `r` `m` `o` `p` cycle the repository, model, outcome
44 * and person facets through what the list offers (then back to any), `f` and `t` type the from and
55 * to days (YYYY-MM-DD), `c` clears them, `j`/`k` move, Enter opens the run's trace, `n` reads the
6 * next older page. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The
6 * next older page. `v` marks a row (two at most, the older mark drops) and `d` opens the two as
7 * a comparison (#18085): the trace screen's own, so the page's words; two runs of different issues
8 * are told so. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The
79 * lines are `traceLine`, the page's own row.
810 */
911 import { binding } from "../app/keys.ts";
1012 import type { Ctx, Screen } from "../app/app.ts";
1113 import { listTraces, OUTCOMES, readFilter, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts";
14 import { getRepoById } from "../../core/repos.ts";
15 import { getRun } from "../../core/runs.ts";
16 import { sameIssue } from "../../trace/compare.ts";
17 import { traceScreen } from "./trace.ts";
1218 import { Scroll, openOnWeb } from "./common.ts";
1319 import { style } from "../term/style.ts";
1420 import { truncate } from "../term/width.ts";
@@ -29,6 +35,8 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
2935 };
3036 let list: TraceList = listTraces(f.app, f.user, {});
3137 let at = 0;
38 // The runs marked to compare, oldest mark first.
39 let marked: string[] = [];
3240 let typing: "q" | "from" | "to" | undefined;
3341 const read = (): void => {
3442 list = listTraces(f.app, f.user, filter());
@@ -47,11 +55,12 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
4755 };
4856 const summary = (): string => {
4957 const on = Object.entries(facet).filter(([k]) => k !== "q" && facet[k as keyof typeof facet] !== undefined);
50 return on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`;
58 const held = marked.length === 0 ? "" : ` marked ${marked.length}/2 (*)`;
59 return `${on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`}${held}`;
5160 };
5261 return {
5362 title: "Traces",
54 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["n"], "older"), binding(["/"], "search"), binding(["r", "m", "o", "p"], "repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
63 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["r", "m", "o", "p"], "repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
5564 render(area, s) {
5665 const c = ctx.theme.c;
5766 s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : "To (YYYY-MM-DD)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w);
@@ -65,7 +74,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
6574 const r = list.rows[scroll.top + i];
6675 if (r === undefined) break;
6776 const on = scroll.top + i === at;
68 s.text(area.x, area.y + 2 + i, truncate(`${on ? "> " : " "}${traceLine(r).replace(/[\u0000-\u001f\u007f]/g, " ")}`, area.w), style(on ? c.fg : c.muted, c.bg), area.x + area.w);
77 s.text(area.x, area.y + 2 + i, truncate(`${on ? ">" : " "}${marked.includes(r.id) ? "*" : " "}${traceLine(r).replace(/[\u0000-\u001f\u007f]/g, " ")}`, area.w), style(on ? c.fg : c.muted, c.bg), area.x + area.w);
6978 }
7079 },
7180 key(e) {
@@ -87,7 +96,20 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
8796 else if (e.key === "m") cycle("model", list.facets.models);
8897 else if (e.key === "o") cycle("outcome", OUTCOMES);
8998 else if (e.key === "p") cycle("by", list.facets.people);
90 else if (e.key === "c") {
99 else if (e.key === "v") {
100 const r = list.rows[at];
101 if (r !== undefined) marked = marked.includes(r.id) ? marked.filter((id) => id !== r.id) : [...marked, r.id].slice(-2);
102 } else if (e.key === "d") {
103 // The marked runs by id, not through the visible rows: a filter or a page may have moved
104 // past them.
outdated

If marked holds an id that the current filter no longer lists, rows has an undefined entry and this toast tells the person to mark two runs when they already did. Clear marked when the list is re-read, or resolve the runs by id with getRun instead of through list.rows.

105 const [ra, rb] = marked.map((id) => getRun(f.app.db, id));
106 if (ra === undefined || rb === undefined) ctx.toast(marked.length < 2 ? "mark two runs of one issue with v" : "a marked run is gone: mark again", "attn");
107 else {
108 const repo = ra.repoId === rb.repoId ? getRepoById(f.app.db, ra.repoId) : undefined;
109 if (repo === undefined || !sameIssue(ra, rb)) ctx.toast("those two are not runs of one issue", "attn");
110 else ctx.push(traceScreen(f, ctx, repo, ra.id, rb.id));
111 }
112 } else if (e.key === "c") {
91113 for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet];
92114 before = undefined;
93115 read();
test/trace-share.test.ts +136 −1
@@ -17,7 +17,9 @@ import { createUser } from "../src/core/users.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
1818 import { appendRunLog, flushRunLogs, runLogPath } from "../src/runs/log.ts";
1919 import { compareRows, compareViews, readCompared } from "../src/trace/compare.ts";
20 import { indexRun } from "../src/trace/index_table.ts";
2021 import { readTrace } from "../src/trace/read.ts";
22 import { listTraces } from "../src/trace/list.ts";
2123 import { isShared, isShareToken } from "../src/trace/share.ts";
2224 import { readShared, sharedTurn } from "../src/trace/shared.ts";
2325 import { traceScreen } from "../src/tui/screens/trace.ts";
@@ -47,7 +49,7 @@ function aRun(issueId: string | undefined, lines: string[], seconds: number, usd
4749 finishRun(app.db, run.id, { state: "ok", summary: "done" });
4850 const start = Date.parse("2026-12-01T10:00:00Z");
4951 app.db
50 .query("UPDATE run SET started_at = ?2, finished_at = ?3, cost_usd = ?4, model = ?5 WHERE id = ?1")
52 .query("UPDATE run SET state = 'ok', started_at = ?2, finished_at = ?3, cost_usd = ?4, model = ?5 WHERE id = ?1")
5153 .run(run.id, new Date(start).toISOString(), new Date(start + seconds * 1000).toISOString(), usd, model);
5254 return run.id;
5355 }
@@ -73,6 +75,7 @@ beforeAll(async () => {
7375 other = aRun(issue.value.id, ["→ Read README.md"], 5, 0.02, "leaky");
7476 appendFileSync(runLogPath(dir, other), `→ Bash curl -H "Authorization: token ${PLANTED}" https://example.com\n`);
7577 flushRunLogs();
78 for (const id of [packed, explored, elsewhere, other]) indexRun(app.db, dir, id);
7679 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
7780 method: "POST",
7881 headers: { "content-type": "application/json" },
@@ -225,3 +228,135 @@ test("a shared trace is read once for repeats, and one address is bounded", asyn
225228 expect(refused).toBeGreaterThan(0);
226229 expect(sharedTurn(app, "203.0.113.10").allowed).toBe(true);
227230 });
231
232 /** One call of the MCP `trace` tool on alice/notes; `data` is undefined when the tool refused. */
233 async function mcpTrace(args: Record<string, unknown>, token = bearer) {
234 const res = await fetch(`${servers.url}/mcp`, {
235 method: "POST",
236 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
237 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "trace", arguments: { repo: "alice/notes", ...args } } }),
238 });
239 const body = (await res.json()) as { result?: { isError?: boolean; content: { text: string }[] } };
240 const r = body.result;
241 const error = r === undefined || r.isError === true;
242 return { error, data: error ? undefined : JSON.parse(r!.content[0]!.text) };
243 }
outdated

These assertions would pass with the current MCP list, which is not the API list. Compare list.data.runs with GET /api/v1/traces for the same filters, and read with GET /api/v1/traces/:id. Add a guest or non-member case that gets nothing.

244
245 // #18085: the MCP `trace` tool answers what the API does, and the terminal list marks two runs.
246 test("MCP trace compare, read and list agree with the API", async () => {
247 const callTrace = mcpTrace;
248 const api = (await (await get(`/api/v1/traces/compare?a=${packed}&b=${explored}`)).json()) as { rows: unknown; timeDiffMs: number; costDiffUsd: number };
249 const cmp = await callTrace({ action: "compare", run: packed, with: explored });
250 expect(cmp.data.table).toEqual(api.rows);
251 expect(cmp.data.timeDiffMs).toBe(api.timeDiffMs);
252 expect(cmp.data.costDiffUsd).toBe(api.costDiffUsd);
253 expect((await callTrace({ action: "compare", run: packed, with: elsewhere })).error).toBe(true);
254
255 // read: the MCP tree is the API's tree, byte for byte.
256 const apiTree = await (await get(`/api/v1/traces/${explored}`)).json();
257 const read = await callTrace({ action: "read", run: explored });
258 expect(read.data.rows.length).toBeGreaterThan(0);
259 expect(read.data.tree).toEqual(apiTree);
260 expect(read.data.tree.id).toBe(explored);
261
262 // list: the API's reader answers both, so the bodies are one body.
263 const apiBody = (q: string) => get(`/api/v1/traces?repository=alice/notes${q}`).then((r) => r.json());
264 const ids = (l: { data: { items: { id: string }[] } }) => l.data.items.map((r) => r.id);
265 const all = await callTrace({ action: "list" });
266 expect(all.data).toEqual(await apiBody(""));
267 expect(ids(all)).toContain(packed);
268 const one = await callTrace({ action: "list", kind: "run", model: "packed" });
269 expect(ids(one)).toEqual([packed]);
270 expect(one.data).toEqual(await apiBody("&kind=run&model=packed"));
271 expect(ids(await callTrace({ action: "list", model: "explored", outcome: "failed" }))).toEqual([]);
272 const first = await callTrace({ action: "list", limit: 1 });
273 expect(first.data).toEqual(await apiBody("&limit=1"));
274 const second = await callTrace({ action: "list", limit: 1, cursor: first.data.next_cursor });
275 expect(second.data).toEqual(await apiBody(`&limit=1&cursor=${encodeURIComponent(first.data.next_cursor)}`));
276 expect(ids(second)).not.toEqual(ids(first));
277 // A malformed value is refused, as the API refuses it.
278 expect((await callTrace({ action: "list", since: "yesterday" })).error).toBe(true);
279 expect((await get("/api/v1/traces?repository=alice/notes&since=yesterday")).status).toBe(400);
280 });
281
282 test("MCP trace gives a stranger what the API gives them: nothing", async () => {
283 const callAs = async (token: string, args: Record<string, unknown>) => (await mcpTrace(args, token)).data;
284 const eve = await createUser(app.db, { origin: "seed", trusted: true, username: "eve", email: "[email protected]", password: "correct-horse-battery" });
285 if (!eve.ok) throw new Error(eve.error);
286 const token = createToken(app.db, eve.value.id, "t", "rw").token;
287 // The API: the run's log is not hers, so it is a 404 and a compare is a 404.
288 const apiRead = await get(`/api/v1/traces/${explored}`, token);
289 const apiCompare = await get(`/api/v1/traces/compare?a=${packed}&b=${explored}`, token);
290 const mine = (await (await get("/api/v1/traces?repository=alice/notes", token)).json()) as { items: unknown[] };
291 expect(apiRead.status).toBe(404);
292 expect(apiCompare.status).toBe(404);
293 const readOut = await callAs(token, { action: "read", run: explored });
294 const cmpOut = await callAs(token, { action: "compare", run: packed, with: explored });
295 const listOut = await callAs(token, { action: "list" });
296 expect(readOut).toBeUndefined();
297 expect(cmpOut).toBeUndefined();
298 expect(listOut).toEqual({ items: [], next_cursor: null });
299 expect(mine.items).toEqual([]);
300 // No sign-in at all: no tool answer, and the list is empty for no one.
301 const anon = await fetch(`${servers.url}/mcp`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "trace", arguments: { repo: "alice/notes", action: "list" } } }) });
302 expect(await anon.text()).not.toContain(packed);
303 });
304
305 test("terminal: two marked rows open the comparison, two of different issues do not", async () => {
306 const { entry } = await import("../src/tui/screens/traces.ts");
307 const toasts: string[] = [];
308 const pushed: { title: string }[] = [];
309 const ctx = { theme: theme("dark"), invalidate() {}, toast: (t: string) => toasts.push(t), push: (s: { title: string }) => pushed.push(s) } as unknown as Ctx;
310 const f = { app, db: app.db, user: alice } as unknown as Session;
311 entry.run(f, ctx);
312 const list = pushed.pop()! as unknown as { key: (e: unknown) => boolean };
313 const key = (k: string) => list.key({ type: "key", key: k, ctrl: false, alt: false, shift: false });
314 const ids = listTraces(app, alice, {}).rows.map((r) => r.id);
315 const mark = (id: string) => {
316 for (let i = 0; i < ids.length; i++) key("k");
317 for (let i = 0; i < ids.indexOf(id); i++) key("j");
318 key("v");
319 };
320 key("d");
321 expect(toasts.at(-1)).toContain("mark two");
322 mark(packed);
323 mark(elsewhere);
324 key("d");
325 expect(toasts.at(-1)).toContain("not runs of one issue");
326 expect(pushed.length).toBe(0);
327 mark(elsewhere); // unmarks it
328 mark(explored);
329 key("d");
330 expect(pushed.length).toBe(1);
331 expect(pushed[0]!.title).toBe("Trace");
332 const screen = pushed[0] as unknown as { load: (s: AbortSignal) => Promise<void> };
333 await screen.load(new AbortController().signal);
334 });
335
336 test("terminal: a mark held past a filter still opens the comparison, and the header counts the marks", async () => {
337 const { entry } = await import("../src/tui/screens/traces.ts");
338 const toasts: string[] = [];
339 const pushed: unknown[] = [];
340 const ctx = { theme: theme("dark"), invalidate() {}, toast: (t: string) => toasts.push(t), push: (s: unknown) => pushed.push(s) } as unknown as Ctx;
341 entry.run({ app, db: app.db, user: alice } as unknown as Session, ctx);
342 const list = pushed.pop()! as unknown as { key: (e: unknown) => boolean; render: (a: unknown, s: unknown) => void };
343 const key = (k: string) => list.key({ type: "key", key: k, ctrl: false, alt: false, shift: false });
344 const order = listTraces(app, alice, {}).rows.map((r) => r.id);
345 const mark = (id: string) => {
346 for (let i = 0; i < order.length; i++) key("k");
347 for (let i = 0; i < order.indexOf(id); i++) key("j");
348 key("v");
349 };
350 mark(packed);
351 mark(explored);
352 // Search for words no run has: both marks are off the visible rows.
353 key("/");
354 for (const ch of "zzzznothing") key(ch);
355 key("enter");
356 const lines: string[] = [];
357 list.render({ x: 0, y: 0, w: 120, h: 10 }, { text: (_x: number, _y: number, t: string) => lines.push(t), line() {} });
358 expect(lines[0]).toContain("marked 2/2");
359 key("d");
360 expect(toasts.at(-1) ?? "").not.toContain("mark two");
361 expect(pushed.length).toBe(1);
362 });

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

Keyboard shortcuts

Docs