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

Traces: every conversation and run kept as a trace, imported from outside agents, and explored in the forge #18011

opened this in answer to

Closed 14h 10m ago

scout/forge:scout/17929-traces-every-conversation-and-run-kept-a → main 8 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +370 −8
docs/design/audit.md +1
@@ -75,6 +75,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
7575 - `/talk` — `pages/talk.ts` · the person's one conversation with the forge: history, composer, Do it and Not now; replies stream in over `/talk/stream` · `/settings/confirms` (the same yes, as a list), the home tell box (one line to an app's crew) · none seen; styles in `docs/design/areas/talk.md`.
7676 - `/tell` — `studio/share_tell.ts` · where a phone's share sheet lands: the shared words in a form, the last repository chosen, nothing filed until Send · the phone's share sheet (manifest `share_target`) · none seen.
7777 - `/tell/share` — `studio/share_receive.ts` · the words a phone shared while signed out, held on the server through sign-in, in a form filed only on Send · the sign-in redirect after a share · none seen.
78 - `/traces` — `pages/traces.ts` · the sessions the person imported from outside agents, newest first, each a link to its tree; how to send one · the Traces palette entry (`tui/screens/traces.ts`) · none seen.
7879 - `/next` — `pages/next_all.ts` · the owner's priorities, one ranked group per administered repository · the repository's Next up page, `next_up` on the MCP · none seen.
7980 - `/notes` — `pages/notes.ts` · what the person wrote, newest first, with the planner's verdict and live state in one line, and one tap to overrule it · the home tell box (Notes button), the user menu, the palette · none seen; styles in `docs/design/areas/notes.md`.
8081 - `/pipeline` — `pages/pipeline.ts` · the four steps a change follows (check, review, land, live), for a newcomer · a pull page's step line, `/flow` · none seen.
docs/features/trace-import.md added +9
@@ -0,0 +1,9 @@
1 ---
2 topic: Your apps
3 row: Traces: import an outside agent's session and keep it
4 ---
5 # Import a session
6
7 `POST /traces/import` with the session file as the body keeps it: a signed-in same-origin session or a `rw` token (`curl -H "authorization: Bearer $FORGE_TOKEN" --data-binary @session.jsonl <forge>/traces/import`). Answers 201 with `{id, title, steps, source, href}`, or 200 when the same bytes were kept before; 422 for a file with no Claude Code or Codex records, 413 past 32 MB (`BODY_CAPS.traceImport`), 507 when the person already keeps 512 MB of sessions. The raw bytes are kept gzipped in `trace_import` (`src/core/trace_imports.ts`) and the tree is parsed from them on every read; an import is private to the person who sent it, and nothing is ever deleted. `/traces` lists a person's imports newest first, `/traces/imported/<id>` shows one as its tree. Terminal door: the Traces palette entry (`src/tui/screens/traces.ts`; `j`/`k`, `o` opens on the web). Not yet: facets and search, tokens priced as cost, compare, share links.
8
9 The page is `src/web/pages/traces.ts`; the reader that makes the tree is described in [traces](traces.md).
docs/features/traces.md +1 −1
@@ -16,6 +16,6 @@ Every conversation and run is a record the forge keeps; a trace is the same reco
1616 Each line a run appends is stamped in `<run id>.times` beside its log (`appendRunLog`), so a step shows what it took and when it ended (`2.3s, at 14s`, the last is the running total), and the strip puts each tick where and as wide as its time in the run: a slow tool or a long silence is a wide tick. A run from before the stamps shows order and says so. The log holds no tokens or cost, so a step carries neither; the run's cost is the only figure. Each run page lists a Trace fact (`runFacts`) and a Talk build card links its trace. Terminal door: `t` on a run's log opens `src/tui/screens/trace.ts` (the same rows, `traceRows`; `o` prints the web address). Reader: `src/trace/run_log.ts`, `src/trace/read.ts`.
1717
1818
19 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.
19 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: tokens and cost per step (the file holds none), compare, share.
2020
2121 The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step.
src/core/migration-pins/20261204010000-trace-import.pin added +1
@@ -0,0 +1,1 @@
1 62c062052ddb150660034d6bedec1f1c5385e24c3708aff0c3ed431e9a520c21
src/core/migrations/20261204010000-trace-import.ts added +19
@@ -0,0 +1,19 @@
1 // An outside agent's session kept as a trace (#17929): the raw bytes (gzipped) are the record, the
2 // normalized view is rebuilt from them on every read. Private to its owner. One row per (owner,
3 // digest), so sending the same file twice keeps one. Additive: a new table.
4 export default `
5 CREATE TABLE IF NOT EXISTS trace_import (
6 id TEXT PRIMARY KEY,
7 owner_id TEXT NOT NULL,
8 digest TEXT NOT NULL,
9 source TEXT NOT NULL,
10 session_id TEXT NOT NULL,
11 title TEXT NOT NULL,
12 steps INTEGER NOT NULL,
13 bytes INTEGER NOT NULL,
14 created_at TEXT NOT NULL,
15 raw BLOB NOT NULL
16 );
17 CREATE UNIQUE INDEX IF NOT EXISTS trace_import_owner_digest ON trace_import (owner_id, digest);
18 CREATE INDEX IF NOT EXISTS trace_import_owner_made ON trace_import (owner_id, id DESC);
19 `;
src/core/trace_imports.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * An outside agent's session file kept as a trace (#17929). The raw bytes are the record (gzipped,
3 * so a long thread costs little); the normalized view is parsed from them on every read, never
4 * stored. Private to the person who sent it: every read names the owner. The same file sent twice
5 * is kept once. A person keeps at most `MAX_KEPT_BYTES` of raw session, so one account cannot fill
6 * the disk; nothing is ever deleted to make room, the next import is refused instead.
7 */
8 import type { Database } from "bun:sqlite";
9 import { createHash } from "node:crypto";
10 import { gunzipSync, gzipSync } from "node:zlib";
11 import { id } from "../kernel/id.ts";
12 import { stepsOf, type Trace } from "../trace/model.ts";
13 import { parseSession } from "../trace/session.ts";
14
15 /** The most raw session bytes (before gzip) one person keeps. */
16 export const MAX_KEPT_BYTES = 512 * 1024 * 1024;
17 /** The most imports one list answers. */
18 export const LIST_MAX = 200;
19
20 export type ImportError = "not_utf8" | "no_session" | "full";
21 export const IMPORT_WORDS: Record<ImportError, string> = {
22 not_utf8: "the file is not UTF-8 text",
23 no_session: "the file holds no Claude Code or Codex session records",
24 full: "you already keep the most session text one account may",
25 };
26
27 export interface TraceImport {
28 id: string;
29 source: string;
30 sessionId: string;
31 title: string;
32 steps: number;
33 bytes: number;
34 createdAt: string;
35 }
36
37 interface Row {
38 id: string;
39 source: string;
40 session_id: string;
41 title: string;
42 steps: number;
43 bytes: number;
44 created_at: string;
45 }
46 const LISTED = "id, source, session_id, title, steps, bytes, created_at";
47 const shape = (r: Row): TraceImport => ({ id: r.id, source: r.source, sessionId: r.session_id, title: r.title, steps: r.steps, bytes: r.bytes, createdAt: r.created_at });
48
49 const titleOf = (t: Trace): string => (t.turns[0]?.prompt.replace(/\s+/g, " ").trim().slice(0, 120) || t.id || "(untitled session)");
50
51 /** Keep a session file for `ownerId`: the existing import when the same bytes were sent before. */
52 export function importSession(db: Database, ownerId: string, bytes: Uint8Array, now: Date = new Date()): { ok: true; value: TraceImport; fresh: boolean } | { ok: false; error: ImportError } {
53 let text: string;
54 try {
55 text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
56 } catch {
57 return { ok: false, error: "not_utf8" };
58 }
59 const trace = parseSession(text);
60 if (trace.turns.length === 0) return { ok: false, error: "no_session" };
61 const digest = createHash("sha256").update(bytes).digest("hex");
62 const have = db.query<Row, [string, string]>(`SELECT ${LISTED} FROM trace_import WHERE owner_id = ? AND digest = ?`).get(ownerId, digest);
63 if (have !== null) return { ok: true, value: shape(have), fresh: false };
64 const kept = db.query<{ n: number | null }, [string]>("SELECT SUM(bytes) AS n FROM trace_import WHERE owner_id = ?").get(ownerId)?.n ?? 0;
65 if (kept + bytes.byteLength > MAX_KEPT_BYTES) return { ok: false, error: "full" };
66 const row: Row = { id: id(now.getTime()), source: trace.source, session_id: trace.id, title: titleOf(trace), steps: stepsOf(trace).length, bytes: bytes.byteLength, created_at: now.toISOString() };
67 db.query("INSERT INTO trace_import (id, owner_id, digest, source, session_id, title, steps, bytes, created_at, raw) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(
68 row.id, ownerId, digest, row.source, row.session_id, row.title, row.steps, row.bytes, row.created_at, gzipSync(bytes),
69 );
70 return { ok: true, value: shape(row), fresh: true };
71 }
72
73 /** `ownerId`'s imports, newest first. */
74 export function listImports(db: Database, ownerId: string, limit: number = LIST_MAX): TraceImport[] {
75 return db.query<Row, [string, number]>(`SELECT ${LISTED} FROM trace_import WHERE owner_id = ? ORDER BY id DESC LIMIT ?`).all(ownerId, Math.min(limit, LIST_MAX)).map(shape);
76 }
77
78 /**
79 * One of `ownerId`'s imports and its trace, parsed again from the raw bytes; undefined for anyone
80 * else's.
81 */
82 export function readImport(db: Database, ownerId: string, importId: string): { meta: TraceImport; trace: Trace } | undefined {
83 const r = db.query<Row & { raw: Uint8Array }, [string, string]>(`SELECT ${LISTED}, raw FROM trace_import WHERE owner_id = ? AND id = ?`).get(ownerId, importId);
84 if (r === null) return undefined;
85 return { meta: shape(r), trace: parseSession(new TextDecoder().decode(gunzipSync(r.raw))) };
86 }
src/generated/screens.ts +9 −7
@@ -127,13 +127,14 @@ import * as s122 from "../tui/screens/tab.ts";
127127 import * as s123 from "../tui/screens/teams.ts";
128128 import * as s124 from "../tui/screens/telemetry.ts";
129129 import * as s125 from "../tui/screens/tell_undo.ts";
130 import * as s126 from "../tui/screens/traffic.ts";
131 import * as s127 from "../tui/screens/trafficview.ts";
132 import * as s128 from "../tui/screens/valves.ts";
133 import * as s129 from "../tui/screens/waiting.ts";
134 import * as s130 from "../tui/screens/waiting_for_me.ts";
135 import * as s131 from "../tui/screens/wayback.ts";
136 import * as s132 from "../tui/screens/weekcard.ts";
130 import * as s126 from "../tui/screens/traces.ts";
131 import * as s127 from "../tui/screens/traffic.ts";
132 import * as s128 from "../tui/screens/trafficview.ts";
133 import * as s129 from "../tui/screens/valves.ts";
134 import * as s130 from "../tui/screens/waiting.ts";
135 import * as s131 from "../tui/screens/waiting_for_me.ts";
136 import * as s132 from "../tui/screens/wayback.ts";
137 import * as s133 from "../tui/screens/weekcard.ts";
137138
138139 /** Each screen file that declares palette entries: its module and the export names. */
139140 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -270,4 +271,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
270271 [s130, ["entry"]],
271272 [s131, ["entry"]],
272273 [s132, ["entry"]],
274 [s133, ["entry"]],
273275 ];
src/http/lazy_lists.ts +3
@@ -695,6 +695,9 @@ export const OPERATIONS_ROUTES = [
695695 ["GET", "/fleet/graph.csv"],
696696 ["GET", "/__forge/domains/ask"],
697697 ["GET", "/runs/:id"],
698 ["GET", "/traces"],
699 ["POST", "/traces/import"],
700 ["GET", "/traces/imported/:id"],
698701 ["GET", "/traces/:id"],
699702 ["GET", "/traces/:id/steps/:n"],
700703 ] as const;
src/http/routes/operations.ts +4
@@ -23,6 +23,7 @@ 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 { importTrace, importedPage, tracesPage } from "../../web/pages/traces.ts";
2627 import { oauthCallbackUri } from "../api.ts";
2728 import { gamesRoutes } from "../games_routes.ts";
2829 import { infraRoutes } from "../infra_routes.ts";
@@ -120,6 +121,9 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s
120121 });
121122 router.add("GET", "/runs/:id", runRedirect);
122123 // A crew run as a tree of steps (#17993). Literal, above /:owner.
124 router.add("GET", "/traces", tracesPage);
125 router.add("POST", "/traces/import", importTrace);
126 router.add("GET", "/traces/imported/:id", importedPage);
123127 router.add("GET", "/traces/:id", tracePage);
124128 router.add("GET", "/traces/:id/steps/:n", traceStep);
125129 }
src/kernel/body_caps.ts +4
@@ -63,6 +63,10 @@ export const BODY_CAPS = {
6363 bytes: 8 * KIB,
6464 reason: "a browser's Content-Security-Policy report: one violation, its URLs and a sample",
6565 },
66 traceImport: {
67 bytes: 32 * MIB,
68 reason: "an outside agent's session file sent to be kept as a trace: read whole to parse it; a longer thread is sent in parts",
69 },
6670 appleUsage: {
6771 bytes: 8 * KIB,
6872 reason: "the Apple app's anonymous daily summary: a few dozen named counts and timings, so this is generous",
src/tui/screens/traces.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * The sessions a person imported from outside agents, in the terminal (#17929): the rows `/traces`
3 * shows (`listImports`, private to the signed-in person). `o` opens the one under the cursor on
4 * the web; `forge trace <file>` prints a file's tree without importing it.
5 */
6 import { listImports } from "../../core/trace_imports.ts";
7 import { importFacts, importHref } from "../../web/pages/traces.ts";
8 import type { Ctx, Screen } from "../app/app.ts";
9 import { binding } from "../app/keys.ts";
10 import type { Session } from "../session.ts";
11 import { style } from "../term/style.ts";
12 import { truncate } from "../term/width.ts";
13 import { ListState, drawList, openOnWeb, type ListRow } from "./common.ts";
14 import type { PaletteEntry } from "./entries.ts";
15
16 export function tracesScreen(f: Session, ctx: Ctx): Screen {
17 const state = new ListState();
18 const rows = () => (f.user === undefined ? [] : listImports(f.app.db, f.user.id));
19 return {
20 title: "Traces",
21 keys: [binding(["j", "k"], "move cursor"), binding(["o"], "open on the web")],
22 render(area, s) {
23 const c = ctx.theme.c;
24 const all = rows();
25 if (all.length === 0) {
26 s.text(area.x, area.y, truncate("Nothing imported yet. POST a session file to /traces/import with a read-write token.", area.w), style(c.mutedFg, c.bg), area.x + area.w);
27 return;
28 }
29 const lines: ListRow[] = all.map((i) => ({ title: i.title, meta: importFacts(i) }));
30 drawList(s, area, c, state, lines);
31 },
32 key(e) {
33 const all = rows();
34 if (state.key(e, all.length)) return true;
35 const at = all[state.index];
36 if (e.key !== "o" || e.ctrl || e.alt || at === undefined) return false;
37 openOnWeb(f, ctx, importHref(at.id), "the trace");
38 return true;
39 },
40 };
41 }
42
43 /** Offered to anyone signed in. */
44 export const entry: PaletteEntry = {
45 rank: 420,
46 id: "traces",
47 title: "Traces",
48 hint: "sessions imported from outside agents, private to you",
49 offered: (session) => session.user !== undefined,
50 run: (session, ctx) => ctx.push(tracesScreen(session, ctx)),
51 };
src/web/pages/traces.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * `/traces` (#17929): the sessions a person imported from outside agents, newest first, private to
3 * them, and one of them as the tree the terminal prints. `POST /traces/import` takes the file's
4 * bytes (a session cookie from this page's origin, or a `rw` token from curl). The terminal reads
5 * the same rows (`src/tui/screens/traces.ts`).
6 */
7 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
8 import { IMPORT_WORDS, importSession, listImports, readImport, type TraceImport } from "../../core/trace_imports.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { BODY_CAPS, readBounded } from "../../http/limits.ts";
11 import { apiError, json, requireScope, securityFloor } from "../../http/respond.ts";
12 import { traceLines } from "../../cli/commands/trace.ts";
13 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
14 import { html } from "../html.ts";
15 import { page } from "../layout.ts";
16 import { row, rowList } from "../ui.ts";
17
18 /** What a row says about an import: `claude-code · 42 steps · 1.2 MB`. */
19 export const importFacts = (i: TraceImport): string => `${i.source} · ${i.steps} steps · ${i.bytes < 1024 * 1024 ? `${Math.max(1, Math.round(i.bytes / 1024))} KB` : `${(i.bytes / 1024 / 1024).toFixed(1)} MB`}`;
20
21 export const importHref = (id: string): string => `/traces/imported/${id}`;
22
23 // GET /traces
24 export async function tracesPage(ctx: Ctx): Promise<Response> {
25 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
26 const user = ctx.auth.user;
27 if (user === undefined) return signInFirst(ctx);
28 const rows = listImports(ctx.app.db, user.id);
29 const cmd = `curl -H "authorization: Bearer $FORGE_TOKEN" --data-binary @session.jsonl ${ctx.url.origin}/traces/import`;
30 return page({
31 ctx,
32 title: "Traces",
33 body: html`${pageHead("Traces", { sub: "Sessions from outside agents, kept private to you." })}
34 <p class="small muted" id="traces-how">Send a Claude Code or Codex session file with a read-write token: <code>${cmd}</code></p>
35 ${rows.length === 0
36 ? html`<p class="muted" id="traces-empty">Nothing imported yet.</p>`
37 : html`<div id="traces-list">${rowList(rows.map((i) => row({ title: html`<a href="${importHref(i.id)}">${i.title}</a>`, meta: html`${importFacts(i)} · ${i.createdAt.slice(0, 10)}`, data: { trace: i.id } })))}</div>`}`,
38 });
39 }
40
41 // GET /traces/imported/:id — the tree of one import, as text in a page.
42 export async function importedPage(ctx: Ctx): Promise<Response> {
43 const user = ctx.auth.user;
44 if (user === undefined) return signInFirst(ctx);
45 const id = ctx.params.id ?? "";
46 const found = /^[0-9a-z]{26}$/.test(id) ? readImport(ctx.app.db, user.id, id) : undefined;
47 if (found === undefined) return notFoundPage(ctx);
48 return page({
49 ctx,
50 title: `Trace · ${found.meta.title}`,
51 body: html`${pageHead(found.meta.title, { sub: importFacts(found.meta) })}
52 <pre class="mono" id="trace-import-tree">${traceLines(found.trace).join("\n")}</pre>
53 <p class="small"><a href="/traces">All traces</a></p>`,
54 });
55 }
56
57 // POST /traces/import — the body is the session file. 201 for a new import, 200 for one already
58 // kept.
59 export async function importTrace(ctx: Ctx): Promise<Response> {
60 const no = requireScope(ctx, "rw");
61 if (no) return no;
62 const cap = BODY_CAPS.traceImport.bytes;
63 const bytes = await readBounded(ctx.request, cap);
64 if (bytes === "too_large") return apiError("too_large", 413, `session too large: at most ${cap / 1024 / 1024} MB; send a long thread in parts`);
65 const done = importSession(ctx.app.db, ctx.auth.user!.id, bytes);
66 if (!done.ok) return apiError(done.error, done.error === "full" ? 507 : 422, IMPORT_WORDS[done.error]);
67 return securityFloor(json({ ...done.value, href: importHref(done.value.id) }, done.fresh ? 201 : 200, { "cache-control": "no-store" }));
68 }
test/budgets/unfixtured/traces-imported-id.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/traces/imported/:id",
3 "why": "an import the signed-in person made; the fixture has imported no session (test/trace-import.test.ts covers it)"
4 }
test/no-polling.test.ts +1
@@ -356,6 +356,7 @@ 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/imported/:id": "needs a session the signed-in person imported, which the seed has none of",
359360 "/signin/access/:token": "needs a one-time access link an admin minted",
360361 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
361362 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/palette-roster.test.ts +3
@@ -231,6 +231,7 @@ test("a site-admin person is offered the whole roster", () => {
231231 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
232232 ["abstractions", "Tables", "the forge's tables: how much each is used, and what builds on what"],
233233 ["security-controls", "Security controls", "each safeguard, its state, and when it was last checked"],
234 ["traces", "Traces", "sessions imported from outside agents, private to you"],
234235 ["billing", "Billing", "each forge's plan, and grant one by hand"],
235236 ["lapsed", "Lapsed forges", "forges asleep until paid, when their data goes, pay again"],
236237 ["sold", "Sold forges", "what each bought forge costs, pays and leaves"],
@@ -363,6 +364,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
363364 ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"],
364365 ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"],
365366 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
367 ["traces", "Traces", "sessions imported from outside agents, private to you"],
366368 ["spend", "Spend", "what the crew's runs spent, by credential, app, agent, issue and kind"],
367369 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
368370 ["archived", "Archive", "what is put away, who put it there: open one or unarchive it"],
@@ -493,6 +495,7 @@ test("a member person is offered the signed-in roster without the admin entries"
493495 ["tell-undo", "Take a tell back", "a tell you sent in the last minute, while nobody has read it"],
494496 ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"],
495497 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
498 ["traces", "Traces", "sessions imported from outside agents, private to you"],
496499 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
497500 ["archived", "Archive", "what is put away, who put it there: open one or unarchive it"],
498501 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
test/security-floor-routes.test.ts +1
@@ -95,6 +95,7 @@ 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/imported/:id": "needs a session the signed-in person imported, which the seed has none of",
9899 "/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)",
99100 "/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)",
100101 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/trace-import.test.ts added +105
@@ -0,0 +1,105 @@
1 // An outside session kept as a trace, private to its owner (#17929).
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 { createApp, type App } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { importSession, listImports, readImport } from "../src/core/trace_imports.ts";
10 import { BODY_CAPS } from "../src/http/limits.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12
13 let dir = "";
14 let app: App;
15 let servers: Servers;
16 let base = "";
17 let alice = "";
18 let bob = "";
19 let aliceId = "";
20 let bobId = "";
21 const rec = (o: object): string => JSON.stringify({ sessionId: "s1", cwd: "/w", ...o });
22 const SESSION = [
23 rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "fix the <b>login</b> bug" } }),
24 rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Looking" }] } }),
25 ].join("\n");
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "trace-import-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 base = `http://127.0.0.1:${servers.port}`;
32 const mk = async (username: string) => {
33 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" });
34 if (!u.ok) throw new Error(u.error);
35 return u.value;
36 };
37 const a = await mk("alice");
38 const b = await mk("bob");
39 aliceId = a.id;
40 bobId = b.id;
41 alice = createToken(app.db, a.id, "a", "rw").token;
42 bob = createToken(app.db, b.id, "b", "rw").token;
43 }, 30_000);
44 afterAll(async () => {
45 await servers.stop();
46 app.close();
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 const post = (token: string | undefined, body: string | Uint8Array, headers: Record<string, string> = {}) =>
51 fetch(`${base}/traces/import`, { method: "POST", headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers }, body });
52
53 test("a posted session is kept, the same bytes once, and read back as a trace", async () => {
54 const first = await post(alice, SESSION);
55 expect(first.status).toBe(201);
56 const made = (await first.json()) as { id: string; steps: number; source: string; title: string };
57 expect(made.source).toBe("claude-code");
58 expect(made.steps).toBe(1);
59 expect((await post(alice, SESSION)).status).toBe(200);
60 expect(listImports(app.db, aliceId).length).toBe(1);
61 const read = readImport(app.db, aliceId, made.id)!;
62 expect(read.trace.turns[0]!.prompt).toContain("login");
63 });
64
65 test("it is private: another person sees none of it", async () => {
66 const mine = listImports(app.db, aliceId)[0]!;
67 expect(listImports(app.db, bobId)).toEqual([]);
68 expect(readImport(app.db, bobId, mine.id)).toBeUndefined();
69 const res = await fetch(`${base}/traces/imported/${mine.id}`, { headers: { authorization: `Bearer ${bob}` } });
70 expect(res.status).toBe(404);
71 });
72
73 test("refusals: no token, a read-only token, not a session, not text, too large", async () => {
74 expect((await post(undefined, SESSION)).status).toBe(401);
75 const ro = createToken(app.db, aliceId, "ro", "ro").token;
76 expect((await post(ro, SESSION)).status).toBe(403);
77 expect((await post(alice, "not a session\n")).status).toBe(422);
78 expect((await post(alice, new Uint8Array([0xff, 0xfe, 0xfd]))).status).toBe(422);
79 expect((await post(alice, new Uint8Array(BODY_CAPS.traceImport.bytes + 1))).status).toBe(413);
80 });
81
82 test("the list page escapes a title and shows the tree", async () => {
83 const mine = listImports(app.db, aliceId)[0]!;
84 const list = await (await fetch(`${base}/traces`, { headers: { authorization: `Bearer ${alice}` } })).text();
85 expect(list).toContain(mine.id);
86 expect(list).not.toContain("<b>login</b>");
87 const one = await (await fetch(`${base}/traces/imported/${mine.id}`, { headers: { authorization: `Bearer ${alice}` } })).text();
88 expect(one).toContain("trace-import-tree");
89 expect(one).not.toContain("<b>login</b>");
90 });
91
92 test("a person's raw session total is capped", () => {
93 const other = importSession(app.db, "someone", new TextEncoder().encode(SESSION));
94 expect(other.ok).toBe(true);
95 app.db.query("UPDATE trace_import SET bytes = ? WHERE owner_id = 'someone'").run(512 * 1024 * 1024);
96 const more = importSession(app.db, "someone", new TextEncoder().encode(SESSION + "\n" + rec({ type: "user", timestamp: "2026-12-01T09:01:00Z", message: { role: "user", content: "more" } })));
97 expect(more).toEqual({ ok: false, error: "full" });
98 });
99
100 test("listing an owner's imports walks its index", () => {
101 const plan = app.db.query("EXPLAIN QUERY PLAN SELECT id FROM trace_import WHERE owner_id = ? ORDER BY id DESC LIMIT 5").all("x").map((r) => (r as { detail: string }).detail).join(" ");
102 expect(plan).toContain("USING");
103 expect(plan).not.toContain("SCAN");
104 expect(plan).not.toContain("TEMP B-TREE");
105 });

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

Keyboard shortcuts

Docs