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

/traces narrows by the tool a run used and the file it touched, on the page, the API and the terminal #18373

opened this

Merged 4h 33m ago, live in production

torque/forge:torque/18368-traces-narrows-by-the-tool-a-run-used-an → main 0 commits fork 2 threads · 2 unresolved

  • Merged. torque/18368-traces-narrows-by-the-tool-a-run-used-an was merged into main as ee241ef.

Review

Sign in to review this change.
17 files changed +498 −23
docs/features/traces.md +6
@@ -22,6 +22,12 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu
2222
2323 Talk turns and imported sessions are rows too (#18356): the viewer's own, read from the trace index behind the API's gate (`listSeenTraces`: a Talk turn to its person, an imported session to its owner, no one else), merged by time with the crew runs. The `kind` facet (`run`, `talk`, `imported`; the Kind select under Filters, `i` in the terminal) narrows to one; a malformed one is dropped. A Talk row opens `/traces/<id>`; an imported row is plain text until its page lands. The repository facet leaves out Talk and imported rows (they have no repository). Older pages carry both places in one opaque `before`; one this list did not write starts the list over. Not yet: archived turns in the search, and a JSON twin of the list.
2424
25 ## Narrow by tool and file (#18368)
26
27 `tool` and `file` are two more facets of `/traces` (the Tool and File fields under Filters), of `GET /api/v1/traces` and of the MCP `trace` tool's `list`: `/traces?tool=Bash` is every run that used Bash, `/traces?file=src/http/respond.ts` every run that edited or read that path (Edit, Write, MultiEdit, NotebookEdit and Read steps name files; the path is whole and exact, relative to the session's directory when it has one, and `./` is dropped). A malformed value (a tool name is letters, digits and `_.:-`; a path has no control character or `..` step, 300 characters at most) is dropped on the page and is a 400 `invalid_tool` or `invalid_file` in the API. Terminal: `u` types the tool, `e` the file (`src/tui/screens/traces.ts`).
28
29 They read the index, never a log on the list path: when a trace is written or imported, its distinct tool names (40 at most) and its file paths (50 at most, edits before reads) go to `trace_touch` (`src/trace/touched.ts`). Traces indexed before that are filled by a background pass at boot, 20 at a time (`src/trace/touched_fill.ts`), so until it ends a tool or file search can miss them: the page and the terminal say how many traces the viewer may open are not indexed yet, and the API adds `unindexed` to the page. The count is gated as the list is (`src/trace/touched_count.ts`); an unindexed row is never shown as a wrong match, only absent. A run that has not been indexed at all (it ended, but the one-time backfill has not reached it) is not counted. The gate is the list's: a viewer finds only the traces they may open.
30
2531 ## Compare two runs, and share one (#17995)
2632
2733 `/traces/<run id>/compare/<other run id>` sets two runs of one issue side by side: steps, failed steps, time (each run's own clock, started to finished), tokens (said "not recorded": a run's log holds none), cost (for those who may see the owner's facts) and outcome, with B − A beside each. Runs of two issues, or one the viewer cannot read, are the not-found a missing run gets. A trace page lists the issue's other runs to compare with. Reader: `src/trace/compare.ts` (`compareViews`, `compareRows`); page: `src/web/pages/trace_compare.ts`. API: `GET /api/v1/traces/compare?a=<run id>&b=<run id>` (#18083) answers the same rows with `timeDiffMs` and `costDiffUsd` (B − A); each run is read through its own gate (one the caller may not read is a 404), and two runs that are not two runs of one issue are a 422 `not_one_issue`.
src/contract/openapi/routes/getApiV1Traces.ts +3 −3
@@ -8,10 +8,10 @@ export const route: Route = {
88 path: "/api/v1/traces",
99 summary: "List traces newest first as `{ items, next_cursor }`",
1010 detail:
11 "List the trace index, newest first (started, then id), as `{ items, next_cursor }` of { id, kind (run, talk, review, imported), repository (an id; empty for a Talk turn), title, model, account, steps, errors, tokensIn, tokensCached, tokensOut, costUsd, outcome (ok, failed, cancelled, stopped), started, ended }; filters repository (an id or owner/name), kind, model, outcome, since (started at or after) and until (started before), the last two a date or an ISO 8601 instant with a zone; limit 1 to 200 (default 50) and a cursor (the next_cursor of the page before). An imported trace is listed to the account that sent it alone. A trace the caller could not read the log of is absent, never a hint it exists: a run is listed to those who may read its log, a Talk turn to its person alone; only the index is read, never a log. A bad filter value is a 400 (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until); a bad limit or cursor, or a parameter this list does not read, is a 422",
11 "List the trace index, newest first (started, then id), as `{ items, next_cursor }` of { id, kind (run, talk, review, imported), repository (an id; empty for a Talk turn), title, model, account, steps, errors, tokensIn, tokensCached, tokensOut, costUsd, outcome (ok, failed, cancelled, stopped), started, ended }; filters repository (an id or owner/name), kind, model, outcome, since (started at or after) and until (started before), the last two a date or an ISO 8601 instant with a zone; tool (a tool the trace used, such as Edit) and file (a path it touched, as the log wrote it), read from the index alone: with either, the page also says `unindexed`, how many traces the caller may open have no tools and files indexed yet; limit 1 to 200 (default 50) and a cursor (the next_cursor of the page before). An imported trace is listed to the account that sent it alone. A trace the caller could not read the log of is absent, never a hint it exists: a run is listed to those who may read its log, a Talk turn to its person alone; only the index is read, never a log. A bad filter value is a 400 (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until, invalid_tool, invalid_file); a bad limit or cursor, or a parameter this list does not read, is a 422",
1212 auth: true,
1313 role: "member",
14 query: { repository: "string", kind: "string", model: "string", outcome: "string", since: "string", until: "string", cursor: "string", limit: limitTo(200) },
14 query: { repository: "string", kind: "string", model: "string", outcome: "string", tool: "string", file: "string", since: "string", until: "string", cursor: "string", limit: limitTo(200) },
1515 itemKeys: ITEM_KEYS,
1616 response: page(
1717 obj({
@@ -20,6 +20,6 @@ export const route: Route = {
2020 outcome: str, started: str, ended: str,
2121 }),
2222 ),
23 errorStatus: { 400: "a filter value that is not one it reads (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until)", 422: "a bad limit or cursor, or a parameter this list does not read" },
23 errorStatus: { 400: "a filter value that is not one it reads (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until, invalid_tool, invalid_file)", 422: "a bad limit or cursor, or a parameter this list does not read" },
2424 refuses: [401],
2525 };
src/core/migration-pins/20261206073718-trace-touch.pin added +1
@@ -0,0 +1,1 @@
1 952431a1012511a0bbf00f6befbce3fc97a2790c5f708a6fd9580ccb3fb4fe58
src/core/migrations/20261206073718-trace-touch.ts added +17
@@ -0,0 +1,17 @@
1 // What a trace used and touched (#18368): the distinct tool names and at most 50 file paths of each
2 // trace, so `/traces` can narrow to "the runs that edited src/http/respond.ts" from the index
3 // without opening a log. `trace_touch` is read by `(kind, value)` (`trace_touch` primary key), the
4 // rows of one trace by `trace_touch_by_trace`; `trace_index.touched` is 1 once a row's touches are
5 // written, so an older row (0) is told apart from a trace that touched nothing, and a partial index
6 // keeps the count of rows still to fill a short walk. Additive.
7 export default `
8 ALTER TABLE trace_index ADD COLUMN touched INTEGER NOT NULL DEFAULT 0;
9 CREATE INDEX trace_index_untouched ON trace_index(repository) WHERE touched = 0;
10 CREATE TABLE trace_touch (
11 kind TEXT NOT NULL CHECK (kind IN ('tool','file')),
12 value TEXT NOT NULL,
13 trace_id TEXT NOT NULL,
14 PRIMARY KEY (kind, value, trace_id)
15 ) WITHOUT ROWID;
16 CREATE INDEX trace_touch_by_trace ON trace_touch(trace_id);
17 `;
src/http/mcp/tools/trace.ts +4 −2
@@ -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 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",
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`, `tool`, `file`, `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",
@@ -21,6 +21,8 @@ export const tool: Tool = {
2121 kind: { type: "string", enum: ["run", "talk", "review", "imported"], description: "list: only this kind" },
2222 model: { type: "string", description: "list: only this model" },
2323 outcome: { type: "string", enum: [...LIST_OUTCOMES], description: "list: only this outcome" },
24 tool: { type: "string", description: "list: only traces that used this tool, such as Edit" },
25 file: { type: "string", description: "list: only traces that touched this path" },
2426 since: { type: "string", description: "list: from this date or ISO 8601 instant" },
2527 until: { type: "string", description: "list: before this date or ISO 8601 instant" },
2628 limit: { type: "integer", description: "list: rows a page, 1 to 200" },
@@ -40,7 +42,7 @@ export const tool: Tool = {
4042 if (action === "list") {
4143 // The API's own parameters, so the API's reader validates them and answers its own body.
4244 const params = new URLSearchParams({ repository: `${repo.ownerName}/${repo.name}` });
43 for (const k of ["kind", "model", "outcome", "since", "until", "cursor", "limit"]) {
45 for (const k of ["kind", "model", "outcome", "tool", "file", "since", "until", "cursor", "limit"]) {
4446 const v = args[k];
4547 if (typeof v === "string" || typeof v === "number") params.set(k, String(v));
4648 }
src/main.ts +5 −1
@@ -45,6 +45,7 @@ import { keepSandboxing } from "./spawn/move_cell.ts";
4545 import { applyBootDefaults, stopCellChildren } from "./spawn/cell.ts";
4646 import { backfillChildren } from "./spawn/forge_code_backfill.ts";
4747 import { backfillTraceIndex } from "./trace/index_table.ts";
48 import { fillTouchesInBatches } from "./trace/touched_fill.ts";
4849 import { firstBoot } from "./spawn/first-boot.ts";
4950 import { previewIdentityKey } from "./spawn/preview-owner.ts";
5051 import { PREVIEW_ADMIN } from "./spawn/preview-looks.ts";
@@ -674,8 +675,11 @@ void backfillChildren(app)
674675 // yield (#18020).
675676 if (!readOnly)
676677 void backfillTraceIndex(app.db, app.config.dataDir)
677 .then((n) => {
678 .then(async (n) => {
678679 if (n > 0) app.log.info("trace index backfill", { rows: n });
680 // The tools and files of the rows indexed before they were kept (#18368).
681 const filled = await fillTouchesInBatches(app.db, app.config.dataDir);
682 if (filled > 0) app.log.info("trace touches backfill", { rows: filled });
679683 })
680684 .catch((error) => app.log.error("could not backfill the trace index", { error: String(error) }));
681685 // A forge still draining on this database keeps writing for its gates and
src/trace/import.ts +2
@@ -13,6 +13,7 @@ import { promisify } from "node:util";
1313 import { gunzipSync, gzip } from "node:zlib";
1414 import { ADAPTERS } from "./import_adapter.ts";
1515 import { stepsOf, totalsOf } from "./model.ts";
16 import { putTouches, touchesOf } from "./touched.ts";
1617 import { putTraceRow, type TraceRow } from "./index_table.ts";
1718
1819 const gzipped = promisify(gzip);
@@ -121,6 +122,7 @@ export async function importSession(db: Database, dataDir: string, owner: string
121122 };
122123 const updated = db.query("SELECT 1 FROM trace_index WHERE id = ?1").get(id) !== null;
123124 putTraceRow(db, row, owner);
125 putTouches(db, id, touchesOf(trace));
124126 return { ok: true, row, session: trace.id, source: adapter.source, updated };
125127 }
126128 return { ok: false, reason: refused };
src/trace/index_table.ts +8
@@ -17,6 +17,7 @@ import { background } from "../perf/jobs.ts";
1717 import { readRunLog, readRunTimes } from "../runs/log.ts";
1818 import { totalsOf } from "./model.ts";
1919 import { parseRunLog } from "./run_log.ts";
20 import { putTouches, touchClause, touchesOf } from "./touched.ts";
2021
2122 export type TraceKind = "run" | "talk" | "review" | "imported";
2223
@@ -88,6 +89,7 @@ function write(db: Database, dataDir: string, raw: Raw): void {
8889 started: raw.started,
8990 ended: raw.ended,
9091 });
92 putTouches(db, raw.id, touchesOf(trace));
9193 }
9294
9395 /**
@@ -277,6 +279,10 @@ export interface TraceQuery {
277279 kind?: TraceKind | undefined;
278280 model?: string | undefined;
279281 outcome?: string | undefined;
282 /** Used this tool (`trace_touch`); a row not yet filled never matches. */
283 tool?: string | undefined;
284 /** Touched this file. */
285 file?: string | undefined;
280286 /** Started at or after this ISO instant. */
281287 since?: string | undefined;
282288 /** Started before this ISO instant. */
@@ -345,6 +351,8 @@ export function listTraceIndex(db: Database, query: TraceQuery = {}): TracePage
345351 else add("kind = ?", query.kind);
346352 add("model = ?", query.model);
347353 add("outcome = ?", query.outcome);
354 if (query.tool !== undefined) (args.push(query.tool), where.push(touchClause("trace_index", "tool", `?${args.length}`)));
355 if (query.file !== undefined) (args.push(query.file), where.push(touchClause("trace_index", "file", `?${args.length}`)));
348356 add("started >= ?", query.since);
349357 add("started < ?", query.until);
350358 const at = query.cursor === undefined ? null : TRACE_CURSOR.exec(query.cursor);
src/trace/list.ts +25 −4
@@ -11,6 +11,8 @@ import { canRead, canSeeOwnerFacts, getRepo, getRepoById, type Repo } from "../c
1111 import type { User } from "../core/users.ts";
1212 import { cursorOf, TRACE_CURSOR, type TraceQuery } from "./index_table.ts";
1313 import { traceHref } from "./read.ts";
14 import { cleanPath, TOOL_NAME, touchClause } from "./touched.ts";
15 import { unindexedFor } from "./touched_count.ts";
1416 import { LIST_OUTCOMES, listSeenTraces } from "./tree.ts";
1517
1618 export const OUTCOMES = ["ok", "failed", "cancelled", "running", "queued"] as const;
@@ -28,6 +30,10 @@ export interface TraceFilter {
2830 readonly from?: string;
2931 readonly to?: string;
3032 readonly by?: string;
33 /** Used this tool (`Edit`, `Bash`): read from the trace index. */
34 readonly tool?: string;
35 /** Touched this file (a path as the log wrote it). */
36 readonly file?: string;
3137 readonly q?: string;
3238 readonly before?: string;
3339 }
@@ -60,6 +66,11 @@ export interface TraceList {
6066 /** The cursor of the next page, when there is one. */
6167 readonly next: string | undefined;
6268 readonly facets: TraceFacets;
69 /**
70 * With a tool or file facet: the traces the viewer may open that the index has no tools and files
71 * for yet.
72 */
73 readonly unindexed: number;
6374 }
6475
6576 export const PAGE = 50;
@@ -88,6 +99,8 @@ export function readFilter(params: URLSearchParams): TraceFilter {
8899 const before = one("before", 256);
89100 const kind = one("kind", 10);
90101 const q = one("q", 80);
102 const tool = one("tool", 64);
103 const file = one("file", 300);
91104 const out: { -readonly [K in keyof TraceFilter]: TraceFilter[K] } = {};
92105 if (repo !== undefined && /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}\/[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}$/.test(repo)) out.repo = repo;
93106 if (outcome !== undefined && (OUTCOMES as readonly string[]).includes(outcome)) out.outcome = outcome as TraceOutcome;
@@ -98,6 +111,9 @@ export function readFilter(params: URLSearchParams): TraceFilter {
98111 if (model !== undefined) out.model = model;
99112 if (before !== undefined && /^(?:[0-9A-Za-z_-]{1,64}|m\.[0-9A-Za-z_-]{1,200})$/.test(before)) out.before = before;
100113 if (q !== undefined) out.q = q;
114 if (tool !== undefined && TOOL_NAME.test(tool)) out.tool = tool;
115 const path = file === undefined ? undefined : cleanPath(file);
116 if (path !== undefined) out.file = path;
101117 return out;
102118 }
103119
@@ -105,7 +121,7 @@ export function readFilter(params: URLSearchParams): TraceFilter {
105121 export function filterQuery(f: TraceFilter, over: Partial<Record<keyof TraceFilter, string | undefined>> = {}): string {
106122 const merged: Record<string, string | undefined> = { ...f, ...over };
107123 const p = new URLSearchParams();
108 for (const k of ["q", "kind", "repo", "model", "outcome", "by", "from", "to", "before"]) {
124 for (const k of ["q", "kind", "repo", "model", "outcome", "by", "tool", "file", "from", "to", "before"]) {
109125 const v = merged[k];
110126 if (v !== undefined && v !== "") p.set(k, v);
111127 }
@@ -136,6 +152,8 @@ function where(f: TraceFilter, repoId: string | undefined, actorName: string | u
136152 if (f.from !== undefined) sql += ` AND r.created_at >= ${add(`${f.from}T00:00:00`)}`;
137153 if (f.to !== undefined) sql += ` AND r.created_at < ${add(`${nextDay(f.to)}T00:00:00`)}`;
138154 if (actorName !== undefined) sql += ` AND u.username = ${add(actorName)}`;
155 if (f.tool !== undefined) sql += ` AND ${touchClause("r", "tool", add(f.tool))}`;
156 if (f.file !== undefined) sql += ` AND ${touchClause("r", "file", add(f.file))}`;
139157 if (f.q !== undefined) {
140158 const like = add(likeOf(f.q));
141159 sql += ` AND (COALESCE(i.title, '') LIKE ${like} ESCAPE '\\' OR r.summary LIKE ${like} ESCAPE '\\')`;
@@ -244,6 +262,8 @@ function personal(app: App, actor: User | undefined, f: TraceFilter, cursor: str
244262 if (f.kind !== undefined) query.kind = f.kind;
245263 if (f.model !== undefined) query.model = f.model;
246264 if (f.outcome !== undefined) query.outcome = f.outcome;
265 if (f.tool !== undefined) query.tool = f.tool;
266 if (f.file !== undefined) query.file = f.file;
247267 if (f.from !== undefined) query.since = `${f.from}T00:00:00.000Z`;
248268 if (f.to !== undefined) query.until = `${nextDay(f.to)}T00:00:00.000Z`;
249269 const q = f.q?.toLowerCase();
@@ -297,12 +317,13 @@ function readCursor(before: string | undefined): { runs: string | undefined; min
297317 export function listTraces(app: App, actor: User | undefined, f: TraceFilter): TraceList {
298318 const cur = readCursor(f.before);
299319 const facets = facetsOf(app, actor);
320 const unindexed = f.tool === undefined && f.file === undefined ? 0 : unindexedFor(app, actor);
300321 const runsOn = f.kind === undefined || f.kind === "run";
301322 const mineOn = f.kind !== "run" && actor !== undefined && f.repo === undefined;
302323 const runs = cur.runs === NOT_MORE || !runsOn ? { rows: [], next: undefined } : crewRuns(app, actor, f, cur.runs);
303 if (!mineOn) return { rows: runs.rows, next: runs.next, facets };
324 if (!mineOn) return { rows: runs.rows, next: runs.next, facets, unindexed };
304325 const mine = cur.mine === NOT_MORE ? { rows: [], next: undefined } : personal(app, actor, f, cur.mine);
305 if (!runsOn) return { rows: mine.rows.slice(0, PAGE), next: resume(mine, Math.min(PAGE, mine.rows.length), cur.mine), facets };
326 if (!runsOn) return { rows: mine.rows.slice(0, PAGE), next: resume(mine, Math.min(PAGE, mine.rows.length), cur.mine), facets, unindexed };
306327 const rows: TraceRow[] = [];
307328 let i = 0;
308329 let j = 0;
@@ -315,7 +336,7 @@ export function listTraces(app: App, actor: User | undefined, f: TraceFilter): T
315336 const a = resume(runs, i, cur.runs);
316337 const b = resume(mine, j, cur.mine);
317338 const next = a === undefined && b === undefined ? undefined : `m.${Buffer.from(`${a === undefined ? NOT_MORE : a}~${b === undefined ? NOT_MORE : b}`).toString("base64url")}`;
318 return { rows, next, facets };
339 return { rows, next, facets, unindexed };
319340 }
320341
321342 /** Where a stream resumes after `used` of its rows were shown; undefined when nothing is left. */
src/trace/touched.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * What a trace used and touched (#18368): the distinct tool names and the file paths of its steps,
3 * kept in `trace_touch` when the trace is indexed so the list narrows by them without opening a
4 * log. Plain data in (a parsed `Trace`), plain data out. A path is the one the tool's step line
5 * names (`Edit src/a.ts +3 −1` → `src/a.ts`), relative to the session's directory when it has one;
6 * tool names are as the log wrote them. At most `MAX_TOOLS` names and `MAX_PATHS` paths a trace,
7 * edits before reads, so the table's growth is bounded by the number of traces.
8 */
9 import type { Database } from "bun:sqlite";
10 import type { Trace } from "./model.ts";
11 import { stepsOf } from "./model.ts";
12
13 export const MAX_TOOLS = 40;
14 export const MAX_PATHS = 50;
15 /** Tools whose step line names a file, and whether they change it. */
16 const FILE_TOOLS: Readonly<Record<string, boolean>> = { Edit: true, Write: true, MultiEdit: true, NotebookEdit: true, Read: false };
17
18 /** A tool name the facet accepts: what a log writes, bounded. */
19 export const TOOL_NAME = /^[A-Za-z0-9_.:-]{1,64}$/;
20 /** A path as kept: one line, no `..` step, at most 300 characters. */
21 export function cleanPath(raw: string): string | undefined {
22 const p = raw.trim().replace(/^(\.\/)+/, "");
23 if (p === "" || p.length > 300 || /[\u0000-\u001f\u007f]/.test(p) || p.split("/").includes("..")) return undefined;
24 return p;
25 }
26
27 export interface Touches {
28 readonly tools: string[];
29 readonly files: string[];
30 }
31
32 /** The tools and files of a trace, bounded. */
33 export function touchesOf(trace: Trace): Touches {
34 const tools = new Set<string>();
35 const edited: string[] = [];
36 const read: string[] = [];
37 const cwd = trace.cwd === undefined ? "" : `${trace.cwd.replace(/\/+$/, "")}/`;
38 for (const s of stepsOf(trace)) {
39 if (s.kind === "model" || !TOOL_NAME.test(s.name) || s.name === "error") continue;
40 if (tools.size < MAX_TOOLS) tools.add(s.name);
41 const writes = FILE_TOOLS[s.name];
42 if (writes === undefined) continue;
43 // Drop the `+12 −3` the step line ends with.
44 const target = s.line.slice(s.name.length + 1).replace(/\s[+−-]\d+(\s[+−-]\d+)?$/, "");
45 const path = cleanPath(cwd !== "" && target.startsWith(cwd) ? target.slice(cwd.length) : target);
46 if (path !== undefined) (writes ? edited : read).push(path);
47 }
48 return { tools: [...tools], files: [...new Set([...edited, ...read])].slice(0, MAX_PATHS) };
49 }
50
51 /** Write a trace's touches, replacing any, and mark its row as filled. */
52 export function putTouches(db: Database, id: string, t: Touches): void {
53 db.query("DELETE FROM trace_touch WHERE trace_id = ?1").run(id);
54 const add = db.query("INSERT OR IGNORE INTO trace_touch (kind, value, trace_id) VALUES (?1, ?2, ?3)");
55 for (const v of t.tools) add.run("tool", v, id);
56 for (const v of t.files) add.run("file", v, id);
57 db.query("UPDATE trace_index SET touched = 1 WHERE id = ?1").run(id);
58 }
59
60 /**
61 * The SQL a facet adds to a read of `trace_index` (aliased `alias`): the trace used the tool,
62 * touched the file.
63 */
64 export const touchClause = (alias: string, kind: "tool" | "file", param: string): string =>
65 `EXISTS (SELECT 1 FROM trace_touch x WHERE x.kind = '${kind}' AND x.value = ${param} AND x.trace_id = ${alias}.id)`;
src/trace/touched_count.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * How many traces a viewer may open still wait to be filled with their tools and files (#18368).
3 * Split from `touched.ts` because it needs the run gate, which `index_table.ts` must not import.
4 */
5 import { mayReadRunLog } from "../actions/runs.ts";
6 import type { App } from "../app.ts";
7 import { canRead, getRepoById } from "../core/repos.ts";
8 import type { User } from "../core/users.ts";
9
10 /**
11 * How many traces `actor` may open are not yet filled: their tools and files are not in the index,
12 * so a tool or file facet cannot see them. Asked of the index alone (the partial index of rows
13 * still to fill), gated as the list is: a repository whose runs the viewer may not read counts for
14 * nothing.
15 */
16 export function unindexedFor(app: App, actor: User | undefined): number {
17 const db = app.db;
18 let n = 0;
19 for (const { repository, n: count } of db.query<{ repository: string; n: number }, []>("SELECT repository, COUNT(*) AS n FROM trace_index WHERE touched = 0 AND repository <> '' AND owner = '' GROUP BY repository").all()) {
20 const repo = getRepoById(db, repository);
21 if (repo !== undefined && canRead(db, repo, actor) && mayReadRunLog(app, actor, repo)) n += count;
22 }
23 // No viewer, no repository-less rows: an empty id would match every ownerless row.
24 if (actor === undefined) return n;
25 n +=
26 db
outdated

Medium: with actor undefined, ?1 is '', so t.owner = ?1 matches every repository-less row with an empty owner. A signed-out viewer is told how many other people's Talk turns are unindexed. Skip this query when there is no actor, and test it.

27 .query<{ n: number }, [string]>(
28 "SELECT COUNT(*) AS n FROM trace_index t WHERE t.touched = 0 AND t.repository = '' AND (t.owner = ?1 OR (t.owner = '' AND t.kind = 'talk' AND EXISTS (SELECT 1 FROM conversation_run c WHERE c.id = t.id AND c.user_id = ?1)))",
29 )
30 .get(actor.id)?.n ?? 0;
31 return n;
32 }
src/trace/touched_fill.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * The touches of the traces indexed before `trace_touch` existed (#18368), filled a few at a time:
3 * each row's log (or an imported session's file) is read once and its tools and files written. The
4 * list never does this on a request; the boot starts it (`fillTouchesInBatches`). A row whose
5 * record cannot be read is marked filled with nothing, so one bad record never holds the rest back.
outdated

This is not true: a filtered list does not ask for a batch. Only the boot pass fills. Drop the clause.

6 */
7 import type { Database } from "bun:sqlite";
8 import { readRunLog, readRunTimes } from "../runs/log.ts";
9 import { readImported } from "./import.ts";
10 import { putTouches, touchesOf } from "./touched.ts";
11 import { parseRunLog } from "./run_log.ts";
12 import { parseSession } from "./session.ts";
13
14 export const FILL_BATCH = 20;
15
16 /** Fill up to `batch` rows still to fill; how many it filled. */
17 export function fillTouches(db: Database, dataDir: string, batch = FILL_BATCH): number {
18 const rows = db.query<{ id: string; title: string; owner: string }, [number]>("SELECT id, title, owner FROM trace_index WHERE touched = 0 ORDER BY started DESC LIMIT ?1").all(batch);
19 db.transaction(() => {
20 for (const r of rows) {
21 let touches = { tools: [] as string[], files: [] as string[] };
22 try {
23 if (r.owner !== "") touches = touchesOf(parseSession(readImported(dataDir, r.id)));
24 else {
25 const { lines } = readRunLog(dataDir, r.id);
26 touches = touchesOf(parseRunLog(r.id, r.title, lines, readRunTimes(dataDir, r.id, lines.length)).trace);
27 }
28 } catch {
29 // Nothing readable: filled with nothing.
30 }
31 putTouches(db, r.id, touches);
32 }
33 })();
34 return rows.length;
35 }
36
37 /** Fill every row still to fill, `batch` at a time with a yield between. */
38 export async function fillTouchesInBatches(db: Database, dataDir: string, yieldNow: () => Promise<void> = () => new Promise((r) => setImmediate(r))): Promise<number> {
39 let total = 0;
40 for (;;) {
41 const n = fillTouches(db, dataDir);
42 total += n;
43 if (n < FILL_BATCH) return total;
44 await yieldNow();
45 }
46 }
src/trace/tree.ts +22 −2
@@ -14,6 +14,8 @@ import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_
1414 import { parseImported } from "./imported_read.ts";
1515 import type { Trace } from "./model.ts";
1616 import { MAX_STEPS, parseRunLog } from "./run_log.ts";
17 import { cleanPath, TOOL_NAME } from "./touched.ts";
18 import { unindexedFor } from "./touched_count.ts";
1719
1820 /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */
1921 export const TRACE_ID = /^[0-9a-z]{1,40}$/;
@@ -35,7 +37,7 @@ function seeing(app: App, actor: User): (row: TraceRow) => boolean {
3537 }
3638
3739 /** The parameters the list reads; any other is refused by name. */
38 export const LIST_PARAMETERS = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const;
40 export const LIST_PARAMETERS = ["repository", "kind", "model", "outcome", "since", "until", "tool", "file", "cursor", "limit"] as const;
3941 const KINDS: readonly string[] = ["run", "talk", "review", "imported"];
4042 export const LIST_OUTCOMES = ["ok", "failed", "cancelled", "stopped"] as const;
4143 /** An instant: a date, or a date and time with a zone. */
@@ -87,6 +89,17 @@ export function readListAsk(app: App, q: URLSearchParams): ListAsk {
8789 if (at === undefined) return { ok: false, error: `invalid_${name}`, message: `${name} is a date or an ISO 8601 instant with a zone` };
8890 query[name] = at;
8991 }
92 const tool = q.get("tool");
93 if (tool !== null) {
94 if (!TOOL_NAME.test(tool)) return { ok: false, error: "invalid_tool", message: "tool is a tool name as the log wrote it, such as Edit or Bash" };
95 query.tool = tool;
96 }
97 const file = q.get("file");
98 if (file !== null) {
99 const path = cleanPath(file);
100 if (path === undefined) return { ok: false, error: "invalid_file", message: "file is a path of up to 300 characters, without .. steps" };
101 query.file = path;
102 }
90103 const repository = q.get("repository");
91104 if (repository !== null) {
92105 if (!WORD.test(repository)) return { ok: false, error: "invalid_repository", message: "repository is a repository id or owner/name" };
@@ -101,7 +114,14 @@ export function readListAsk(app: App, q: URLSearchParams): ListAsk {
101114 * One page of the index `actor` may see, newest first, as `{ items, next_cursor }`. Only the index
102115 * is read, never a raw log.
103116 */
104 export function listSeenTraces(app: App, actor: User, ask: { query: TraceQuery; cursor: string | undefined; limit: number }): { items: TraceRow[]; next_cursor: string | null } {
117 export function listSeenTraces(app: App, actor: User, ask: { query: TraceQuery; cursor: string | undefined; limit: number }): { items: TraceRow[]; next_cursor: string | null; unindexed?: number } {
118 const page = listPage(app, actor, ask);
119 // A tool or file facet reads what the index holds: say how many the viewer may open that it
120 // does not hold yet, so a short answer is not read as a complete one (#18368).
121 return ask.query.tool === undefined && ask.query.file === undefined ? page : { ...page, unindexed: unindexedFor(app, actor) };
122 }
123
124 function listPage(app: App, actor: User, ask: { query: TraceQuery; cursor: string | undefined; limit: number }): { items: TraceRow[]; next_cursor: string | null } {
105125 const may = seeing(app, actor);
106126 const items: TraceRow[] = [];
107127 let from = ask.cursor;
src/tui/screens/traces.ts +14 −11
@@ -1,13 +1,13 @@
11 /**
22 * The Traces command (#17992): what `/traces` says, one line a crew run, Talk turn or imported
33 * session (`i` cycles the kind), newest first. `/` types a search (the same text as the page's
4 * `q`), `r` `m` `o` `p` cycle the repository, model, outcome and person facets through what the
5 * list offers (then back to any), `f` and `t` type the from and to days (YYYY-MM-DD), `c` clears
6 * them, `j`/`k` move, Enter opens the run's trace, `n` reads the next older page. `v` marks a row
7 * (two at most, the older mark drops) and `d` opens the two as a comparison (#18085): the trace
8 * screen's own, so the page's words; two runs of different issues are told so. Every value goes
9 * through the page's own `readFilter`. Read-only; Esc closes. The lines are `traceLine`, the page's
10 * own row.
4 * `q`), `u` and `e` type the tool a run used and the file it touched (the page's Tool and File),
5 * `r` `m` `o` `p` cycle the repository, model, outcome and person facets through what the list
6 * offers (then back to any), `f` and `t` type the from and to days (YYYY-MM-DD), `c` clears them,
7 * `j`/`k` move, Enter opens the run's trace, `n` reads the next older page. `v` marks a row (two at
8 * most, the older mark drops) and `d` opens the two as a comparison (#18085): the trace screen's
9 * own, so the page's words; two runs of different issues are told so. Every value goes through the
10 * page's own `readFilter`. Read-only; Esc closes. The lines are `traceLine`, the page's own row.
1111 */
1212 import { binding } from "../app/keys.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
@@ -26,7 +26,7 @@ import type { PaletteEntry } from "./entries.ts";
2626 function tracesScreen(f: Session, ctx: Ctx): Screen {
2727 const scroll = new Scroll();
2828 // What the page holds in its URL, as strings; `readFilter` is the one validator of them.
29 const facet: { [K in "q" | "kind" | "repo" | "model" | "outcome" | "by" | "from" | "to"]?: string } = {};
29 const facet: { [K in "q" | "kind" | "repo" | "model" | "outcome" | "by" | "tool" | "file" | "from" | "to"]?: string } = {};
3030 let before: string | undefined;
3131 const filter = (): TraceFilter => {
3232 const p = new URLSearchParams();
@@ -38,7 +38,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
3838 let at = 0;
3939 // The runs marked to compare, oldest mark first.
4040 let marked: string[] = [];
41 let typing: "q" | "from" | "to" | undefined;
41 let typing: "q" | "tool" | "file" | "from" | "to" | undefined;
4242 const read = (): void => {
4343 list = listTraces(f.app, f.user, filter());
4444 at = 0;
@@ -61,10 +61,11 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
6161 };
6262 return {
6363 title: "Traces",
64 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
64 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["u", "e"], "tool used, file touched"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
6565 render(area, s) {
6666 const c = ctx.theme.c;
67 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);
67 s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : typing === "to" ? "To (YYYY-MM-DD)" : typing === "tool" ? "Tool (Edit, Bash…)" : "File (path)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w);
68 if (list.unindexed > 0) s.text(area.x, area.y + 1, truncate(`${list.unindexed} not indexed for tools and files yet: a tool or file search may miss them`, area.w), style(c.muted, c.bg), area.x + area.w);
6869 if (list.rows.length === 0) {
6970 emptyState(s, { ...area, y: area.y + 2, h: Math.max(1, area.h - 2) }, c, { title: Object.keys(facet).length === 0 ? "No traces yet" : "No trace matches", body: "" });
7071 return;
@@ -91,6 +92,8 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
9192 else if (!e.ctrl && !e.alt && [...e.key].length === 1 && [...cur].length < 80) set(typing, cur + e.key);
9293 } else if (e.key === "esc") ctx.pop();
9394 else if (e.key === "/") typing = "q";
95 else if (e.key === "u") typing = "tool";
96 else if (e.key === "e") typing = "file";
9497 else if (e.key === "f") typing = "from";
9598 else if (e.key === "t") typing = "to";
9699 else if (e.key === "i") cycle("kind", SOURCES);
src/web/pages/traces.ts +9
@@ -20,6 +20,8 @@ const FILTERS: readonly [keyof TraceFilter, string][] = [
2020 ["model", "Model"],
2121 ["outcome", "Outcome"],
2222 ["by", "Person or agent"],
23 ["tool", "Tool"],
24 ["file", "File"],
2325 ["from", "From"],
2426 ["to", "To"],
2527 ];
@@ -31,6 +33,9 @@ const select = (name: string, label: string, values: readonly string[], now: str
3133 const date = (name: string, label: string, now: string | undefined): Html =>
3234 html`<label class="field"><span class="small muted">${label}</span><input class="input" type="date" name="${name}" value="${now ?? ""}" /></label>`;
3335
36 const text = (name: string, label: string, now: string | undefined, hint: string, max = 300): Html =>
37 html`<label class="field"><span class="small muted">${label}</span><input class="input" name="${name}" value="${now ?? ""}" placeholder="${hint}" maxlength="${max}" autocomplete="off" /></label>`;
38
3439 const line = (r: TraceRow): Html =>
3540 row({
3641 // An imported session has no page yet: a plain row, not a link that goes nowhere.
@@ -52,6 +57,7 @@ function controls(f: TraceFilter, list: TraceList): Html {
5257 html`<div class="traces-facets">
5358 ${select("kind", "Kind", SOURCES, f.kind)}${select("repo", "Repository", list.facets.repos, f.repo)}${select("model", "Model", list.facets.models, f.model)}
5459 ${select("outcome", "Outcome", OUTCOMES, f.outcome)}${select("by", "Person or agent", list.facets.people, f.by)}
60 ${text("tool", "Tool", f.tool, "Edit, Bash…", 64)}${text("file", "File", f.file, "src/http/respond.ts")}
5561 ${date("from", "From", f.from)}${date("to", "To", f.to)}
5662 </div>${f.repo === undefined ? "" : html`<p class="muted" data-repo-note>A repository narrows to crew runs: Talk turns and imported sessions have none.</p>`}`,
5763 { small: true, extra: "mt", open: active.length > 0 },
@@ -82,6 +88,9 @@ export function tracesPage(ctx: Ctx): Response {
8288 const searching = Object.keys(f).some((k) => k !== "before");
8389 const body = html`${pageHead("Traces", { sub: "Every crew run, Talk turn and imported session you may open, newest first." })}
8490 ${controls(f, list)}
91 ${list.unindexed === 0
92 ? null
93 : html`<p class="small muted" id="traces-unindexed">${list.unindexed} ${list.unindexed === 1 ? "trace is" : "traces are"} not indexed for tools and files yet, so a Tool or File search may miss ${list.unindexed === 1 ? "it" : "them"}.</p>`}
8594 ${list.rows.length === 0
8695 ? empty({ icon: "activity", title: searching ? "No trace matches" : "No traces yet", note: searching ? "Take a filter off, or search for fewer words." : "A crew run's steps appear here once it has run." })
8796 : html`<div id="traces-list">${listCard(list.rows.map(line))}</div>`}
test/traces-touch-tui.test.ts added +79
@@ -0,0 +1,79 @@
1 /** The terminal's Traces screen takes the tool and file keys the page's fields have (#18368). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App as Forge } from "../src/app.ts";
8 import type { User } from "../src/core/users.ts";
9 import { appendRunLog, flushRunLogs } from "../src/runs/log.ts";
10 import { indexRun } from "../src/trace/index_table.ts";
11 import { createForgeApp } from "../src/tui/forge.ts";
12 import { headlessTerminal } from "../src/tui/term/terminal.ts";
13 import { entry } from "../src/tui/screens/traces.ts";
14 import { seedAdmin } from "./helpers/admin.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let forge: Forge;
22 let alice: User;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-tui-touch-"));
26 forge = createApp({ dataDir: dir, port: 0 });
27 const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
28 if (!a.ok) throw new Error("signup failed");
29 alice = a.value;
30 const repo = await createRepo(forge, alice, { name: "mix", visibility: "public", description: "" });
31 if (!repo.ok) throw new Error("repo failed");
32 const ins = forge.db.prepare("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at) VALUES (?1, ?2, 'agent', 'ok', ?3, 'm', ?4, 0, ?5)");
33 ins.run("run1", repo.value.id, "edited the responder", alice.id, "2026-12-03T10:00:00.000Z");
34 ins.run("run2", repo.value.id, "only ran tests", alice.id, "2026-12-02T10:00:00.000Z");
35 appendRunLog(dir, "run1", "→ Edit src/http/respond.ts +1 −1");
36 appendRunLog(dir, "run2", "→ Bash bun test");
37 flushRunLogs();
38 indexRun(forge.db, dir, "run1");
39 indexRun(forge.db, dir, "run2");
40 // One more, not indexed for tools and files yet.
41 ins.run("run3", repo.value.id, "an older one", alice.id, "2026-12-01T10:00:00.000Z");
42 indexRun(forge.db, dir, "run3");
43 forge.db.query("UPDATE trace_index SET touched = 0 WHERE id = 'run3'").run();
44 });
45 afterAll(async () => {
46 forge.close?.();
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 test("u types the tool and e the file; the list narrows and says what is not indexed yet", async () => {
51 const { app, session } = createForgeApp(forge, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(120, 30), exitHooks: false });
52 app.start();
53 await settleApp(app);
54 entry.run(session, app.ctx);
55 await settleApp(app);
56 const press = async (key: string): Promise<string> => {
57 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
58 await settleApp(app);
59 return app.screen.toText();
60 };
61 const type = async (keys: string): Promise<string> => {
62 let out = "";
63 for (const k of keys) out = await press(k);
64 return out;
65 };
66 expect(app.screen.toText()).toContain("only ran tests");
67 await press("u");
68 const bash = await type("Bash");
69 expect(bash).toContain("only ran tests");
70 expect(bash).not.toContain("edited the responder");
71 expect(bash).toContain("1 not indexed for tools and files yet");
72 await press("enter");
73 await press("c");
74 await press("e");
75 const file = await type("src/http/respond.ts");
76 expect(file).toContain("edited the responder");
77 expect(file).not.toContain("only ran tests");
78 app.stop();
79 });
test/traces-touch.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * `/traces` narrows by the tool a run used and the file it touched (#18368): the page, the API and
3 * the terminal read the trace index (`trace_touch`), never a log on the list path.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { appendRunLog, flushRunLogs } from "../src/runs/log.ts";
15 import { indexRun, putTraceRow } from "../src/trace/index_table.ts";
16 import { listTraces, readFilter } from "../src/trace/list.ts";
17 import { MAX_PATHS, putTouches, touchesOf } from "../src/trace/touched.ts";
18 import { fillTouches } from "../src/trace/touched_fill.ts";
19 import { parseRunLog } from "../src/trace/run_log.ts";
20 import { seedAdmin } from "./helpers/admin.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24
25 let dir = "";
26 let app: App;
27 let servers: Servers;
28 let alice: User;
29 let bob: User;
30 let aliceToken = "";
31
32 const ids = (u: User | undefined, q: string): string[] => listTraces(app, u, readFilter(new URLSearchParams(q))).rows.map((r) => r.id);
33 const get = (token: string, path: string) => fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${token}` } });
34
35 function run(id: string, repoId: string, at: string, log: string[]): void {
36 app.db.query("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at, finished_at) VALUES (?1, ?2, 'agent', 'ok', ?1, 'm', ?3, 0, ?4, ?4)").run(id, repoId, alice.id, at);
37 for (const line of log) appendRunLog(dir, id, line);
38 flushRunLogs();
39 }
40
41 beforeAll(async () => {
42 dir = await mkdtemp(join(tmpdir(), "forge-traces-touch-"));
43 app = createApp({ dataDir: dir, port: 0 });
44 servers = await serve(app);
45 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
46 if (!a.ok) throw new Error(a.error);
47 alice = a.value;
48 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
49 if (!b.ok) throw new Error("bob");
50 bob = b.value;
51 aliceToken = createToken(app.db, alice.id, "t", "ro").token;
52 const open = await createRepo(app, alice, { name: "lamp", visibility: "public" });
53 const priv = await createRepo(app, alice, { name: "vault", visibility: "private" });
54 if (!open.ok || !priv.ok) throw new Error("repo");
55 run("r1", open.value.id, "2026-12-01T10:00:00.000Z", ["Looking.", "→ Edit src/http/respond.ts +4 −1", "→ Bash bun test"]);
56 run("r2", open.value.id, "2026-12-02T10:00:00.000Z", ["→ Read src/http/respond.ts", "→ Bash ls -l"]);
57 run("r3", open.value.id, "2026-12-03T10:00:00.000Z", ["→ Write docs/new.md +10"]);
58 run("r4", priv.value.id, "2026-12-04T10:00:00.000Z", ["→ Edit src/http/respond.ts +1 −1", "→ Grep secret"]);
59 for (const id of ["r1", "r2", "r3", "r4"]) indexRun(app.db, dir, id);
60 // Alice's own imported session.
61 putTraceRow(app.db, { id: "imp1", kind: "imported", repository: "", title: "outside", model: "x", account: "", steps: 1, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-05T09:00:00.000Z", ended: "2026-12-05T09:01:00.000Z" }, alice.id);
62 putTouches(app.db, "imp1", { tools: ["Edit", "WebFetch"], files: ["src/http/respond.ts"] });
63 }, 30_000);
64
65 afterAll(async () => {
66 servers.stop();
67 app.close();
68 await rm(dir, { recursive: true, force: true });
69 });
70
71 test("the tool facet narrows the list to the traces that used it", () => {
72 expect(ids(alice, "tool=Bash")).toEqual(["r2", "r1"]);
73 expect(ids(alice, "tool=Edit")).toEqual(["imp1", "r4", "r1"]);
74 expect(ids(alice, "tool=Edit&kind=imported")).toEqual(["imp1"]);
75 expect(ids(alice, "tool=Nothing")).toEqual([]);
76 expect(ids(alice, "tool=Bash&file=src/http/respond.ts")).toEqual(["r2", "r1"]);
77 });
78
79 test("the file facet narrows to the traces that touched that path, and a step's +/- tail is no part of it", () => {
80 expect(ids(alice, "file=src/http/respond.ts")).toEqual(["imp1", "r4", "r2", "r1"]);
81 expect(ids(alice, "file=docs/new.md")).toEqual(["r3"]);
82 expect(ids(alice, "file=./docs/new.md")).toEqual(["r3"]);
83 expect(ids(alice, "file=respond.ts")).toEqual([]); // the whole path, not a piece of it
84 });
85
86 test("a viewer sees only the traces they may read", () => {
87 expect(ids(bob, "tool=Edit")).toEqual([]);
88 // A run's log is the crew's and the owner's: a stranger finds none, public repository or not.
89 expect(ids(bob, "file=src/http/respond.ts")).toEqual([]);
90 expect(ids(bob, "tool=Grep")).toEqual([]);
91 expect(ids(undefined, "tool=Bash")).toEqual([]);
92 });
93
94 test("a row not yet indexed is counted, not answered wrongly, and a fill makes it match", () => {
95 run("r5", (app.db.query("SELECT repo_id FROM run WHERE id = 'r1'").get() as { repo_id: string }).repo_id, "2026-12-06T10:00:00.000Z", ["→ Edit late.ts"]);
96 indexRun(app.db, dir, "r5");
97 app.db.query("UPDATE trace_index SET touched = 0 WHERE id = 'r5'").run();
98 app.db.query("DELETE FROM trace_touch WHERE trace_id = 'r5'").run();
99 expect(ids(alice, "file=late.ts")).toEqual([]);
100 expect(listTraces(app, alice, readFilter(new URLSearchParams("file=late.ts"))).unindexed).toBe(1);
101 expect(listTraces(app, alice, {}).unindexed).toBe(0); // only a tool or file search needs it said
102 // A stranger is told of none: the count is gated as the list is.
103 expect(listTraces(app, bob, readFilter(new URLSearchParams("tool=Edit"))).unindexed).toBe(0);
104 // A signed-out viewer is told of none, though another person's Talk turn waits unindexed.
105 app.db.query("INSERT INTO trace_index (id, kind, repository, title, model, account, steps, errors, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started, ended, owner, touched) VALUES ('talk-x', 'talk', '', 't', 'm', '', 0, 0, 0, 0, 0, 0, 'ok', '2026-12-06T11:00:00.000Z', '2026-12-06T11:00:00.000Z', '', 0)").run();
106 expect(listTraces(app, undefined, readFilter(new URLSearchParams("tool=Edit"))).unindexed).toBe(0);
107 expect(listTraces(app, bob, readFilter(new URLSearchParams("tool=Edit"))).unindexed).toBe(0);
108 app.db.query("DELETE FROM trace_index WHERE id = 'talk-x'").run();
109 expect(fillTouches(app.db, dir)).toBe(1);
110 expect(ids(alice, "file=late.ts")).toEqual(["r5"]);
111 expect(listTraces(app, alice, readFilter(new URLSearchParams("file=late.ts"))).unindexed).toBe(0);
112 });
113
114 test("a malformed value is dropped on the page's reader and refused by the API", async () => {
115 expect(readFilter(new URLSearchParams("tool=a b<c&file=../etc/passwd"))).toEqual({});
116 expect(readFilter(new URLSearchParams("tool=Edit&file=src/a.ts"))).toEqual({ tool: "Edit", file: "src/a.ts" });
117 for (const bad of ["tool=%3Cscript%3E", "tool=", "file=../x", "file=a%0Ab"]) {
118 const r = await get(aliceToken, `/api/v1/traces?${bad}`);
119 expect(r.status).toBe(400);
120 expect(((await r.json()) as { error: string }).error).toMatch(/^invalid_(tool|file)$/);
121 }
122 });
123
124 test("the API answers the narrowed list and says how many are unindexed", async () => {
125 const r = await get(aliceToken, "/api/v1/traces?tool=Bash");
126 expect(r.status).toBe(200);
127 const body = (await r.json()) as { items: { id: string }[]; unindexed: number };
128 expect(body.items.map((i) => i.id)).toEqual(["r2", "r1"]);
129 expect(body.unindexed).toBe(0);
130 const plain = (await (await get(aliceToken, "/api/v1/traces")).json()) as Record<string, unknown>;
131 expect("unindexed" in plain).toBe(false);
132 });
133
134 test("the page has Tool and File fields, and a hostile value is escaped", async () => {
135 const html = await (await get(aliceToken, "/traces?tool=Bash")).text();
136 expect(html).toContain('name="tool"');
137 expect(html).toContain('name="file"');
138 expect(html).toContain('data-trace="r2"');
139 expect(html).not.toContain('data-trace="r3"');
140 const hostile = await (await get(aliceToken, `/traces?file=${encodeURIComponent('x"><img src=x onerror=alert(1)>.ts')}`)).text();
141 expect(hostile).not.toContain("<img src=x");
142 expect(hostile).toContain("&lt;img src=x");
143 expect(hostile).toContain("No trace matches");
144 });
145
146 test("the index keeps at most MAX_PATHS paths a trace, edits first, and the step tail is dropped", () => {
147 const lines = [...Array.from({ length: 70 }, (_, i) => `→ Read read${i}.ts`), "→ Edit edited.ts +3 −2"];
148 const t = touchesOf(parseRunLog("x", "x", lines).trace);
149 expect(t.files.length).toBe(MAX_PATHS);
150 expect(t.files[0]).toBe("edited.ts");
151 expect(t.tools).toEqual(["Read", "Edit"]);
152 });
153
154 test("the facets are answered from the index by key, never a scan", () => {
155 const plan = (sql: string) => app.db.query<{ detail: string }, [string]>(`EXPLAIN QUERY PLAN ${sql}`).all("Edit").map((r) => r.detail).join("\n");
156 const tool = plan("SELECT id FROM trace_index WHERE EXISTS (SELECT 1 FROM trace_touch x WHERE x.kind = 'tool' AND x.value = ?1 AND x.trace_id = trace_index.id)");
157 expect(tool).toContain("trace_touch");
158 expect(tool).not.toMatch(/SCAN x|SCAN trace_touch/);
159 expect(plan("SELECT repository, COUNT(*) FROM trace_index WHERE touched = 0 AND repository <> '' GROUP BY repository")).toContain("trace_index_untouched");
160 });

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

Keyboard shortcuts

Docs