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

Traces 5: compare two traces, and share one with secrets redacted #18017

opened this in answer to

Merged 6h 41m ago, live in production

torque/forge:torque/17995-traces-5-compare-two-traces-and-share-on → main 0 commits fork 5 threads · 5 unresolved

  • Merged. torque/17995-traces-5-compare-two-traces-and-share-on was merged into main as 7a17314.

Review

Sign in to review this change.
30 files changed +857 −9
docs/design/areas/traces.md +2
@@ -3,3 +3,5 @@
33 `/traces/:id` (`src/web/pages/trace.ts`), one crew run as a tree of steps beside a strip of them. Page-local classes, drawn from existing tokens: `.trace-strip` (the inline SVG, fixed 28px tall so nothing shifts; `.trace-tick-model`, `.trace-tick-tool` and `.trace-tick-bad` colour a tick by what the step was), `.trace-tree` (the collapsible tree, a group of `details`), `.trace-calls` (a step's tool calls, indented), `.trace-step` (one step's `details`; `.trace-bad` turns a failed one `--danger`, `.trace-here` rings the step a `#step-N` address names), `.trace-raw` (a step's raw lines, loaded when it opens, scrolls inside 24rem) and `.trace-n` (the step's number, quiet).
44
55 `/traces` (`src/web/pages/traces.ts`), the list. Page-local classes, drawn from existing tokens: `.traces-search` (the search form: the input grows, the button and the Filters disclosure wrap under it on a phone) and `.traces-facets` (the facet selects and dates, an auto-fit grid of `.field`s). `#traces-list` only ellipsises a row's title and meta to one line each. A removable active filter is the shared `.badge` with the `x` icon inside its link.
6
7 `/traces/:id/compare/:other` (`src/web/pages/trace_compare.ts`) is one `table` of the shared table class, A and B as column heads and B − A last; `/traces/shared/:token` (`src/web/pages/trace_share.ts`) is the same `details` rows with the raw lines inline and no script. No new classes.
docs/features/traces.md +9 −1
@@ -22,6 +22,14 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu
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
25 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: storing an import, tokens and cost per step (the file holds none), compare, share.
25 ## Compare two runs, and share one (#17995)
26
27 `/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`.
28
29 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`).
30
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`.
32
33 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).
2634
2735 The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step.
src/actions/trace_share.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * Who may make or end a trace's share link (#17995): the repository's owner, and only for a run of
3 * theirs whose log they may read. A reader who is not the owner is told `forbidden`; someone who
4 * cannot see the run is told `not_found`, never a hint it exists. The page, the terminal and the
5 * MCP tool all come through here, so the three share one gate and the same words.
6 */
7 import type { App } from "../app.ts";
8 import { ownsRepo, type Repo } from "../core/repos.ts";
9 import type { User } from "../core/users.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { isShared, makeShare, revokeShare } from "../trace/share.ts";
12 import { getRepoRun } from "./runs.ts";
13
14 export type ShareError = "unauthorized" | "forbidden" | "not_found";
15
16 /** The path a link's secret opens: `/traces/shared/<secret>`. */
17 export const sharedHref = (token: string): string => `/traces/shared/${token}`;
18
19 function mayShare(app: App, actor: User | undefined, repo: Repo, runId: string): Result<User, ShareError> {
20 if (actor === undefined) return err("unauthorized");
21 if (!getRepoRun(app, actor, repo, runId).ok) return err("not_found");
22 return ownsRepo(app.db, repo, actor) ? ok(actor) : err("forbidden");
23 }
24
25 /** Make the run's link (an older one ends); its secret is told once. */
26 export function shareRun(app: App, actor: User | undefined, repo: Repo, runId: string, now = Date.now()): Result<{ token: string }, ShareError> {
27 const who = mayShare(app, actor, repo, runId);
28 if (!who.ok) return who;
29 return ok({ token: makeShare(app.db, runId, who.value.id, now) });
30 }
31
32 /** End the run's link; whether one was live. */
33 export function unshareRun(app: App, actor: User | undefined, repo: Repo, runId: string, now = Date.now()): Result<{ was: boolean }, ShareError> {
34 const who = mayShare(app, actor, repo, runId);
35 return who.ok ? ok({ was: revokeShare(app.db, runId, now) }) : who;
36 }
37
38 /** Whether the run is shared now: said only to the owner who could end it. */
39 export function sharedNow(app: App, actor: User | undefined, repo: Repo, runId: string): boolean | undefined {
40 return mayShare(app, actor, repo, runId).ok ? isShared(app.db, runId) : undefined;
41 }
src/core/account_purge.ts +2
@@ -52,6 +52,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5252 "access_link.created_by": FORMER,
5353 // Who asked a game box to run a command: the record keeps it, as the former account.
5454 "game_command.by": FORMER,
55 // A trace share link is its maker's to give, like a client pack link: it ends with the person.
56 "trace_share.created_by": DELETE,
5557 // The link a person made to a game box's client pack ends with the person: it is theirs to give, and the row goes.
5658 "game_client_link.created_by": DELETE,
5759 // The !forge audit keeps what was said and what came of it; who said it becomes a former member.
src/core/migration-pins/20261204025000-trace-share.pin added +1
@@ -0,0 +1,1 @@
1 1a84b78ce5e7bb6e6471c3980f99d49157b70f8242d1ef1d5456296b62194523
src/core/migrations/20261204025000-trace-share.ts added +14
@@ -0,0 +1,14 @@
1 // A share link for one run's trace (#17995): off by default, made by the repository's owner,
2 // revoked by setting `revoked_at`. Only the hash of the link's secret is kept. Additive: a new
3 // table.
4 export default `
5 CREATE TABLE IF NOT EXISTS trace_share (
6 id TEXT PRIMARY KEY,
7 run_id TEXT NOT NULL,
8 token_hash TEXT NOT NULL UNIQUE,
9 created_by TEXT NOT NULL,
10 created_at TEXT NOT NULL,
11 revoked_at TEXT
12 );
13 CREATE INDEX IF NOT EXISTS trace_share_run ON trace_share (run_id, revoked_at);
14 `;
src/core/runs.ts +13
@@ -2198,3 +2198,16 @@ export function lastPullAt(db: Database, appId: string): number | undefined {
21982198 const at = Date.parse(row.created_at);
21992199 return Number.isFinite(at) ? at : undefined;
22002200 }
2201
2202 /**
2203 * The other agent runs of one issue or pull, newest first, at most `limit` (#17995): what a trace
2204 * is compared with. Walks `run_issue (issue_id, id DESC)`.
2205 */
2206 export function otherRunsOfIssue(db: Database, issueId: string, exceptRunId: string, limit = 20): Run[] {
2207 return db
2208 .query<RunRow, [string, string, number]>(
2209 "SELECT * FROM run WHERE issue_id = ?1 AND id <> ?2 AND kind = 'agent' ORDER BY id DESC LIMIT ?3",
2210 )
2211 .all(issueId, exceptRunId, limit)
2212 .map(toRun);
2213 }
src/crew/conversation_ask.ts +4
@@ -188,6 +188,10 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
188188 close: (a) =>
189189 a["state"] === "open" ? `Reopen ${item(a)}` : `Close ${item(a)}${clause(" as ", verb(a, "reason", { done: "done", dropped: "dropped", split: "split up" }, ""))}`,
190190 merge: (a) => `Merge ${pull(a)}`,
191 trace: (a) =>
192 a["action"] === "unshare"
193 ? `Stop sharing the trace of run ${val(a, "run")} in ${repo(a)}`
194 : `Make a redacted share link for the trace of run ${val(a, "run")} in ${repo(a)}`,
191195 cut_wave: (a) => `Cut the next wave of ${repo(a, "the app")} as a draft pull`,
192196 wall: (a) => (a["answer"] === "send_back" ? `Send ${pull(a)} back at the access wall` : `Allow ${pull(a)} at the access wall and merge it`),
193197 edit: (a) =>
src/crew/conversation_confirm.ts +3
@@ -63,6 +63,9 @@ export const ASKING: Readonly<Record<string, Asking>> = {
6363 undo: (a) => `\`archive\` with \`archived: ${a["archived"] === false}\` turns it back`,
6464 },
6565 board_delete: {},
66 // Making or ending a redacted share link for a run trace (#17995); reading and comparing never
67 // ask.
68 trace: { asks: (a) => a["action"] === "share" || a["action"] === "unshare" },
6669 // One action over every row a fleet query selects (#450); only `apply: true` writes.
6770 flow: {
6871 undo: () => "`limb` with `action: undo` and the receipt's id reverts it for 24 hours",
src/http/lazy_lists.ts +4
@@ -698,6 +698,10 @@ export const OPERATIONS_ROUTES = [
698698 ["GET", "/traces"],
699699 ["GET", "/traces/:id"],
700700 ["GET", "/traces/:id/steps/:n"],
701 ["GET", "/traces/:id/compare/:other"],
702 ["POST", "/traces/:id/share"],
703 ["POST", "/traces/:id/unshare"],
704 ["GET", "/traces/shared/:token"],
701705 ] as const;
702706
703707 /** `originsRoutes` (`routes/origins.ts`). */
src/http/mcp/tools/index.ts +1
@@ -209,6 +209,7 @@ export { tool as templates } from "./templates.ts";
209209 export { tool as thought } from "./thought.ts";
210210 export { tool as threads } from "./threads.ts";
211211 export { tool as tokens } from "./tokens.ts";
212 export { tool as trace } from "./trace.ts";
212213 export { tool as trail } from "./trail.ts";
213214 export { tool as upstream } from "./upstream.ts";
214215 export { tool as usage } from "./usage.ts";
src/http/mcp/tools/trace.ts added +60
@@ -0,0 +1,60 @@
1 import { listRepoRuns } from "../../../actions/runs.ts";
2 import { sharedHref, shareRun, unshareRun } from "../../../actions/trace_share.ts";
3 import { compareRows, compareViews, readCompared } from "../../../trace/compare.ts";
4 import { readTrace, traceHref, traceRows } from "../../../trace/read.ts";
5 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
6
7 const ID = /^[0-9A-Za-z_-]{1,64}$/;
8 const ACTIONS = ["read", "list", "compare", "share", "unshare"] as const;
9
10 export const tool: Tool = {
11 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",
13 description: "Read, list or compare crew-run traces; an owner makes or ends a redacted share link.",
14 inputSchema: {
15 type: "object",
16 properties: {
17 repo: REPO_ARG,
18 action: { type: "string", enum: [...ACTIONS] },
19 run: { type: "string" },
20 with: { type: "string", description: "compare: the other run of the same issue" },
21 },
22 required: ["repo"],
23 },
24 writes: true,
25 heldNotWhen: (args) => args["action"] !== "share" && args["action"] !== "unshare",
26 async run(ctx, user, args) {
27 const repo = repoArg(ctx, user, args);
28 if (isAnswer(repo)) return repo;
29 const run = args["run"];
30 if (run !== undefined && (typeof run !== "string" || !ID.test(run))) return bad("bad_run", "run is a run id");
31 const action = args["action"] ?? (run === undefined ? "list" : "read");
32 if (typeof action !== "string" || !ACTIONS.some((a) => a === action)) return bad("bad_action", `action is one of ${ACTIONS.join(", ")}`);
33 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) })) });
37 }
38 if (run === undefined) return bad("bad_run", "name the `run`");
39 if (action === "read") {
40 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) });
42 }
43 if (action === "compare") {
44 const other = args["with"];
45 if (typeof other !== "string" || !ID.test(other)) return bad("bad_with", "name `with`: the other run of the same issue");
46 const both = await readCompared(ctx.app, user, repo, run, other);
47 if (both === undefined) return bad("not_found", "no such pair of runs: both must be readable runs of one issue");
48 const c = compareViews(both.a, both.b);
49 return good({ rows: compareRows(both.a, both.b), table: c.rows, timeDiffMs: c.timeDiffMs ?? null, costDiffUsd: c.costDiffUsd ?? null });
50 }
51 if (action === "share") {
52 const made = shareRun(ctx.app, user, repo, run);
53 if (!made.ok) return bad(made.error, made.error === "forbidden" ? "only the repository's owner makes a share link" : "no such run here");
54 return good({ says: "Share link made: shown once, secrets redacted.", link: `${ctx.url.origin}${sharedHref(made.value.token)}` });
55 }
56 const ended = unshareRun(ctx.app, user, repo, run);
57 if (!ended.ok) return bad(ended.error, ended.error === "forbidden" ? "only the repository's owner ends a share link" : "no such run here");
58 return good({ says: ended.value.was ? "Sharing stopped: the link no longer works." : "This trace was not shared." });
59 },
60 };
src/http/routes/operations.ts +7
@@ -23,6 +23,8 @@ import { advisoriesIngest, advisoriesPage } from "../../web/pages/advisories.ts"
2323 import { resiliencePage, nightlyOutputPage } from "../../web/pages/resilience.ts";
2424 import { runRedirect } from "../../web/pages/runs.ts";
2525 import { tracePage, traceStep } from "../../web/pages/trace.ts";
26 import { traceComparePage } from "../../web/pages/trace_compare.ts";
27 import { traceShare, traceShared, traceUnshare } from "../../web/pages/trace_share.ts";
2628 import { tracesPage } from "../../web/pages/traces.ts";
2729 import { oauthCallbackUri } from "../api.ts";
2830 import { gamesRoutes } from "../games_routes.ts";
@@ -124,4 +126,9 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s
124126 router.add("GET", "/traces", tracesPage);
125127 router.add("GET", "/traces/:id", tracePage);
126128 router.add("GET", "/traces/:id/steps/:n", traceStep);
129 // Two runs of one issue side by side, and a trace shared by a link its owner made (#17995).
130 router.add("GET", "/traces/:id/compare/:other", traceComparePage);
131 router.add("POST", "/traces/:id/share", traceShare);
132 router.add("POST", "/traces/:id/unshare", traceUnshare);
133 router.add("GET", "/traces/shared/:token", traceShared);
127134 }
src/trace/compare.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * Two runs of one issue side by side (#17995), as plain rows: steps, failed steps, time, tokens,
3 * cost, outcome, each with the difference (B − A). Time is the run's own wall clock (started to
4 * finished); the cost is shown only where the viewer may see the owner's facts (`costUsd`, as the
5 * trace page's). A run's log holds no tokens, so a run with none says "not recorded" rather than 0.
6 */
7 import { stepsOf, type Step } from "./model.ts";
8 import type { App } from "../app.ts";
9 import type { Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import { readTrace, spanWords, type TraceView } from "./read.ts";
12
13 export interface CompareRow {
14 readonly label: string;
15 readonly a: string;
16 readonly b: string;
17 /** B − A in words, where both sides have the figure; otherwise empty. */
18 readonly diff: string;
19 }
20
21 export interface Comparison {
22 readonly rows: readonly CompareRow[];
23 /** B − A in numbers, undefined where a side lacks the figure (units: ms, USD). */
24 readonly timeDiffMs: number | undefined;
25 readonly costDiffUsd: number | undefined;
26 }
27
28 /** The run's wall time in ms, from its own record; undefined while it has not both ends. */
29 export function wallMs(run: { startedAt: string | null; finishedAt: string | null }): number | undefined {
30 if (run.startedAt === null || run.finishedAt === null) return undefined;
31 const ms = Date.parse(run.finishedAt) - Date.parse(run.startedAt);
32 return Number.isFinite(ms) && ms >= 0 ? ms : undefined;
33 }
34
35 const signed = (n: number, unit: (abs: number) => string): string => (n === 0 ? "same" : `${n > 0 ? "+" : "−"}${unit(Math.abs(n))}`);
36 const money = (usd: number): string => `$${usd.toFixed(2)}`;
37 const failed = (s: readonly Step[]): number => s.filter((x) => x.outcome === "error").length;
38 const tokensOf = (s: readonly Step[]): number => s.reduce((n, x) => n + x.tokensIn + x.tokensOut, 0);
39
40 export function compareViews(a: TraceView, b: TraceView): Comparison {
41 const sa = stepsOf(a.trace);
42 const sb = stepsOf(b.trace);
43 const ta = wallMs(a.run);
44 const tb = wallMs(b.run);
45 const ka = tokensOf(sa);
46 const kb = tokensOf(sb);
47 const timeDiffMs = ta === undefined || tb === undefined ? undefined : tb - ta;
48 const costDiffUsd = a.costUsd === undefined || b.costUsd === undefined ? undefined : Math.round((b.costUsd - a.costUsd) * 1e6) / 1e6;
49 const rows: CompareRow[] = [
50 { label: "Steps", a: String(sa.length), b: String(sb.length), diff: signed(sb.length - sa.length, String) },
51 { label: "Failed steps", a: String(failed(sa)), b: String(failed(sb)), diff: signed(failed(sb) - failed(sa), String) },
52 {
53 label: "Time",
54 a: ta === undefined ? "not finished" : spanWords(ta),
55 b: tb === undefined ? "not finished" : spanWords(tb),
56 diff: timeDiffMs === undefined ? "" : signed(timeDiffMs, spanWords),
57 },
58 {
59 label: "Tokens",
60 a: ka === 0 ? "not recorded" : String(ka),
61 b: kb === 0 ? "not recorded" : String(kb),
62 diff: ka === 0 || kb === 0 ? "" : signed(kb - ka, String),
63 },
64 {
65 label: "Cost",
66 a: a.costUsd === undefined ? "not shown" : money(a.costUsd),
67 b: b.costUsd === undefined ? "not shown" : money(b.costUsd),
68 diff: costDiffUsd === undefined ? "" : signed(costDiffUsd, money),
69 },
70 { label: "Outcome", a: a.run.state, b: b.run.state, diff: a.run.state === b.run.state ? "same" : "differs" },
71 ];
72 return { rows, timeDiffMs, costDiffUsd };
73 }
74
75 /** The comparison as terminal lines: the two runs, then `label: A | B (diff)` a row. */
76 export function compareRows(a: TraceView, b: TraceView): string[] {
77 const c = compareViews(a, b);
78 return [
79 `A: ${a.title} (${a.run.id})`,
80 `B: ${b.title} (${b.run.id})`,
81 ...c.rows.map((r) => `${r.label}: ${r.a} | ${r.b}${r.diff === "" ? "" : ` (${r.diff})`}`),
82 ];
83 }
84
85 /** Two runs may be compared when they are two different runs of one issue or pull. */
86 export function sameIssue(a: Pick<TraceView["run"], "id" | "issueId">, b: Pick<TraceView["run"], "id" | "issueId">): boolean {
87 return a.id !== b.id && a.issueId !== null && a.issueId === b.issueId;
88 }
89
90 export interface Compared {
91 readonly a: TraceView;
92 readonly b: TraceView;
93 readonly comparison: Comparison;
94 }
95
96 /**
97 * Both runs' traces through the one gate (`readTrace`) and their difference: `undefined` where
98 * either cannot be read or the two are not runs of one issue, so a stranger learns nothing.
99 */
100 export async function readCompared(app: App, actor: User | undefined, repo: Repo, aId: string, bId: string): Promise<Compared | undefined> {
101 const [a, b] = await Promise.all([readTrace(app, actor, repo, aId), readTrace(app, actor, repo, bId)]);
102 if (a === undefined || b === undefined || !sameIssue(a.run, b.run)) return undefined;
103 return { a, b, comparison: compareViews(a, b) };
104 }
src/trace/share.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * A trace's share link (#17995): a row per link, only the hash of its secret kept. Off until the
3 * repository's owner makes one (`actions/trace_share.ts` decides who); one live link a run, so
4 * making a new one withdraws the old; revoking stops it at the next request. Plain data in, plain
5 * data out.
6 */
7 import type { Database } from "bun:sqlite";
8 import { sha256 } from "../kernel/hash.ts";
9 import { id as newId, secret } from "../kernel/id.ts";
10
11 /** A link's secret as it arrives in a path: what `secret()` makes, nothing else. */
12 export const isShareToken = (raw: string): boolean => /^[A-Za-z0-9_-]{43}$/.test(raw);
13
14 /** Make the run's link; the secret is returned once and never kept. Any older live link ends. */
15 export function makeShare(db: Database, runId: string, userId: string, now: number): string {
16 const token = secret();
17 const at = new Date(now).toISOString();
18 db.transaction(() => {
19 db.query("UPDATE trace_share SET revoked_at = ?2 WHERE run_id = ?1 AND revoked_at IS NULL").run(runId, at);
20 db.query("INSERT INTO trace_share (id, run_id, token_hash, created_by, created_at) VALUES (?1, ?2, ?3, ?4, ?5)").run(
21 newId(now),
22 runId,
23 sha256(token),
24 userId,
25 at,
26 );
27 })();
28 return token;
29 }
30
31 /** End the run's live link; whether there was one. */
32 export function revokeShare(db: Database, runId: string, now: number): boolean {
33 return db.query("UPDATE trace_share SET revoked_at = ?2 WHERE run_id = ?1 AND revoked_at IS NULL").run(runId, new Date(now).toISOString()).changes > 0;
34 }
35
36 /** Whether the run has a live link. */
37 export function isShared(db: Database, runId: string): boolean {
38 return db.query("SELECT 1 FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(runId) !== null;
39 }
40
41 /** The run a live link opens, or undefined for an unknown or revoked one. */
42 export function sharedRunId(db: Database, token: string): string | undefined {
43 if (!isShareToken(token)) return undefined;
44 return db.query<{ run_id: string }, [string]>("SELECT run_id FROM trace_share WHERE token_hash = ?1 AND revoked_at IS NULL").get(sha256(token))?.run_id ?? undefined;
45 }
src/trace/shared.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * A run's trace as a stranger holding its share link reads it (#17995). Nothing here asks who the
3 * reader is: the link is the whole right, and it is gone when revoked (`sharedRunId`). Everything
4 * served passes the forge's own redaction (`redactHeld`: credential shapes and the values a run was
5 * granted) before it is parsed, so no step, title or raw line can carry what the log's writer
6 * missed. The run's cost, its repository's links and its people are not part of it.
7 */
8 import type { App } from "../app.ts";
9 import { getIssueById } from "../core/issues.ts";
10 import { getRun } from "../core/runs.ts";
11 import { RateLimiter } from "../core/ratelimit.ts";
12 import { sha256 } from "../kernel/hash.ts";
13 import { redactHeld } from "../kernel/log.ts";
14 import { readRunLog, readRunTimes } from "../runs/log.ts";
15 import { restoreRunLog } from "../runs/archive.ts";
16 import { stepsOf } from "./model.ts";
17 import { parseRunLog } from "./run_log.ts";
18 import { sharedRunId } from "./share.ts";
19
20 /** The most steps and raw lines a step the shared page carries; a longer trace says so. */
21 export const SHARED_STEPS_MAX = 2_000;
22 export const SHARED_RAW_MAX = 200;
23
24 export interface SharedStep {
25 readonly n: number;
26 readonly failed: boolean;
27 readonly kind: "model" | "tool" | "subagent";
28 readonly line: string;
29 readonly took: { startMs: number; endMs: number } | undefined;
30 readonly raw: readonly string[];
31 }
32
33 export interface SharedTrace {
34 readonly title: string;
35 readonly state: string;
36 readonly timed: boolean;
37 readonly steps: readonly SharedStep[];
38 /** Steps or lines were left out for size, or the log's start was cut. */
39 readonly cut: boolean;
40 }
41
42 /** How long a redacted trace is served from memory, and how many a forge holds at once. */
43 const KEPT_MS = 30_000;
outdated

Medium, denial of service. Any holder of a link (no sign-in) makes the forge restore, read and parse the whole run log and redact every line on every request, and there is no rate limit by address. Cache the redacted SharedTrace by run id (drop it on revoke or a new link), and rate-limit this route by socket address.

44 const KEPT_MAX = 32;
45 /** Requests a minute from one address; the link is the right, the address is the bound on cost. */
46 const PER_ADDRESS = 60;
47
48 interface Kept {
49 readonly at: number;
50 readonly trace: SharedTrace;
51 }
52 /** Per forge, so a test's forge never shares with another's. */
53 const kept = new WeakMap<App, Map<string, Kept>>();
54 const limiters = new WeakMap<App, RateLimiter>();
55
56 /** Whether this address may open another shared trace now, else the seconds to wait. */
57 export function sharedTurn(app: App, address: string): { allowed: true } | { allowed: false; retryAfter: number } {
58 let limiter = limiters.get(app);
59 if (limiter === undefined) {
60 limiter = new RateLimiter({ perMinute: PER_ADDRESS, adminPerMinute: PER_ADDRESS, enabled: true, maxKeys: 10_000 });
61 limiters.set(app, limiter);
62 }
63 const v = limiter.take(address, "ro");
64 return v.allowed ? { allowed: true } : { allowed: false, retryAfter: v.retryAfter };
65 }
66
67 /**
68 * The trace a live link opens. The link is checked on every call (a revoked one is gone at once);
69 * the redacted result is kept for `KEPT_MS` under the hash of the secret, so a new link, which has
70 * a new secret, never reads the old one's, and a stranger's repeats cost one read, not many.
71 */
72 export async function readShared(app: App, token: string): Promise<SharedTrace | undefined> {
73 const runId = sharedRunId(app.db, token);
74 if (runId === undefined) return undefined;
75 let held = kept.get(app);
76 if (held === undefined) {
77 held = new Map();
78 kept.set(app, held);
79 }
80 const key = sha256(token);
81 const hit = held.get(key);
82 if (hit !== undefined && Date.now() - hit.at < KEPT_MS) return hit.trace;
83 const trace = await buildShared(app, runId);
84 if (trace === undefined) return undefined;
85 held.delete(key);
86 held.set(key, { at: Date.now(), trace });
87 while (held.size > KEPT_MAX) held.delete(held.keys().next().value as string);
88 return trace;
89 }
90
91 async function buildShared(app: App, runId: string): Promise<SharedTrace | undefined> {
92 const run = getRun(app.db, runId);
93 if (run === undefined) return undefined;
94 await restoreRunLog(app.db, app.config.dataDir, run.id);
95 const { lines, truncated } = readRunLog(app.config.dataDir, run.id);
96 const issue = run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
97 const title = redactHeld(issue?.title ?? (run.summary === "" ? `${run.kind} run` : run.summary));
98 const { trace, spans, timed } = parseRunLog(run.id, title, lines, readRunTimes(app.config.dataDir, run.id, lines.length));
99 const all = stepsOf(trace);
100 let cut = truncated || all.length > SHARED_STEPS_MAX;
101 const steps = all.slice(0, SHARED_STEPS_MAX).map((s, i): SharedStep => {
102 const span = spans[i]!;
103 const raw = lines.slice(span.from, span.to).map(redactHeld);
104 if (raw.length > SHARED_RAW_MAX) cut = true;
105 return {
106 n: i + 1,
107 failed: s.outcome === "error",
108 kind: s.kind,
109 line: redactHeld(s.line),
110 took: timed ? { startMs: s.startMs, endMs: s.endMs } : undefined,
111 raw: raw.slice(0, SHARED_RAW_MAX),
112 };
113 });
114 return { title, state: run.state, timed, steps, cut };
115 }
src/tui/screens/trace.ts +50 −2
@@ -5,6 +5,10 @@
55 */
66
77 import type { Repo } from "../../core/repos.ts";
8 import { isShared } from "../../trace/share.ts";
9 import { sharedHref, shareRun, unshareRun } from "../../actions/trace_share.ts";
10 import { otherRunsOfIssue } from "../../core/runs.ts";
11 import { compareRows, readCompared } from "../../trace/compare.ts";
812 import { readTrace, traceHref, traceRows } from "../../trace/read.ts";
913 import type { Ctx, Screen } from "../app/app.ts";
1014 import { binding } from "../app/keys.ts";
@@ -14,17 +18,34 @@ import { truncate } from "../term/width.ts";
1418 import { emptyState } from "../ui/widgets.ts";
1519 import { Scroll, openOnWeb } from "./common.ts";
1620
17 export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string): Screen {
21 /**
22 * `versus`: the other run of the issue to read against, as `compareRows` (the page's table); `c`
23 * opens the newest other run of the issue. `s` makes the share link (owner only, shown once), `x`
24 * ends it.
25 */
26 export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string, versus?: string): Screen {
1827 const scroll = new Scroll();
1928 let rows: string[] | undefined;
2029 let loaded = false;
30 let issueId: string | null = null;
31 let shared = false;
32 let confirm = false;
2133 return {
2234 title: "Trace",
2335 here: () => ({ repo, run: runId }),
24 keys: [binding(["j", "k"], "scroll"), binding(["pgup", "pgdn"], "page"), binding(["o"], "open on the web")],
36 keys: [binding(["j", "k"], "scroll"), binding(["pgup", "pgdn"], "page"), binding(["o"], "open on the web"), binding(["c"], "compare"), binding(["s"], "share"), binding(["x"], "stop sharing")],
2537 async load() {
38 if (versus !== undefined) {
39 const both = await readCompared(f.app, f.user, repo, runId, versus);
40 rows = both === undefined ? undefined : compareRows(both.a, both.b);
41 loaded = true;
42 ctx.invalidate();
43 return;
44 }
2645 const view = await readTrace(f.app, f.user, repo, runId);
2746 rows = view === undefined ? undefined : traceRows(view);
47 issueId = view?.run.issueId ?? null;
48 shared = isShared(f.app.db, runId);
2849 loaded = true;
2950 ctx.invalidate();
3051 },
@@ -46,6 +67,33 @@ export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string): Sc
4667 openOnWeb(f, ctx, traceHref(runId), "the run's trace");
4768 return true;
4869 }
70 if (e.ctrl || e.alt) return false;
71 if (e.key !== "s") confirm = false;
72 if (e.key === "c" && versus === undefined && issueId !== null) {
73 const other = otherRunsOfIssue(f.app.db, issueId, runId, 1)[0];
outdated

Medium. s mints a new link and silently ends the live one, no confirmation. The web and MCP doors ask first (MCP is held; the page shows the state). Require a second press or a confirm step when isShared is true. Also s/x stay live on the compare screen (versus set), where the key acts on a run the screen is not showing as one trace; restrict them to the single-trace screen. No test covers this door; add one for c, s, x and the owner refusal.

74 if (other === undefined) ctx.toast("no other run of this issue to compare with", "attn");
75 else ctx.push(traceScreen(f, ctx, repo, runId, other.id));
76 return true;
77 }
78 if ((e.key === "s" || e.key === "x") && versus === undefined) {
79 // A live link already handed out ends when another is made: the second press says yes.
80 if (e.key === "s" && shared && !confirm) {
81 confirm = true;
82 ctx.toast("a share link is live: press s again to replace it, and end the old one", "attn");
83 return true;
84 }
85 confirm = false;
86 const done = e.key === "s" ? shareRun(f.app, f.user, repo, runId) : unshareRun(f.app, f.user, repo, runId);
87 if (!done.ok) ctx.toast(done.error === "forbidden" ? "only the repository's owner shares a trace" : "that could not be done", "danger");
88 else if ("token" in done.value) {
89 shared = true;
90 openOnWeb(f, ctx, sharedHref(done.value.token), "the share link (shown once)");
91 } else {
92 shared = false;
93 ctx.toast(done.value.was ? "sharing stopped: the link no longer works" : "this trace was not shared", "success");
94 }
95 return true;
96 }
4997 if (rows === undefined) return false;
5098 const took = scroll.key(e, rows.length);
5199 if (took) ctx.invalidate();
src/web/pages/trace.ts +12 −4
@@ -7,7 +7,8 @@
77 */
88 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
99 import { canRead, getRepoById, type Repo } from "../../core/repos.ts";
10 import { getRun } from "../../core/runs.ts";
10 import { getRun, otherRunsOfIssue } from "../../core/runs.ts";
11 import { sharedNow } from "../../actions/trace_share.ts";
1112 import type { Ctx } from "../../http/context.ts";
1213 import { securityFloor } from "../../http/respond.ts";
1314 import { branchesOf, stepNumber } from "../../trace/run_log.ts";
@@ -92,7 +93,7 @@ function strip(steps: readonly Step[], timed: boolean): Html {
9293 return html`<svg class="trace-strip" viewBox="0 0 1000 28" preserveAspectRatio="none" role="group" aria-label="${timed ? `Steps over ${spanWords(whole)}` : "Steps in order"}">${out}</svg>`;
9394 }
9495
95 function body(view: TraceView): Html {
96 function body(view: TraceView, others: readonly { id: string; title: string }[], shared: boolean | undefined): Html {
9697 const steps = stepsInView(view);
9798 const total = steps.length;
9899 const base = traceHref(view.run.id);
@@ -118,6 +119,11 @@ function body(view: TraceView): Html {
118119 </dl>
119120 <nav class="bar small" id="trace-links" aria-label="Where this run went">${view.links.map((l) => html`<a href="${l.href}">${l.label}</a>`)}<a href="/traces">All traces</a></nav>
120121 ${changed === undefined ? null : html`<p id="trace-changed"><strong>What it changed:</strong> ${changed}. <a href="${view.links.find((l) => l.label.startsWith("Pull"))?.href ?? "#"}">Read the diff on the pull</a>.</p>`}
122 ${others.length === 0 ? null : html`<nav class="bar small" id="trace-compare" aria-label="Compare with another run of this issue"><span class="muted">Compare with</span>${others.map((o) => html`<a href="${traceHref(view.run.id)}/compare/${o.id}">${o.title}</a>`)}</nav>`}
outdated

Principle 7: the compare links are a run-on paragraph of anchors separated by trailing spaces. Make it a short list of rows (or a nav.bar as the line above does), and use the actual run date or title rather than the last six characters of an id.

123 ${shared === undefined ? null : html`<form method="post" class="bar small" id="trace-share" action="${traceHref(view.run.id)}/${shared ? "unshare" : "share"}">
124 <span class="muted">${shared ? "A share link is live: anyone holding it reads this trace, secrets redacted." : "Not shared. A share link lets anyone holding it read this trace, secrets redacted."}</span>
125 <button type="submit">${shared ? "Stop sharing" : "Make a share link"}</button>
126 </form>`}
121127 ${view.truncated ? html`<p class="small muted" id="trace-cut">The start of the log was cut, so steps count from the cut.</p>` : null}
122128 ${total === 0 ? html`<p class="muted" id="trace-empty">This run wrote no steps.</p>` : html`${strip(steps, timed)}
123129 <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${rows}</div>
@@ -125,7 +131,7 @@ function body(view: TraceView): Html {
125131 }
126132
127133 /** The repository and run `:id` names, when the viewer may read the repository. */
128 function repoOfRun(ctx: Ctx): { repo: Repo; id: string } | undefined {
134 export function repoOfRun(ctx: Ctx): { repo: Repo; id: string } | undefined {
129135 const id = ctx.params.id ?? "";
130136 const run = /^[0-9A-Za-z_-]{1,64}$/.test(id) ? getRun(ctx.app.db, id) : undefined;
131137 const repo = run === undefined ? undefined : getRepoById(ctx.app.db, run.repoId);
@@ -139,12 +145,14 @@ export async function tracePage(ctx: Ctx): Promise<Response> {
139145 if (found === undefined) return notFoundPage(ctx);
140146 const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id);
141147 if (view === undefined) return notFoundPage(ctx);
148 const others = view.run.issueId === null ? [] : otherRunsOfIssue(ctx.app.db, view.run.issueId, view.run.id, 10).map((r) => ({ id: r.id, title: `${r.model === "" ? r.kind : r.model} · ${r.state} · ${r.createdAt.slice(0, 16).replace("T", " ")} UTC` }));
149 const shared = sharedNow(ctx.app, ctx.auth.user, found.repo, found.id);
142150 return page({
143151 ctx,
144152 title: `Trace · ${view.title}`,
145153 crumbs: crumbsFor(found.repo),
146154 palette: repoPalette(ctx, found.repo),
147 body: body(view),
155 body: body(view, others, shared),
148156 styleCss: TRACE_CSS,
149157 scriptJs: `${behaviorsJs}\n${TRACE_JS}`,
150158 });
src/web/pages/trace_compare.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * `/traces/:id/compare/:other` (#17995): two runs of one issue side by side, as a table: steps,
3 * failed steps, time, tokens, cost and outcome, with B − A beside each. Read through the trace's
4 * own gate (`readCompared`); runs of two different issues, or one the viewer cannot read, are the
5 * not-found a missing run gets. The terminal reads the same rows (`compareRows`).
6 */
7 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
8 import type { Ctx } from "../../http/context.ts";
9 import { readCompared } from "../../trace/compare.ts";
10 import { traceHref } from "../../trace/read.ts";
11 import { crumbsFor, notFoundPage, pageHead, repoPalette } from "../chrome.ts";
12 import { html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { repoOfRun } from "./trace.ts";
15
16 const ID = /^[0-9A-Za-z_-]{1,64}$/;
17
18 // GET /traces/:id/compare/:other
19 export async function traceComparePage(ctx: Ctx): Promise<Response> {
20 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
21 const found = repoOfRun(ctx);
22 const other = ctx.params.other ?? "";
23 if (found === undefined || !ID.test(other)) return notFoundPage(ctx);
24 const both = await readCompared(ctx.app, ctx.auth.user, found.repo, found.id, other);
25 if (both === undefined) return notFoundPage(ctx);
26 const { a, b, comparison } = both;
27 return page({
28 ctx,
29 title: `Compare · ${a.title}`,
30 crumbs: crumbsFor(found.repo),
31 palette: repoPalette(ctx, found.repo),
32 body: html`${pageHead(html`Compare: ${a.title}`, { sub: "Two runs of one issue side by side. Difference is B − A." })}
33 <table class="table" id="trace-compare-table">
34 <caption class="visually-hidden">Run A and run B</caption>
35 <thead><tr><th scope="col"></th><th scope="col"><a href="${traceHref(a.run.id)}">A: ${a.run.model === "" ? a.run.kind : a.run.model}</a></th><th scope="col"><a href="${traceHref(b.run.id)}">B: ${b.run.model === "" ? b.run.kind : b.run.model}</a></th><th scope="col">B − A</th></tr></thead>
36 <tbody>${comparison.rows.map((r) => html`<tr><th scope="row">${r.label}</th><td>${r.a}</td><td>${r.b}</td><td>${r.diff}</td></tr>`)}</tbody>
37 </table>`,
outdated

Principle 1 and 8: the sub line already says 'Difference is B − A' and the column head says B − A; the notes paragraph then explains time, tokens and cost again. Keep the one sentence and drop the notes paragraph (the cells already say 'not recorded' and 'not shown').

38 });
39 }
src/web/pages/trace_share.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * A trace's share link (#17995). `POST /traces/:id/share` and `/unshare` are the owner's
3 * (same-origin form, `shareRun`/`unshareRun`); the link's secret is shown once, on the answer, and
4 * never kept. `GET /traces/shared/:token` serves the trace redacted to anyone holding a live link
5 * (`readShared`), as plain server-rendered steps with no script; a revoked or unknown link is the
6 * not-found a missing page gets. The terminal does the same (`src/tui/screens/trace.ts`).
7 */
8 import { sharedHref, shareRun, unshareRun } from "../../actions/trace_share.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { spanWords, traceHref } from "../../trace/read.ts";
11 import { readShared, sharedTurn } from "../../trace/shared.ts";
12 import { crumbsFor, forbiddenPage, notFoundPage, pageHead } from "../chrome.ts";
13 import { readForm } from "../form.ts";
14 import { html } from "../html.ts";
15 import { flashTo, page } from "../layout.ts";
16 import { field } from "../ui.ts";
17 import { clientAddress } from "../../http/peer.ts";
18 import { tryAgain } from "../../http/respond.ts";
19 import { repoOfRun } from "./trace.ts";
20
21 const noStore = (r: Response): Response => {
22 r.headers.set("cache-control", "private, no-store");
23 return r;
24 };
25
26 // POST /traces/:id/share
27 export async function traceShare(ctx: Ctx): Promise<Response> {
28 const form = await readForm(ctx, "rw");
29 if (form instanceof Response) return form;
30 const found = repoOfRun(ctx);
31 if (found === undefined) return notFoundPage(ctx);
32 const made = shareRun(ctx.app, ctx.auth.user, found.repo, found.id);
33 if (!made.ok) return made.error === "forbidden" || made.error === "unauthorized" ? forbiddenPage(ctx, "Only the repository's owner makes a share link.") : notFoundPage(ctx);
34 const url = `${ctx.app.config.url?.replace(/\/+$/, "") ?? ctx.url.origin}${sharedHref(made.value.token)}`;
35 return noStore(
36 page({
outdated

Principles 2/3: a hand-rolled <input size="70"> is wider than a phone and shifts layout. Use the shared field component, full width, with mono, and put the page's single sentence in the head; the sub line plus a trailing sentence says the same twice.

37 ctx,
38 title: "Share link",
39 crumbs: crumbsFor(found.repo),
40 body: html`${pageHead("Share link made", { sub: "Anyone holding it reads this trace with secrets redacted. It is shown once; making another ends this one." })}
41 ${field({ name: "share-url", id: "share-url", label: "Share link", labelHidden: true, value: url, readonly: true, mono: true })}
42 <p><a href="${traceHref(found.id)}">Back to the trace</a>, where you can stop sharing.</p>`,
43 }),
44 );
45 }
46
47 // POST /traces/:id/unshare
48 export async function traceUnshare(ctx: Ctx): Promise<Response> {
49 const form = await readForm(ctx, "rw");
50 if (form instanceof Response) return form;
51 const found = repoOfRun(ctx);
52 if (found === undefined) return notFoundPage(ctx);
53 const ended = unshareRun(ctx.app, ctx.auth.user, found.repo, found.id);
54 if (!ended.ok) return ended.error === "not_found" ? notFoundPage(ctx) : forbiddenPage(ctx, "Only the repository's owner ends a share link.");
55 return flashTo(ctx, traceHref(found.id), { message: ended.value.was ? "Sharing stopped: the link no longer works." : "This trace was not shared." });
56 }
57
58 // GET /traces/shared/:token
59 export async function traceShared(ctx: Ctx): Promise<Response> {
60 const turn = sharedTurn(ctx.app, clientAddress(ctx.request));
61 if (!turn.allowed) return tryAgain("too_many_requests", 429, "too many shared traces opened from this address: wait and open again", turn.retryAfter);
62 const view = await readShared(ctx.app, ctx.params.token ?? "");
63 if (view === undefined) return notFoundPage(ctx, { signedOut: true });
64 const last = view.steps[view.steps.length - 1];
65 return noStore(
66 page({
67 ctx,
68 title: `Trace · ${view.title}`,
69 body: html`${pageHead(html`Trace: ${view.title}`, { sub: "Shared read-only. Secrets are redacted." })}
70 <dl class="row-facts" id="shared-total">
71 <div><dt>Steps</dt><dd>${String(view.steps.length)}</dd></div>
72 <div><dt>Failed</dt><dd>${String(view.steps.filter((s) => s.failed).length)}</dd></div>
73 ${view.timed && last?.took !== undefined ? html`<div><dt>Time</dt><dd>${spanWords(last.took.endMs)}</dd></div>` : null}
74 <div><dt>State</dt><dd>${view.state}</dd></div>
75 </dl>
76 ${view.cut ? html`<p class="small muted" id="shared-cut">Part of this trace was left out for size.</p>` : null}
77 <div id="shared-steps">${view.steps.map(
78 (s) => html`<details class="trace-step" id="step-${String(s.n)}"><summary><span class="mono">${String(s.n)}/${String(view.steps.length)}</span> ${s.failed ? "✗ " : ""}${s.line}${s.took === undefined ? null : html` <span class="small muted">(${spanWords(s.took.endMs - s.took.startMs)}, at ${spanWords(s.took.endMs)})</span>`}</summary><pre class="mono">${s.raw.join("\n")}</pre></details>`,
79 )}</div>`,
80 }),
81 );
82 }
test/budgets/unfixtured/traces-id-compare-other.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/traces/:id/compare/:other",
3 "why": "no fixture holds the id this route needs"
4 }
test/budgets/unfixtured/traces-shared-token.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/traces/shared/:token",
3 "why": "no fixture holds the id this route needs"
4 }
test/conversation-ask.test.ts +2
@@ -13,6 +13,8 @@ import { TOOLS } from "../src/http/mcp/tools.ts";
1313
1414 /** Every form, said: a tool, a call of it, and the sentence the person reads. */
1515 const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
16 ["trace", { repo: "marin/cakes", run: "r1", action: "share" }, "Make a redacted share link for the trace of run r1 in marin/cakes."],
17 ["trace", { repo: "marin/cakes", run: "r1", action: "unshare" }, "Stop sharing the trace of run r1 in marin/cakes."],
1618 ["cut_wave", { repo: "marin/cakes" }, "Cut the next wave of marin/cakes as a draft pull."],
1719 [
1820 "tell",
test/hot-reads-indexed.test.ts +5 −1
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
77 import { listEvents } from "../src/core/events.ts";
8 import { lastPullCursor, listPullRuns, queuedApart } from "../src/core/runs.ts";
8 import { lastPullCursor, listPullRuns, otherRunsOfIssue, queuedApart } from "../src/core/runs.ts";
99 import { closedByReview, reviewedClosed } from "../src/core/gate_hold.ts";
1010 import { askToLiveByPillar } from "../src/core/pillars.ts";
1111
@@ -115,3 +115,7 @@ test("the crew's lessons read the week's failed checks by finish time from an in
115115 expect(lines.join("\n")).toMatch(/run_(kind|failed)_finished/);
116116 noScan(lines);
117117 });
118
119 test("the other runs of an issue (a trace's comparison) walk the issue's run index (#17995)", () => {
120 noScan(plans(() => otherRunsOfIssue(app.db, "x", "y")));
121 });
test/mcp-forge-protocol.test.ts +1
@@ -175,6 +175,7 @@ describe("the forge over MCP: protocol", () => {
175175 "profile",
176176 "mint_invite",
177177 "tokens",
178 "trace",
178179 "invites",
179180 "account_role",
180181 "account_suspend",
test/mixed-actions-held.test.ts +1
@@ -63,6 +63,7 @@ const MIXED: Readonly<
6363 .map((action) => ({ action, id: "o1" }))
6464 .concat([{ action: "hosts", id: "o1" }]),
6565 },
66 trace: { key: "action", reads: [{ repo: "o/r", action: "list" }, { repo: "o/r", run: "r1", action: "read" }, { repo: "o/r", run: "r1", with: "r2", action: "compare" }] },
6667 sessions: { key: "action", reads: [{ action: "list" }] },
6768 ssh_keys: { key: "action", reads: [{ action: "list" }] },
6869 };
test/no-polling.test.ts +2
@@ -356,6 +356,8 @@ const NOT_WALKED: Record<string, string> = {
356356 "/runs/:id": "the seed creates no run",
357357 "/traces/:id": "the seed creates no crew run with a log",
358358 "/traces/:id/steps/:n": "the seed creates no crew run with a log",
359 "/traces/:id/compare/:other": "the seed creates no crew run with a log",
360 "/traces/shared/:token": "the seed creates no crew run with a log",
359361 "/signin/access/:token": "needs a one-time access link an admin minted",
360362 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
361363 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/open-routes-floor.test.ts +1 −1
@@ -36,7 +36,7 @@ const SLOW_MS = 200 * 5;
3636 * issue, or a well-formed value nothing seeds.
3737 */
3838 const FILL: Readonly<Record<string, string>> = {
39 owner: "alice", username: "alice", user: "alice", org: "alice", scope: "alice",
39 owner: "alice", other: "2", username: "alice", user: "alice", org: "alice", scope: "alice",
4040 name: "notes", repo: "notes", number: "1", n: "1", id: "1", job: "1",
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
test/security-floor-routes.test.ts +2
@@ -95,6 +95,8 @@ const UNSEEDED: Record<string, string> = {
9595 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
9696 "/traces/:id": "needs a crew run with a log, which the seed has none of",
9797 "/traces/:id/steps/:n": "needs a crew run with a log, which the seed has none of",
98 "/traces/:id/compare/:other": "needs a crew run with a log, which the seed has none of",
99 "/traces/shared/:token": "needs a crew run with a log, which the seed has none of",
98100 "/pricing/orders/:id": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
99101 "/pricing/orders/:id/receipt.html": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
100102 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/trace-share.test.ts added +227
@@ -0,0 +1,227 @@
1 /**
2 * Compare two runs of one issue, and share a trace by a link that redacts and can be revoked
3 * (#17995).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { appendFileSync } from "node:fs";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { shareRun, unshareRun } from "../src/actions/trace_share.ts";
14 import { createRun, finishRun, otherRunsOfIssue } from "../src/core/runs.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { appendRunLog, flushRunLogs, runLogPath } from "../src/runs/log.ts";
19 import { compareRows, compareViews, readCompared } from "../src/trace/compare.ts";
20 import { readTrace } from "../src/trace/read.ts";
21 import { isShared, isShareToken } from "../src/trace/share.ts";
22 import { readShared, sharedTurn } from "../src/trace/shared.ts";
23 import { traceScreen } from "../src/tui/screens/trace.ts";
24 import { theme } from "../src/tui/ui/theme.ts";
25 import type { Ctx } from "../src/tui/app/app.ts";
26 import type { Session } from "../src/tui/session.ts";
27 import type { Repo } from "../src/core/repos.ts";
28 import type { User } from "../src/core/users.ts";
29 import { seedAdmin } from "./helpers/admin.ts";
30
31 let dir = "";
32 let app: App, servers: Servers, bearer = "", other = "";
33 let alice: User;
34 let repo: Repo;
35 let packed = "", explored = "", elsewhere = "";
36 const PLANTED = "ghp_0123456789abcdefghijABCDEFGHIJ0123";
37
38 const get = (path: string, token = bearer) =>
39 fetch(`${servers.url}${path}`, { headers: token === "" ? {} : { authorization: `Bearer ${token}` } });
40 const post = (path: string, token = bearer) =>
41 fetch(`${servers.url}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}` }, redirect: "manual" });
42
43 /** A finished agent run on `issueId` taking `seconds` and costing `usd`. */
44 function aRun(issueId: string | undefined, lines: string[], seconds: number, usd: number, model: string): string {
45 const run = createRun(app.db, { repoId: repo.id, kind: "agent", ...(issueId === undefined ? {} : { issueId }), actorId: alice.id });
46 for (const l of lines) appendRunLog(dir, run.id, l);
47 finishRun(app.db, run.id, { state: "ok", summary: "done" });
48 const start = Date.parse("2026-12-01T10:00:00Z");
49 app.db
50 .query("UPDATE run SET started_at = ?2, finished_at = ?3, cost_usd = ?4, model = ?5 WHERE id = ?1")
51 .run(run.id, new Date(start).toISOString(), new Date(start + seconds * 1000).toISOString(), usd, model);
52 return run.id;
53 }
54
55 beforeAll(async () => {
56 dir = await mkdtemp(join(tmpdir(), "forge-trace-share-"));
57 app = createApp({ dataDir: dir, port: 0 });
58 servers = await serve(app);
59 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
60 if (!admin.ok) throw new Error(admin.error);
61 alice = admin.value;
62 const made = await createRepo(app, alice, { name: "notes", visibility: "public", description: "" });
63 if (!made.ok) throw new Error(String(made.error));
64 repo = made.value;
65 const issue = openIssue(app, alice, repo, { title: "Add a footer", body: "" });
66 if (!issue.ok) throw new Error(String(issue.error));
67 const second = openIssue(app, alice, repo, { title: "Add a header", body: "" });
68 if (!second.ok) throw new Error(String(second.error));
69 packed = aRun(issue.value.id, ["→ Read README.md", "→ Edit footer.txt"], 90, 0.25, "packed");
70 explored = aRun(issue.value.id, ["Looking around.", "→ Read a.ts", "→ Read b.ts", "→ Bash ls", "! exit 1", "→ Edit footer.txt"], 330, 1.75, "explored");
71 elsewhere = aRun(second.value.id, ["→ Read x"], 10, 0.01, "other");
72 // A log that holds a secret its writer never saw: written to the file directly.
73 other = aRun(issue.value.id, ["→ Read README.md"], 5, 0.02, "leaky");
74 appendFileSync(runLogPath(dir, other), `→ Bash curl -H "Authorization: token ${PLANTED}" https://example.com\n`);
75 flushRunLogs();
76 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
77 method: "POST",
78 headers: { "content-type": "application/json" },
79 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
80 });
81 bearer = ((await minted.json()) as { token: string }).token;
82 }, 30_000);
83
84 afterAll(async () => {
85 servers.stop();
86 app.close();
87 await rm(dir, { recursive: true, force: true });
88 });
89
90 test("two runs of one issue differ by hand-checked cost and time, and the outcome is stated", async () => {
91 const both = await readCompared(app, alice, repo, packed, explored);
92 expect(both).toBeDefined();
93 const c = compareViews(both!.a, both!.b);
94 // 330 s − 90 s = 240 s = 240,000 ms; $1.75 − $0.25 = $1.50.
95 expect(c.timeDiffMs).toBe(240_000);
96 expect(c.costDiffUsd).toBe(1.5);
97 const row = (label: string) => c.rows.find((r) => r.label === label)!;
98 expect(row("Time")).toEqual({ label: "Time", a: "1m 30s", b: "5m 30s", diff: "+4m 00s" });
99 expect(row("Cost")).toEqual({ label: "Cost", a: "$0.25", b: "$1.75", diff: "+$1.50" });
100 // 2 steps against 6 (words, three tools, a failure, an edit).
101 expect(row("Steps").diff).toBe("+4");
102 expect(row("Failed steps").diff).toBe("+1");
103 expect(row("Tokens").a).toBe("not recorded");
104 expect(row("Outcome").diff).toBe("same");
105 expect(compareRows(both!.a, both!.b).some((l) => l.startsWith("Cost: $0.25 | $1.75 (+$1.50)"))).toBe(true);
106 });
107
108 test("runs of two different issues, or one run with itself, are not compared", async () => {
109 expect(await readCompared(app, alice, repo, packed, elsewhere)).toBeUndefined();
110 expect(await readCompared(app, alice, repo, packed, packed)).toBeUndefined();
111 expect((await get(`/traces/${packed}/compare/${elsewhere}`)).status).toBe(404);
112 expect(otherRunsOfIssue(app.db, (await readTrace(app, alice, repo, packed))!.run.issueId!, packed).map((r) => r.id)).not.toContain(elsewhere);
113 });
114
115 test("the compare page shows the table, and the trace page offers it", async () => {
116 const page = await (await get(`/traces/${packed}/compare/${explored}`)).text();
117 expect(page).toContain("+$1.50");
118 expect(page).toContain("+4m 00s");
119 expect(await (await get(`/traces/${packed}`)).text()).toContain(`/traces/${packed}/compare/${explored}`);
120 // A stranger may not read the run's log, so the comparison is the not-found a missing run gets.
121 expect((await get(`/traces/${packed}/compare/${explored}`, "")).status).toBe(404);
122 });
123
124 test("a share link is off by default, made by the owner, redacts a planted token, and stops when revoked", async () => {
125 expect(await (await get(`/traces/${other}`)).text()).toContain("Make a share link");
126 expect((await get("/traces/shared/" + "a".repeat(43), "")).status).toBe(404);
127
128 const made = await post(`/traces/${other}/share`);
129 expect(made.status).toBe(200);
130 const html = await made.text();
131 const link = /value="[^"]*(\/traces\/shared\/[A-Za-z0-9_-]{43})"/.exec(html)?.[1];
132 expect(link).toBeDefined();
133
134 // Anyone holding it, with no credentials at all.
135 const shared = await get(link!, "");
136 expect(shared.status).toBe(200);
137 expect(shared.headers.get("cache-control")).toContain("no-store");
138 expect(shared.headers.get("x-content-type-options")).toBe("nosniff");
139 const text = await shared.text();
140 expect(text).toContain("README.md");
141 expect(text).toContain("[redacted]");
142 expect(text).not.toContain(PLANTED);
143 expect(text).not.toContain("$0.02");
144
145 // The file itself still holds it: redaction is on the way out.
146 expect(await Bun.file(runLogPath(dir, other)).text()).toContain(PLANTED);
147
148 const ended = await post(`/traces/${other}/unshare`);
149 expect(ended.status).toBe(303);
150 expect((await get(link!, "")).status).toBe(404);
151 });
152
153 test("only the repository's owner makes a share link, and a new link withdraws the old", async () => {
154 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bobby", email: "[email protected]", password: "correct-horse-battery" });
155 if (!bob.ok) throw new Error(bob.error);
156 const theirs = createToken(app.db, bob.value.id, "t", "rw").token;
157 expect((await post(`/traces/${packed}/share`, theirs)).status).toBeGreaterThanOrEqual(403);
158 expect(shareRun(app, bob.value, repo, packed).ok).toBe(false);
159 expect(shareRun(app, undefined, repo, packed).ok).toBe(false);
160 expect(unshareRun(app, bob.value, repo, packed).ok).toBe(false);
161 // A cross-site form is refused before anything is made.
162 const cross = await fetch(`${servers.url}/traces/${packed}/share`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, origin: "https://evil.example" } });
163 expect(cross.status).toBe(403);
164
165 const one = shareRun(app, alice, repo, packed);
166 const two = shareRun(app, alice, repo, packed);
167 if (!one.ok || !two.ok) throw new Error("not made");
168 expect(isShareToken(one.value.token)).toBe(true);
169 expect((await get(`/traces/shared/${one.value.token}`, "")).status).toBe(404);
170 expect((await get(`/traces/shared/${two.value.token}`, "")).status).toBe(200);
171 expect(unshareRun(app, alice, repo, packed)).toEqual({ ok: true, value: { was: true } });
172 expect(unshareRun(app, alice, repo, packed)).toEqual({ ok: true, value: { was: false } });
173 });
174
175 // The terminal door (`src/tui/screens/trace.ts`): c, s, x, and the owner's refusal.
176 function tui(user: User, runId: string, versus?: string) {
177 const toasts: string[] = [];
178 const pushed: unknown[] = [];
179 const ctx = { theme: theme("dark"), invalidate() {}, toast: (t: string) => toasts.push(t), push: (s: unknown) => pushed.push(s) } as unknown as Ctx;
180 const f = { app, db: app.db, user } as unknown as Session;
181 const screen = traceScreen(f, ctx, repo, runId, versus);
182 return { screen, toasts, pushed, send: (k: string) => screen.key({ type: "key", key: k, ctrl: false, alt: false, shift: false }) };
183 }
184
185 test("terminal: s asks before replacing a live link, x ends it, only the owner shares, compare screen has neither", async () => {
186 const t = tui(alice, packed);
187 await t.screen.load!(new AbortController().signal);
188 t.send("s");
189 expect(isShared(app.db, packed)).toBe(true);
190 const live = app.db.query<{ n: number }, [string]>("SELECT COUNT(*) n FROM trace_share WHERE run_id = ?1").get(packed)!.n;
191 t.send("s");
192 expect(t.toasts.at(-1)).toContain("press s again");
193 expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) n FROM trace_share WHERE run_id = ?1").get(packed)!.n).toBe(live);
194 t.send("s");
195 expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) n FROM trace_share WHERE run_id = ?1").get(packed)!.n).toBe(live + 1);
196 t.send("x");
197 expect(isShared(app.db, packed)).toBe(false);
198
199 t.send("c");
200 expect(t.pushed.length).toBe(1);
201
202 const cmp = tui(alice, packed, explored);
203 await cmp.screen.load!(new AbortController().signal);
204 cmp.send("s");
205 expect(isShared(app.db, packed)).toBe(false);
206
207 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "correct-horse-battery" });
208 if (!bob.ok) throw new Error(bob.error);
209 const theirs = tui(bob.value, packed);
210 await theirs.screen.load!(new AbortController().signal);
211 theirs.send("s");
212 expect(isShared(app.db, packed)).toBe(false);
213 expect(theirs.toasts.at(-1)).toContain("only the repository's owner");
214 });
215
216 test("a shared trace is read once for repeats, and one address is bounded", async () => {
217 const made = shareRun(app, alice, repo, explored);
218 if (!made.ok) throw new Error("not made");
219 const first = await readShared(app, made.value.token);
220 expect(await readShared(app, made.value.token)).toBe(first!);
221 unshareRun(app, alice, repo, explored);
222 expect(await readShared(app, made.value.token)).toBeUndefined();
223 let refused = 0;
224 for (let i = 0; i < 70; i++) if (!sharedTurn(app, "203.0.113.9").allowed) refused++;
225 expect(refused).toBeGreaterThan(0);
226 expect(sharedTurn(app, "203.0.113.10").allowed).toBe(true);
227 });

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

Keyboard shortcuts

Docs