Public: anyone can read this; the crew can change it.
Traces 4: a Claude Code session file imports as a trace and is listed beside the others #18129
Merged 6h 24m ago, live in production
scout/forge:scout/18071-traces-4-a-claude-code-session-file-impo → main 0 commits fork 2 threads · 2 unresolved
19 files
changed +463
−27
- docs/features/traces.md
- scripts/unused-exports-allow.json
- src/contract/openapi/routes/getApiV1Traces.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1TracesImport.ts
- src/core/account_purge.ts
- src/core/migration-pins/20261204072951-trace-index-imported.pin
- src/core/migrations/20261204072951-trace-index-imported.ts
- src/http/api/traces.ts
- src/http/lazy_lists.ts
- src/kernel/body_caps.ts
- src/maintain/duties/account_purge.ts
- src/trace/import.ts
- src/trace/import_adapter.ts
- src/trace/import_claude_code.ts
- src/trace/index_table.ts
- test/account-purge.test.ts
- test/private-by-default.test.ts
- test/traces-import.test.ts
docs/features/traces.md +11
| @@ -30,6 +30,17 @@ The file is read whole, then parsed, so the 256 MB limit is memory-bound: a sess | ||
| 30 | 30 | |
| 31 | 31 | `GET /api/v1/traces` lists the trace index newest first as `{items, next_cursor}`: filters `repository` (an id or `owner/name`), `kind` (run, talk), `model`, `outcome` (ok, failed, cancelled, stopped), `since` and `until` (a date or an ISO instant with a zone); `limit` 1 to 200 (default 50) and `cursor`. A run is listed only to someone who may read its log (the rule the run page uses), a Talk turn to its person alone; any other row is absent, never a hint. Only the index is read, never a log. A bad filter value is a 400 (`invalid_since`, …); a bad limit or cursor, or an unknown parameter, a 422. Code: `src/http/api/traces.ts` over `listTraceIndex`. |
| 32 | 32 | |
| 33 | ## Importing a Claude Code session (#18071) | |
| 34 | ||
| 35 | From a Mac, send the newest session (a token with `rw` scope in `FORGE_TOKEN`, the forge's address in `FORGE_URL`): | |
| 36 | ||
| 37 | ||
| 38 | curl -sS -X POST -H "authorization: Bearer $FORGE_TOKEN" -H "content-type: application/x-ndjson" --data-binary @"$(ls -t ~/.claude/projects/*/*.jsonl | head -1)" "$FORGE_URL/api/v1/traces/import" | |
| 39 | ||
| 40 | ||
| 41 | `POST /api/v1/traces/import` takes the session JSONL as the raw body, at most 32 MiB (a plain 413 past it; `traceImport` in `src/kernel/body_caps.ts`). The file is read by the one Claude Code reader (`src/trace/claude_code.ts`), stored gzipped as `traces/imported/<id>.jsonl.gz` under the data directory, and indexed as a trace of kind `imported`, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for no one else. The id comes from the caller and the session's own id, so sending the same session again answers 200 and replaces its trace; a first send answers 201. A file that is not UTF-8, is empty, holds no session records or carries no usable `sessionId` is a 422 (`invalid_session`) that says which. An account keeps at most 256 MiB of imported sessions (compressed, as stored; `IMPORT_QUOTA_BYTES` in `src/trace/import.ts`): an import that would pass it is a 413 (`quota_exceeded`), and re-sending a session replaces its own copy in the count. A person's imported files are deleted with their account. A session caller's cross-origin request is a 403. | |
| 42 | ||
| 43 | A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex is next. Not yet: Codex files, a page for an imported trace, deleting one. | |
| 33 | 44 | ## One trace as a tree (#18022) |
| 34 | 45 | |
| 35 | 46 | `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`. |
scripts/unused-exports-allow.json +2 −1
| @@ -185,5 +185,6 @@ | ||
| 185 | 185 | "src/spawn/machines.ts forgetMachines", |
| 186 | 186 | "src/spawn/machines.ts registerMachine", |
| 187 | 187 | "src/spawn/routes.ts forgetRoutes", |
| 188 | "src/maintain/lockfiles.ts lockfileDependencies" | |
| 188 | "src/maintain/lockfiles.ts lockfileDependencies", | |
| 189 | "src/trace/import.ts readImported" | |
| 189 | 190 | ] |
src/contract/openapi/routes/getApiV1Traces.ts +1 −1
| @@ -8,7 +8,7 @@ export const route: Route = { | ||
| 8 | 8 | path: "/api/v1/traces", |
| 9 | 9 | summary: "List traces newest first as `{ items, next_cursor }`", |
| 10 | 10 | detail: |
| 11 | "List the trace index, newest first (started, then id), as `{ items, next_cursor }` of { id, kind (run, talk, review), repository (an id; empty for a Talk turn), title, model, account, steps, errors, tokensIn, tokensCached, tokensOut, costUsd, outcome (ok, failed, cancelled, stopped), started, ended }; filters repository (an id or owner/name), kind, model, outcome, since (started at or after) and until (started before), the last two a date or an ISO 8601 instant with a zone; limit 1 to 200 (default 50) and a cursor (the next_cursor of the page before). A trace the caller could not read the log of is absent, never a hint it exists: a run is listed to those who may read its log, a Talk turn to its person alone; only the index is read, never a log. A bad filter value is a 400 (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until); a bad limit or cursor, or a parameter this list does not read, is a 422", | |
| 11 | "List the trace index, newest first (started, then id), as `{ items, next_cursor }` of { id, kind (run, talk, review, imported), repository (an id; empty for a Talk turn), title, model, account, steps, errors, tokensIn, tokensCached, tokensOut, costUsd, outcome (ok, failed, cancelled, stopped), started, ended }; filters repository (an id or owner/name), kind, model, outcome, since (started at or after) and until (started before), the last two a date or an ISO 8601 instant with a zone; limit 1 to 200 (default 50) and a cursor (the next_cursor of the page before). An imported trace is listed to the account that sent it alone. A trace the caller could not read the log of is absent, never a hint it exists: a run is listed to those who may read its log, a Talk turn to its person alone; only the index is read, never a log. A bad filter value is a 400 (invalid_kind, invalid_outcome, invalid_model, invalid_repository, invalid_since, invalid_until); a bad limit or cursor, or a parameter this list does not read, is a 422", | |
| 12 | 12 | auth: true, |
| 13 | 13 | role: "member", |
| 14 | 14 | query: { repository: "string", kind: "string", model: "string", outcome: "string", since: "string", until: "string", cursor: "string", limit: limitTo(200) }, |
src/contract/openapi/routes/index.ts +1
| @@ -515,6 +515,7 @@ export { route as postApiV1Thoughts } from "./postApiV1Thoughts.ts"; | ||
| 515 | 515 | export { route as postApiV1Timers } from "./postApiV1Timers.ts"; |
| 516 | 516 | export { route as postApiV1TimersFinish } from "./postApiV1TimersFinish.ts"; |
| 517 | 517 | export { route as postApiV1Tokens } from "./postApiV1Tokens.ts"; |
| 518 | export { route as postApiV1TracesImport } from "./postApiV1TracesImport.ts"; | |
| 518 | 519 | export { route as postApiV1UserDevices } from "./postApiV1UserDevices.ts"; |
| 519 | 520 | export { route as postApiV1UserEmailVerify } from "./postApiV1UserEmailVerify.ts"; |
| 520 | 521 | export { route as postApiV1UserKeys } from "./postApiV1UserKeys.ts"; |
src/contract/openapi/routes/postApiV1TracesImport.ts added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | import { int, num, obj, str } from "../schema_kit.ts"; | |
| 2 | import type { Route } from "../shared.ts"; | |
| 3 | ||
| 4 | export const route: Route = { | |
| 5 | method: "post", | |
| 6 | path: "/api/v1/traces/import", | |
| 7 | summary: "Keep an agent session file as a trace of your own", | |
| 8 | detail: | |
| 9 | "Send one Claude Code session file (JSONL, one record a line) as the raw body, up to 32 MiB. It is stored compressed, indexed as a trace of kind imported, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for nobody else. The same session sent again (by its sessionId) replaces its trace and answers 200; a first send answers 201. Answers the trace row with session, source and updated. A session caller's cross-origin request is refused (403)", | |
| 10 | auth: true, | |
| 11 | role: "member", | |
| 12 | status: 201, | |
| 13 | body: { "(raw body)": "the session file as text, one JSON record per line" }, | |
| 14 | response: obj({ | |
| 15 | id: str, kind: str, repository: str, title: str, model: str, account: str, | |
| 16 | steps: int, errors: int, tokensIn: int, tokensCached: int, tokensOut: int, costUsd: num, | |
| 17 | outcome: str, started: str, ended: str, session: str, source: str, | |
| 18 | }), | |
| 19 | errorStatus: { 413: "the file is past the cap (too_large), or the account already keeps 256 MiB of imports (quota_exceeded)", 422: "not a session file: not UTF-8, empty, no records or no sessionId (invalid_session); the sentence says which" }, | |
| 20 | refuses: [401, 403], | |
| 21 | }; |
src/core/account_purge.ts +10 −2
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | 20 | import type { Database } from "bun:sqlite"; |
| 21 | import { importedIdsOf, removeImported } from "../trace/import.ts"; | |
| 21 | 22 | |
| 22 | 23 | /** The placeholder's fixed id, and the words every page shows for it. */ |
| 23 | 24 | export const FORMER_ID = "former-member"; |
| @@ -49,6 +50,9 @@ const FORMER: Coverage = { do: "former" }; | ||
| 49 | 50 | export const COVERED: Readonly<Record<string, Coverage>> = { |
| 50 | 51 | // A person's own: sign-in links, notices, asks, search, grants, sessions. |
| 51 | 52 | "access_link.user_id": DELETE, |
| 53 | // An imported session file is private to the person who imported it; the index row goes with | |
| 54 | // them. | |
| 55 | "trace_index.owner": DELETE, | |
| 52 | 56 | "access_link.created_by": FORMER, |
| 53 | 57 | // Who asked a game box to run a command: the record keeps it, as the former account. |
| 54 | 58 | "game_command.by": FORMER, |
| @@ -331,7 +335,7 @@ export type PurgeOutcome = | ||
| 331 | 335 | * an account still closing and past its grace is touched, so a second run, |
| 332 | 336 | * or a person who pressed Keep my account, finds nothing to do. |
| 333 | 337 | */ |
| 334 | export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutcome { | |
| 338 | export function purgeAccount(db: Database, userId: string, now: Date, dataDir = ""): PurgeOutcome { | |
| 335 | 339 | const cutoff = new Date(now.getTime() - PURGE_AFTER_DAYS * DAY_MS).toISOString(); |
| 336 | 340 | const due = db |
| 337 | 341 | .query( |
| @@ -343,7 +347,9 @@ export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutc | ||
| 343 | 347 | const repos = ownedRepos(db, userId).length; |
| 344 | 348 | if (repos > 0) return { ok: false, reason: "owns_repos", repos }; |
| 345 | 349 | const columns = userColumns(db); |
| 346 | return db.transaction((): PurgeOutcome => { | |
| 350 | // Their imported session files go with their rows: the ids are read before the rows are. | |
| 351 | const files = dataDir === "" ? [] : importedIdsOf(db, userId); | |
| 352 | const outcome = db.transaction((): PurgeOutcome => { | |
| 347 | 353 | ensureFormer(db); |
| 348 | 354 | const count = (table: string): number => |
| 349 | 355 | db.query<{ n: number }, [string]>(`SELECT COUNT(*) AS n FROM "${table}" WHERE user_id = ?1`).get(userId)?.n ?? 0; |
| @@ -392,4 +398,6 @@ export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutc | ||
| 392 | 398 | db.query("DELETE FROM user WHERE id = ?1").run(userId); |
| 393 | 399 | return { ok: true, counts: { ...own, deleted, kept, events, scrubbed } }; |
| 394 | 400 | })(); |
| 401 | if (outcome.ok) removeImported(dataDir, files); | |
| 402 | return outcome; | |
| 395 | 403 | } |
src/core/migration-pins/20261204072951-trace-index-imported.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 68eba009ac0e79be6c49ce764d3ba452a3d6e4d5dd30673a6a7e31e140fa1c81 |
src/core/migrations/20261204072951-trace-index-imported.ts added +9
| @@ -0,0 +1,9 @@ | ||
| 1 | // Imported traces (#18071, part of #17929): a session file a person sends is one more row of | |
| 2 | // `trace_index`, private to the account in `owner` ('' for every crew run and Talk turn, which are | |
| 3 | // gated by their own rules). Additive, so a release still in play keeps serving: SQLite cannot | |
| 4 | // widen the `kind` CHECK without a rebuild, so an imported row is stored with the kind the CHECK | |
| 5 | // already allows and nothing writes ('review'), and is *read* as kind 'imported' wherever `owner` | |
| 6 | // is set (`listTraceIndex`). The raw file is kept compressed under the data directory. | |
| 7 | export default ` | |
| 8 | ALTER TABLE trace_index ADD COLUMN owner TEXT NOT NULL DEFAULT ''; | |
| 9 | `; |
src/http/api/traces.ts +22 −1
| @@ -12,15 +12,17 @@ import type { App } from "../../app.ts"; | ||
| 12 | 12 | import { getRepo, getRepoById, type Repo } from "../../core/repos.ts"; |
| 13 | 13 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 14 | 14 | import type { User } from "../../core/users.ts"; |
| 15 | import { importSession } from "../../trace/import.ts"; | |
| 15 | 16 | import { readRunLog, readRunTimes } from "../../runs/log.ts"; |
| 16 | 17 | import { MAX_STEPS, parseRunLog } from "../../trace/run_log.ts"; |
| 17 | 18 | import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "../../trace/index_table.ts"; |
| 18 | 19 | import type { Handler } from "../context.ts"; |
| 20 | import { BODY_CAPS, readBounded } from "../limits.ts"; | |
| 19 | 21 | import { apiError, json, requireScope } from "../respond.ts"; |
| 20 | 22 | import type { Router } from "../router.ts"; |
| 21 | 23 | |
| 22 | 24 | const ACCEPTED = ["repository", "kind", "model", "outcome", "since", "until", "cursor", "limit"] as const; |
| 23 | const KINDS: readonly string[] = ["run", "talk", "review"]; | |
| 25 | const KINDS: readonly string[] = ["run", "talk", "review", "imported"]; | |
| 24 | 26 | const OUTCOMES: readonly string[] = ["ok", "failed", "cancelled", "stopped"]; |
| 25 | 27 | /** An instant: a date, or a date and time with a zone. */ |
| 26 | 28 | const INSTANT = /^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d{1,3})?)?(Z|[+-]\d\d:\d\d))?$/; |
| @@ -44,6 +46,7 @@ function seeing(app: App, actor: User): (row: TraceRow) => boolean { | ||
| 44 | 46 | const owner = app.db.query<{ user_id: string }, [string]>("SELECT user_id FROM conversation_run WHERE id = ?1").get(row.id); |
| 45 | 47 | return owner?.user_id === actor.id; |
| 46 | 48 | } |
| 49 | if (row.kind === "imported") return app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(row.id)?.owner === actor.id; | |
| 47 | 50 | if (row.kind !== "run") return false; |
| 48 | 51 | if (!repos.has(row.repository)) repos.set(row.repository, getRepoById(app.db, row.repository)); |
| 49 | 52 | const repo = repos.get(row.repository); |
| @@ -128,6 +131,23 @@ export const listTraces: Handler = (ctx) => { | ||
| 128 | 131 | }); |
| 129 | 132 | }; |
| 130 | 133 | |
| 134 | /** | |
| 135 | * POST /api/v1/traces/import (#18071): the body is one agent session file (Claude Code's JSONL), | |
| 136 | * read through the cap, kept compressed, and indexed as an `imported` trace private to the caller. | |
| 137 | * The same session sent again answers 200 and replaces its trace; a first send answers 201. | |
| 138 | */ | |
| 139 | export const importTrace: Handler = async (ctx) => { | |
| 140 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 141 | // `rw` also refuses a browser session's cross-origin request. | |
| 142 | const denied = requireScope(ctx, "rw"); | |
| 143 | if (denied) return denied; | |
| 144 | const body = await readBounded(ctx.request, BODY_CAPS.traceImport.bytes); | |
| 145 | if (body === "too_large") return apiError("too_large", 413, `a session file is at most ${BODY_CAPS.traceImport.bytes / 1048576} MiB`); | |
| 146 | const done = await importSession(ctx.app.db, ctx.app.config.dataDir, ctx.auth.user!.id, body); | |
| 147 | if (!done.ok) return done.quota ? apiError("quota_exceeded", 413, done.reason) : apiError("invalid_session", 422, done.reason); | |
| 148 | return json({ ...done.row, session: done.session, source: done.source, updated: done.updated }, done.updated ? 200 : 201); | |
| 149 | }; | |
| 150 | ||
| 131 | 151 | /** The ids a trace has: a run's or a Talk turn's, never more than this many characters. */ |
| 132 | 152 | const TRACE_ID = /^[0-9a-z]{1,40}$/; |
| 133 | 153 | |
| @@ -180,6 +200,7 @@ export const readTraceTree: Handler = (ctx) => { | ||
| 180 | 200 | }; |
| 181 | 201 | |
| 182 | 202 | export function traceRoutes(router: Router<Handler>): void { |
| 203 | router.add("POST", "/api/v1/traces/import", importTrace); | |
| 183 | 204 | router.add("GET", "/api/v1/traces/:id", readTraceTree); |
| 184 | 205 | router.add("GET", "/api/v1/traces", listTraces); |
| 185 | 206 | } |
src/http/lazy_lists.ts +1
| @@ -1492,6 +1492,7 @@ export const API_ROUTES = [ | ||
| 1492 | 1492 | ["GET", "/api/v1/models"], |
| 1493 | 1493 | ["POST", "/api/v1/conversations"], |
| 1494 | 1494 | ["PATCH", "/api/v1/conversations/:id"], |
| 1495 | ["POST", "/api/v1/traces/import"], | |
| 1495 | 1496 | ["GET", "/api/v1/traces/:id"], |
| 1496 | 1497 | ["GET", "/api/v1/traces"], |
| 1497 | 1498 | ["POST", "/api/v1/builds"], |
src/kernel/body_caps.ts +4
| @@ -133,6 +133,10 @@ export const BODY_CAPS = { | ||
| 133 | 133 | bytes: 32 * MIB, |
| 134 | 134 | reason: "one file main's verification hands back from its runner: the impact map, kept results or times, streamed to disk", |
| 135 | 135 | }, |
| 136 | traceImport: { | |
| 137 | bytes: 32 * MIB, | |
| 138 | reason: "one agent session file sent to be kept as a trace: a long Claude Code session runs to a few MiB, read whole to check it before anything is kept", | |
| 139 | }, | |
| 136 | 140 | printRaster: { |
| 137 | 141 | bytes: 80 * MIB, |
| 138 | 142 | reason: "PWG raster sent to a printer: uncompressed pages run large; every page is walked before anything is sent", |
src/maintain/duties/account_purge.ts +1 −1
| @@ -76,7 +76,7 @@ export async function purgeOne(app: App, userId: string, now: Date): Promise<Pur | ||
| 76 | 76 | // each ended stream is an event that names the account, and `purgeAccount` takes those too. |
| 77 | 77 | const signedOut = signOutEveryBrowser(app, user); |
| 78 | 78 | const ended = signedOut.ok ? signedOut.value.ended : 0; |
| 79 | const purged = purgeAccount(app.db, user.id, now); | |
| 79 | const purged = purgeAccount(app.db, user.id, now, app.config.dataDir); | |
| 80 | 80 | if (!purged.ok) return fail(purged.reason === "owns_repos" ? `still owns ${purged.repos} repositories` : "no longer due"); |
| 81 | 81 | // The browsers ended above are this account's sessions too. |
| 82 | 82 | const c = { ...purged.counts, sessions: purged.counts.sessions + ended }; |
src/trace/import.ts added +116
| @@ -0,0 +1,116 @@ | ||
| 1 | /** | |
| 2 | * A session file kept as a trace (#18071). The raw file is stored compressed under the data | |
| 3 | * directory (`traces/imported/<id>.jsonl.gz`), the rest is one `trace_index` row of kind | |
| 4 | * `imported`, private to the account that sent it. The row's id comes from the account and the | |
| 5 | * session's own id, so sending the same session again replaces its row and its file: one trace, | |
| 6 | * never a duplicate. Nothing is ever deleted by an import but the older copy of the same session. | |
| 7 | */ | |
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { createHash, randomUUID } from "node:crypto"; | |
| 10 | import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; | |
| 11 | import { dirname, join } from "node:path"; | |
| 12 | import { promisify } from "node:util"; | |
| 13 | import { gunzipSync, gzip } from "node:zlib"; | |
| 14 | import { ADAPTERS } from "./import_adapter.ts"; | |
| 15 | import { stepsOf, totalsOf } from "./model.ts"; | |
| 16 | import { putTraceRow, type TraceRow } from "./index_table.ts"; | |
| 17 | ||
| 18 | const gzipped = promisify(gzip); | |
| 19 | ||
| 20 | export type ImportResult = | |
| 21 | | { readonly ok: true; readonly row: TraceRow; readonly session: string; readonly source: string; readonly updated: boolean } | |
| 22 | | { readonly ok: false; readonly reason: string; readonly quota?: true }; | |
| 23 | ||
| 24 | /** | |
| 25 | * The id of the trace an account's copy of a session has: lowercase hex, so it is a cursor's id | |
| 26 | * too. | |
| 27 | */ | |
| 28 | export const importedId = (owner: string, source: string, session: string): string => | |
| 29 | createHash("sha256").update(`${owner}\0${source}\0${session}`).digest("hex").slice(0, 32); | |
| 30 | ||
| 31 | const fileOf = (dataDir: string, id: string): string => join(dataDir, "traces", "imported", `${id}.jsonl.gz`); | |
| 32 | ||
| 33 | /** A time inside 2000 to 2100 as ISO 8601 UTC; any other (a bad clock in the file) is now. */ | |
| 34 | const iso = (ms: number): string => new Date(ms > 9.46e11 && ms < 4.1e12 ? ms : Date.now()).toISOString(); | |
| 35 | ||
| 36 | /** The most compressed bytes of imported sessions one account keeps: past it an import is a 413. */ | |
| 37 | export const IMPORT_QUOTA_BYTES = 256 * 1024 * 1024; | |
| 38 | ||
| 39 | const sizeOf = (file: string): number => { | |
| 40 | try { | |
| 41 | return statSync(file).size; | |
| 42 | } catch { | |
| 43 | return 0; | |
| 44 | } | |
| 45 | }; | |
| 46 | ||
| 47 | /** The ids of the sessions an account has imported. */ | |
| 48 | export function importedIdsOf(db: Database, owner: string): string[] { | |
| 49 | return db.query<{ id: string }, [string]>("SELECT id FROM trace_index WHERE owner = ?1").all(owner).map((r) => r.id); | |
| 50 | } | |
| 51 | ||
| 52 | /** Take the stored files of these ids off the disk (the account purge's, after its rows go). */ | |
| 53 | export function removeImported(dataDir: string, ids: readonly string[]): void { | |
| 54 | for (const id of ids) rmSync(fileOf(dataDir, id), { force: true }); | |
| 55 | } | |
| 56 | ||
| 57 | /** The raw session as it was sent, from the stored file. */ | |
| 58 | export function readImported(dataDir: string, id: string): string { | |
| 59 | return gunzipSync(readFileSync(fileOf(dataDir, id))).toString("utf8"); | |
| 60 | } | |
| 61 | ||
| 62 | /** Read `bytes` as a session of some source, keep it, and index it for `owner`. */ | |
| 63 | export async function importSession(db: Database, dataDir: string, owner: string, bytes: Uint8Array): Promise<ImportResult> { | |
| 64 | let text: string; | |
| 65 | try { | |
| 66 | text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); | |
| 67 | } catch { | |
| 68 | return { ok: false, reason: "the file is not UTF-8 text" }; | |
| 69 | } | |
| 70 | if (text.trim() === "") return { ok: false, reason: "the file is empty" }; | |
| 71 | let refused = ""; | |
| 72 | for (const adapter of ADAPTERS) { | |
| 73 | const read = adapter.read(text); | |
| 74 | if ("refused" in read) { | |
| 75 | refused = read.refused; | |
| 76 | continue; | |
| 77 | } | |
| 78 | const { trace } = read; | |
| 79 | const id = importedId(owner, adapter.source, trace.id); | |
| 80 | const file = fileOf(dataDir, id); | |
| 81 | mkdirSync(dirname(file), { recursive: true }); | |
| 82 | const packed = await gzipped(bytes); | |
| 83 | // What the account keeps, less the copy this replaces, plus this one, stays under the quota. | |
| 84 | const kept = importedIdsOf(db, owner).reduce((n, other) => n + (other === id ? 0 : sizeOf(fileOf(dataDir, other))), 0); | |
| 85 | if (kept + packed.length > IMPORT_QUOTA_BYTES) { | |
| 86 | return { ok: false, quota: true, reason: `the account's imported sessions are at most ${IMPORT_QUOTA_BYTES / 1048576} MiB stored` }; | |
| 87 | } | |
| 88 | const part = `${file}.${randomUUID()}.part`; | |
| 89 | writeFileSync(part, packed); | |
| 90 | renameSync(part, file); | |
| 91 | const t = totalsOf(trace); | |
| 92 | const model = stepsOf(trace).find((s) => s.model !== undefined)?.model ?? ""; | |
| 93 | const at = t.startMs > 0 ? t.startMs : (trace.turns[0]?.startMs ?? Date.now()); | |
| 94 | const row: TraceRow = { | |
| 95 | id, | |
| 96 | kind: "imported", | |
| 97 | repository: "", | |
| 98 | title: trace.turns.find((x) => x.prompt !== "")?.prompt ?? `${adapter.source} session`, | |
| 99 | model, | |
| 100 | account: "", | |
| 101 | steps: t.steps, | |
| 102 | errors: t.errors, | |
| 103 | tokensIn: t.tokensIn, | |
| 104 | tokensCached: t.tokensCached, | |
| 105 | tokensOut: t.tokensOut, | |
| 106 | costUsd: 0, | |
| 107 | outcome: "ok", | |
| 108 | started: iso(at), | |
| 109 | ended: iso(Math.max(t.endMs, at)), | |
| 110 | }; | |
| 111 | const updated = db.query("SELECT 1 FROM trace_index WHERE id = ?1").get(id) !== null; | |
| 112 | putTraceRow(db, row, owner); | |
| 113 | return { ok: true, row, session: trace.id, source: adapter.source, updated }; | |
| 114 | } | |
| 115 | return { ok: false, reason: refused }; | |
| 116 | } |
src/trace/import_adapter.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** | |
| 2 | * What a source of session files must be to be imported (#18071): a name, a way to say whether a | |
| 3 | * file is its own, and a way to read it into a `Trace`. One file per source | |
| 4 | * (`import_claude_code.ts`); Codex is the next file and one line in `ADAPTERS`, never a rewrite | |
| 5 | * of the route or the store. Plain data in, plain data out. | |
| 6 | */ | |
| 7 | import type { Trace } from "./model.ts"; | |
| 8 | import { claudeCode } from "./import_claude_code.ts"; | |
| 9 | ||
| 10 | export interface ImportAdapter { | |
| 11 | readonly source: Trace["source"]; | |
| 12 | /** The file read into a trace, or why it is refused: a sentence for the person who sent it. */ | |
| 13 | read(text: string): { readonly trace: Trace } | { readonly refused: string }; | |
| 14 | } | |
| 15 | ||
| 16 | /** Every source the import takes, in the order a file is tried. */ | |
| 17 | export const ADAPTERS: readonly ImportAdapter[] = [claudeCode]; |
src/trace/import_claude_code.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | /** | |
| 2 | * The Claude Code source of the import (#18071): `parseClaudeSession` is the one reader, this only | |
| 3 | * decides whether what it read is a session worth keeping. | |
| 4 | */ | |
| 5 | import { parseClaudeSession } from "./claude_code.ts"; | |
| 6 | import type { ImportAdapter } from "./import_adapter.ts"; | |
| 7 | ||
| 8 | /** A session id is the file's own name for it: letters, digits, `-`, `_`, `.`, at most 100. */ | |
| 9 | const SESSION_ID = /^[\w.-]{1,100}$/; | |
| 10 | ||
| 11 | export const claudeCode: ImportAdapter = { | |
| 12 | source: "claude-code", | |
| 13 | read(text) { | |
| 14 | const trace = parseClaudeSession(text); | |
| 15 | if (trace.turns.length === 0) return { refused: "no Claude Code records: a session file is one JSON record per line, with user and assistant messages" }; | |
| 16 | if (!SESSION_ID.test(trace.id)) return { refused: "the records carry no usable sessionId (1 to 100 letters, digits, - _ .)" }; | |
| 17 | return { trace }; | |
| 18 | }, | |
| 19 | }; |
src/trace/index_table.ts +51 −20
| @@ -18,7 +18,7 @@ import { readRunLog, readRunTimes } from "../runs/log.ts"; | ||
| 18 | 18 | import { totalsOf } from "./model.ts"; |
| 19 | 19 | import { parseRunLog } from "./run_log.ts"; |
| 20 | 20 | |
| 21 | export type TraceKind = "run" | "talk" | "review"; | |
| 21 | export type TraceKind = "run" | "talk" | "review" | "imported"; | |
| 22 | 22 | |
| 23 | 23 | export interface TraceRow { |
| 24 | 24 | readonly id: string; |
| @@ -71,26 +71,54 @@ function write(db: Database, dataDir: string, raw: Raw): void { | ||
| 71 | 71 | const { lines } = readRunLog(dataDir, raw.id); |
| 72 | 72 | const { trace } = parseRunLog(raw.id, raw.title, lines, readRunTimes(dataDir, raw.id, lines.length)); |
| 73 | 73 | const t = totalsOf(trace); |
| 74 | putTraceRow(db, { | |
| 75 | id: raw.id, | |
| 76 | kind: raw.kind, | |
| 77 | repository: raw.repository, | |
| 78 | title: raw.title, | |
| 79 | model: raw.model, | |
| 80 | account: raw.account, | |
| 81 | steps: t.steps, | |
| 82 | errors: t.errors, | |
| 83 | tokensIn: Math.max(t.tokensIn, raw.tokensIn), | |
| 84 | tokensCached: t.tokensCached, | |
| 85 | tokensOut: Math.max(t.tokensOut, raw.tokensOut), | |
| 86 | costUsd: raw.costUsd, | |
| 87 | outcome: raw.outcome, | |
| 88 | started: raw.started, | |
| 89 | ended: raw.ended, | |
| 90 | }); | |
| 91 | } | |
| 92 | ||
| 93 | /** | |
| 94 | * One row written, replacing the one with its id; `owner` is the account an imported row is private | |
| 95 | * to. Careful: an imported row is stored with kind `review` (the table's CHECK predates it) and is | |
| 96 | * told apart only by `owner <> ''`. A reader of `kind = 'review'` must add `owner = ''`, or it | |
| 97 | * shows a private row to everyone; `listTraceIndex` does, and a test holds it. | |
| 98 | */ | |
| 99 | export function putTraceRow(db: Database, row: TraceRow, owner = ""): void { | |
| 74 | 100 | db.query( |
| 75 | 101 | `INSERT OR REPLACE INTO trace_index |
| 76 | (id, kind, repository, title, model, account, steps, errors, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started, ended) | |
| 77 | VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)`, | |
| 102 | (id, kind, repository, title, model, account, steps, errors, tokens_in, tokens_cached, tokens_out, cost_usd, outcome, started, ended, owner) | |
| 103 | VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16)`, | |
| 78 | 104 | ).run( |
| 79 | raw.id, | |
| 80 | raw.kind, | |
| 81 | raw.repository, | |
| 82 | clip(raw.title), | |
| 83 | raw.model.slice(0, 100), | |
| 84 | raw.account, | |
| 85 | t.steps, | |
| 86 | t.errors, | |
| 87 | Math.max(t.tokensIn, raw.tokensIn), | |
| 88 | t.tokensCached, | |
| 89 | Math.max(t.tokensOut, raw.tokensOut), | |
| 90 | raw.costUsd, | |
| 91 | raw.outcome, | |
| 92 | raw.started, | |
| 93 | raw.ended, | |
| 105 | row.id, | |
| 106 | // An imported row is stored under the kind the table's CHECK allows (see the migration). | |
| 107 | row.kind === "imported" ? "review" : row.kind, | |
| 108 | row.repository, | |
| 109 | clip(row.title), | |
| 110 | row.model.slice(0, 100), | |
| 111 | row.account, | |
| 112 | row.steps, | |
| 113 | row.errors, | |
| 114 | row.tokensIn, | |
| 115 | row.tokensCached, | |
| 116 | row.tokensOut, | |
| 117 | row.costUsd, | |
| 118 | row.outcome, | |
| 119 | row.started, | |
| 120 | row.ended, | |
| 121 | owner, | |
| 94 | 122 | ); |
| 95 | 123 | } |
| 96 | 124 | |
| @@ -289,6 +317,7 @@ interface Stored { | ||
| 289 | 317 | outcome: string; |
| 290 | 318 | started: string; |
| 291 | 319 | ended: string; |
| 320 | owner: string; | |
| 292 | 321 | } |
| 293 | 322 | |
| 294 | 323 | /** One row of the index by its id, or undefined where none was written. */ |
| @@ -311,7 +340,9 @@ export function listTraceIndex(db: Database, query: TraceQuery = {}): TracePage | ||
| 311 | 340 | where.push(clause.replace("?", `?${args.length}`)); |
| 312 | 341 | }; |
| 313 | 342 | add("repository = ?", query.repository); |
| 314 | add("kind = ?", query.kind); | |
| 343 | if (query.kind === "imported") where.push("owner <> ''"); | |
| 344 | else if (query.kind === "review") where.push("kind = 'review' AND owner = ''"); | |
| 345 | else add("kind = ?", query.kind); | |
| 315 | 346 | add("model = ?", query.model); |
| 316 | 347 | add("outcome = ?", query.outcome); |
| 317 | 348 | add("started >= ?", query.since); |
| @@ -333,7 +364,7 @@ export function listTraceIndex(db: Database, query: TraceQuery = {}): TracePage | ||
| 333 | 364 | return { |
| 334 | 365 | rows: page.map((r) => ({ |
| 335 | 366 | id: r.id, |
| 336 | kind: r.kind, | |
| 367 | kind: r.owner === "" ? r.kind : "imported", | |
| 337 | 368 | repository: r.repository, |
| 338 | 369 | title: r.title, |
| 339 | 370 | model: r.model, |
test/account-purge.test.ts +21 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | * a user id fails here until the purge knows what to do with it. |
| 8 | 8 | */ |
| 9 | 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 10 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 10 | import { existsSync, mkdtempSync, rmSync } from "node:fs"; | |
| 11 | 11 | import { tmpdir } from "node:os"; |
| 12 | 12 | import { join } from "node:path"; |
| 13 | 13 | import { createApp, type App } from "../src/app.ts"; |
| @@ -19,6 +19,7 @@ import { createRepo, getRepoById } from "../src/core/repos.ts"; | ||
| 19 | 19 | import { createSession } from "../src/core/sessions.ts"; |
| 20 | 20 | import { createToken } from "../src/core/tokens.ts"; |
| 21 | 21 | import { createUser, getUserById } from "../src/core/users.ts"; |
| 22 | import { importSession, importedId } from "../src/trace/import.ts"; | |
| 22 | 23 | import { duty, purgeDue } from "../src/maintain/duties/account_purge.ts"; |
| 23 | 24 | |
| 24 | 25 | const DAY = 86_400_000; |
| @@ -138,6 +139,25 @@ describe("the purge", () => { | ||
| 138 | 139 | }); |
| 139 | 140 | }); |
| 140 | 141 | |
| 142 | describe("an imported session", () => { | |
| 143 | test("its stored file goes with its person, and another's stays", async () => { | |
| 144 | const dana = await make("dana"); | |
| 145 | const eve = await make("eve"); | |
| 146 | const line = JSON.stringify({ type: "user", sessionId: "s-purge", cwd: "/w", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "private prompt" } }); | |
| 147 | for (const u of [dana, eve]) { | |
| 148 | const done = await importSession(app.db, root, u.id, new TextEncoder().encode(line)); | |
| 149 | if (!done.ok) throw new Error(done.reason); | |
| 150 | } | |
| 151 | const file = (id: string) => join(root, "traces", "imported", `${importedId(id, "claude-code", "s-purge")}.jsonl.gz`); | |
| 152 | expect(existsSync(file(dana.id))).toBe(true); | |
| 153 | expect(requestClose(app.db, dana.id, T0)).toBe(true); | |
| 154 | await purgeDue(app, at(7)); | |
| 155 | expect(getUserById(app.db, dana.id)).toBeUndefined(); | |
| 156 | expect(existsSync(file(dana.id))).toBe(false); | |
| 157 | expect(existsSync(file(eve.id))).toBe(true); | |
| 158 | }); | |
| 159 | }); | |
| 160 | ||
| 141 | 161 | describe("a held account", () => { |
| 142 | 162 | test("a fork that heads a pull elsewhere holds the purge before anything is deleted, once in the audit", async () => { |
| 143 | 163 | const owner = await make("gina"); |
test/private-by-default.test.ts +1
| @@ -79,6 +79,7 @@ const DOORS: Readonly<Record<string, Door>> = { | ||
| 79 | 79 | proven: "test/start.test.ts", |
| 80 | 80 | says: 'expect(repo.visibility).toBe("public")', |
| 81 | 81 | }, |
| 82 | "POST /api/v1/traces/import": { noRepository: "a trace, private to the account that imported it" }, | |
| 82 | 83 | "POST /api/v1/user/origin-apps": { noRepository: "an OAuth app for connecting origins" }, |
| 83 | 84 | "POST /api/v1/user/origins/:id/fork": { noRepository: "a fork at the origin, not here" }, |
| 84 | 85 | "POST /api/v1/user/origins/:id/mirror": { |
test/traces-import.test.ts added +154
| @@ -0,0 +1,154 @@ | ||
| 1 | /** | |
| 2 | * POST /api/v1/traces/import (#18071): a recorded Claude Code session is kept, listed for its | |
| 3 | * sender alone, read back through the one reader, and never duplicated. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createToken } from "../src/core/tokens.ts"; | |
| 11 | import { createUser } from "../src/core/users.ts"; | |
| 12 | import { listTraceIndex } from "../src/trace/index_table.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { BODY_CAPS } from "../src/kernel/body_caps.ts"; | |
| 15 | import { IMPORT_QUOTA_BYTES, importSession, importedId, readImported } from "../src/trace/import.ts"; | |
| 16 | import { stepsOf, totalsOf } from "../src/trace/model.ts"; | |
| 17 | import { parseSession } from "../src/trace/session.ts"; | |
| 18 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 19 | ||
| 20 | const rec = (o: object): string => JSON.stringify({ sessionId: "sess-1", cwd: "/w", ...o }); | |
| 21 | const SESSION = [ | |
| 22 | rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "fix the login bug" } }), | |
| 23 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Edit", input: { file_path: "a.ts", old_string: "a", new_string: "a\nb" } }], usage: { input_tokens: 5, cache_read_input_tokens: 7, output_tokens: 9 } } }), | |
| 24 | rec({ type: "user", timestamp: "2026-12-01T09:00:04Z", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] } }), | |
| 25 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:05Z", message: { id: "m2", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Done" }], usage: { input_tokens: 6, output_tokens: 2 } } }), | |
| 26 | ].join("\n"); | |
| 27 | ||
| 28 | let dir = ""; | |
| 29 | let app: App; | |
| 30 | let servers: Servers; | |
| 31 | let alice = ""; | |
| 32 | let bob = ""; | |
| 33 | ||
| 34 | const send = (token: string, body: string | Uint8Array, headers: Record<string, string> = {}): Promise<Response> => | |
| 35 | fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${token}`, ...headers }, body }); | |
| 36 | const list = async (token: string): Promise<any[]> => { | |
| 37 | const res = await fetch(`${servers.url}/api/v1/traces?kind=imported`, { headers: { authorization: `Bearer ${token}` } }); | |
| 38 | return ((await res.json()) as any).items; | |
| 39 | }; | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | dir = await mkdtemp(join(tmpdir(), "forge-traces-import-")); | |
| 43 | app = createApp({ dataDir: dir, port: 0 }); | |
| 44 | servers = await serve(app); | |
| 45 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 46 | if (!a.ok) throw new Error(a.error); | |
| 47 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 48 | if (!b.ok) throw new Error(b.error); | |
| 49 | alice = createToken(app.db, a.value.id, "t", "rw").token; | |
| 50 | bob = createToken(app.db, b.value.id, "t", "rw").token; | |
| 51 | }, 30_000); | |
| 52 | ||
| 53 | afterAll(async () => { | |
| 54 | await servers.stop(); | |
| 55 | await rm(dir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("a session is kept, listed to its sender alone, and read back with turns, tools, tokens and model", async () => { | |
| 59 | const res = await send(alice, SESSION); | |
| 60 | expect(res.status).toBe(201); | |
| 61 | const made: any = await res.json(); | |
| 62 | expect(made).toMatchObject({ kind: "imported", session: "sess-1", source: "claude-code", updated: false, model: "claude-x", steps: 3, tokensIn: 11, tokensCached: 7, tokensOut: 11, title: "fix the login bug", outcome: "ok" }); | |
| 63 | const mine = await list(alice); | |
| 64 | expect(mine.map((r) => r.id)).toEqual([made.id]); | |
| 65 | expect(mine[0].kind).toBe("imported"); | |
| 66 | expect(await list(bob)).toEqual([]); | |
| 67 | // The stored raw file, through the reader. | |
| 68 | const trace = parseSession(readImported(dir, made.id)); | |
| 69 | expect(trace.id).toBe("sess-1"); | |
| 70 | expect(trace.turns.length).toBe(1); | |
| 71 | expect(trace.turns[0]!.prompt).toBe("fix the login bug"); | |
| 72 | const steps = stepsOf(trace); | |
| 73 | expect(steps.filter((s) => s.kind === "tool").map((s) => s.line)).toEqual(["Edit a.ts +2 −1"]); | |
| 74 | expect(steps[0]!.model).toBe("claude-x"); | |
| 75 | expect(totalsOf(trace)).toMatchObject({ tokensIn: 11, tokensCached: 7, tokensOut: 11 }); | |
| 76 | // Crew listings are untouched: it is not a `review` for anyone. | |
| 77 | const reviews = await fetch(`${servers.url}/api/v1/traces?kind=review`, { headers: { authorization: `Bearer ${alice}` } }); | |
| 78 | expect(((await reviews.json()) as any).items).toEqual([]); | |
| 79 | }); | |
| 80 | ||
| 81 | test("the same session twice is one trace; another account's copy is its own", async () => { | |
| 82 | const again = await send(alice, `${SESSION}\n${rec({ type: "user", timestamp: "2026-12-01T09:01:00Z", message: { role: "user", content: "and again" } })}`); | |
| 83 | expect(again.status).toBe(200); | |
| 84 | expect(((await again.json()) as any).updated).toBe(true); | |
| 85 | expect((await list(alice)).length).toBe(1); | |
| 86 | expect(app.db.query("SELECT COUNT(*) AS n FROM trace_index WHERE id = ?1").get(importedId(app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id, "claude-code", "sess-1"))).toEqual({ n: 1 }); | |
| 87 | expect((await send(bob, SESSION)).status).toBe(201); | |
| 88 | expect((await list(bob)).length).toBe(1); | |
| 89 | expect((await list(alice)).length).toBe(1); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a malformed or empty file is refused with its reason", async () => { | |
| 93 | const bad = await send(alice, "this is not a session\nneither is this"); | |
| 94 | expect(bad.status).toBe(422); | |
| 95 | const body: any = await bad.json(); | |
| 96 | expect(body.error).toBe("invalid_session"); | |
| 97 | expect(body.message).toContain("no Claude Code records"); | |
| 98 | expect(((await (await send(alice, "")).json()) as any).message).toBe("the file is empty"); | |
| 99 | expect(((await (await send(alice, new Uint8Array([0xff, 0xfe, 0x41]))).json()) as any).message).toBe("the file is not UTF-8 text"); | |
| 100 | const noId = await send(alice, JSON.stringify({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "hi" } })); | |
| 101 | expect(noId.status).toBe(422); | |
| 102 | expect(((await noId.json()) as any).message).toContain("sessionId"); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a body past the cap is a plain 413", async () => { | |
| 106 | const big = new Uint8Array(BODY_CAPS.traceImport.bytes + 1); | |
| 107 | const res = await send(alice, big); | |
| 108 | expect(res.status).toBe(413); | |
| 109 | expect(((await res.json()) as any).error).toBe("too_large"); | |
| 110 | }); | |
| 111 | ||
| 112 | test("a caller without a token is refused, and a read-only token cannot import", async () => { | |
| 113 | expect((await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", body: SESSION })).status).toBe(401); | |
| 114 | const ro = createToken(app.db, app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!.id, "ro", "ro").token; | |
| 115 | expect((await send(ro, SESSION)).status).toBe(403); | |
| 116 | }); | |
| 117 | ||
| 118 | test("an account at its quota is refused with a 413, and a re-send of its own session still fits", async () => { | |
| 119 | const carol = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" }); | |
| 120 | if (!carol.ok) throw new Error(carol.error); | |
| 121 | const token = createToken(app.db, carol.value.id, "t", "rw").token; | |
| 122 | expect((await send(token, SESSION)).status).toBe(201); | |
| 123 | const { writeFileSync, statSync } = await import("node:fs"); | |
| 124 | const id = importedId(carol.value.id, "claude-code", "sess-1"); | |
| 125 | const file = join(dir, "traces", "imported", `${id}.jsonl.gz`); | |
| 126 | // Another stored session of this account, filling what is left of the quota. | |
| 127 | const filler = importedId(carol.value.id, "claude-code", "filler"); | |
| 128 | app.db.query("INSERT INTO trace_index (id, kind, title, started, ended, owner) VALUES (?1,'review','x','2026-12-01T00:00:00.000Z','2026-12-01T00:00:00.000Z',?2)").run(filler, carol.value.id); | |
| 129 | writeFileSync(join(dir, "traces", "imported", `${filler}.jsonl.gz`), new Uint8Array(IMPORT_QUOTA_BYTES - statSync(file).size)); | |
| 130 | expect((await send(token, SESSION)).status).toBe(200); // replaces its own copy: still fits | |
| 131 | const other = SESSION.replaceAll("sess-1", "sess-2"); | |
| 132 | const res = await send(token, other); | |
| 133 | expect(res.status).toBe(413); | |
| 134 | expect(((await res.json()) as any).error).toBe("quota_exceeded"); | |
| 135 | expect((await list(token)).length).toBe(2); // sess-1 and the filler row; sess-2 was not kept | |
| 136 | }); | |
| 137 | ||
| 138 | test("two imports of one session at once both finish and leave one readable file", async () => { | |
| 139 | const id = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!.id; | |
| 140 | const bytes = new TextEncoder().encode(SESSION); | |
| 141 | const done = await Promise.all([importSession(app.db, dir, id, bytes), importSession(app.db, dir, id, bytes)]); | |
| 142 | expect(done.every((d) => d.ok)).toBe(true); | |
| 143 | expect(parseSession(readImported(dir, importedId(id, "claude-code", "sess-1"))).id).toBe("sess-1"); | |
| 144 | }); | |
| 145 | ||
| 146 | test("no query through listTraceIndex shows an imported row without asking for it as imported", () => { | |
| 147 | const plain = listTraceIndex(app.db, { limit: 200 }).rows; | |
| 148 | // An unfiltered list does carry the row (the API's `seeing` is what hides it), but as `imported`, | |
| 149 | // never as a `review`, and a `review` filter never returns one. | |
| 150 | expect(plain.filter((r) => r.kind === "review" && importedOwned(r.id))).toEqual([]); | |
| 151 | expect(listTraceIndex(app.db, { kind: "review", limit: 200 }).rows.filter((r) => importedOwned(r.id))).toEqual([]); | |
| 152 | expect(listTraceIndex(app.db, { kind: "run", limit: 200 }).rows.filter((r) => importedOwned(r.id))).toEqual([]); | |
| 153 | }); | |
| 154 | const importedOwned = (id: string): boolean => app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(id)?.owner !== ""; |
new above
offline
HIGH: this deletes only the index row. The gzipped raw session under traces/imported/<id>.jsonl.gz is left on disk after the account is purged. Remove the files for the owner's rows too, and test it.