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

A dataset as we go: the forge's events, decisions, runs, checks and usage exported as a documented, growing dataset the crew can learn from #1365

Closed opened this in answer to
Closed without merging

scout/forge:scout/1139-a-dataset-as-we-go-the-forge-s-events-de → main 2 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +1709 −0
README.md +4
@@ -365,6 +365,10 @@ holds, where it goes, and the one command that restores it.
365365 grew up in switched off: what a host owes it, the moves in order, and what is
366366 given up.
367367
368 ## The dataset
369
370 The forge's events, decisions, runs, checks, pulls and usage as JSONL, one file per table, every field named in [`docs/DATASET.md`](docs/DATASET.md). Set `FORGE_DATASET_REPO=owner/data` (a **private** repository) and it is committed there nightly when something grew; or run `bun scripts/export-dataset.ts --repo owner/data` (`--out dir` writes the files in place, for the forge's admin alone). What is published is only what that repository's owner already reads: their own repositories, events meant for readers (no webhook, prompt, secret, mail, report, run, app or settings events), nothing about sealed issues or pulls. People are salted `p_` hashes, one name per person, including `@mentions` in free text. The forge admin sees what it holds at `/data` (Settings → Dataset); it has no terminal or MCP view yet.
371
368372 ## Cloud accounts
369373
370374 **Settings → Cloud accounts** (admins) holds provider keys — Cloudflare,
docs/DATASET.md added +142
@@ -0,0 +1,142 @@
1 # The forge's dataset
2
3 <!-- Generated from `SCHEMA` in `src/core/dataset.ts` by `bun scripts/export-dataset.ts --schema`; edit it there. -->
4
5 One JSONL file per table, one object per line, keys in the order below; `null` is unknown or not applicable. Times are ISO 8601, UTC. Ids sort by time. Rows are sorted by id.
6
7 ## Getting it
8
9 - Nightly, inside the running forge: set `FORGE_DATASET_REPO=owner/data` to a **private** repository on the forge. The export commits the six files, `SCHEMA.md` and `manifest.json` there when something grew; the history is git's.
10 - By hand: `bun scripts/export-dataset.ts --repo owner/data`, or `--out ./dir` to write the files without a repository.
11 - The forge's admin sees what it holds and what it already answers at `/data`; the planner is given the last week of it before it plans.
12 - The salt is kept in `$FORGE_APP_DATA/dataset/salt` and is never exported. Page opens are not recorded yet, so "which pages nobody opens" waits for a table.
13
14 ## Privacy, one rule everywhere
15
16 - A person is `p_` + 12 hex of a SHA-256 salted with a secret that never leaves the forge: the same person has the same name on every row, and nobody can be read back from it. A crew agent is its username.
17 - Free text has emails, tokens, credentials in URLs, long secret-looking runs and absolute paths replaced by `[email]`, `[token]`, `[credentials]`, `[secret]` and `[path]`.
18 - Only what the owner of the dataset repository already reads leaves the forge: their own repositories' rows, events meant for a repository's readers (`webhook.*`, `prompt.*`, `secret.*`, `mail.*`, `report.*`, `run.*`, `app.*`, `look.*`, `repo.settings_updated` and the like stay behind), nothing about a sealed issue or pull, and no deploy summaries.
19 - Usernames in free text (`@mentions`, and a username of four letters or more) are replaced by the person's `p_` name.
20 - Event payloads keep their shape; a value under a key that names a secret (token, secret, password, cookie, key, email, …) reads `[redacted]`, and a value under a key that names a person is hashed like a person.
21
22 ## events
23
24 Every event on the forge's bus, in the order it happened.
25
26 | field | type | meaning |
27 | --- | --- | --- |
28 | `id` | text | The event's id; ids sort by time. |
29 | `seq` | number | The outbox sequence number, when it has one. |
30 | `kind` | text | What happened, e.g. `pull.merged`. |
31 | `repo_id` | text | The repository it happened in; null for the forge itself. |
32 | `actor` | text | Who did it. A person is `p_` and 12 hex of a salted hash, the same on every row; a crew agent is its username. |
33 | `payload` | json | The event's body, scrubbed; keys that name a secret read `[redacted]`; capped at 4000 characters. |
34 | `created_at` | time | When it was appended (UTC). |
35
36 ## decisions
37
38 Every fixed-choice decision the crew's decider made, and what came of it.
39
40 | field | type | meaning |
41 | --- | --- | --- |
42 | `id` | text | The decision's id. |
43 | `kind` | text | `next`, `land`, `retry`, `lean` or `guard`. |
44 | `repo_id` | text | The repository it was about. |
45 | `issue_id` | text | The issue it was about; null when none. |
46 | `state` | json | What the decider saw, scrubbed; capped at 4000 characters. |
47 | `answer` | text | What it answered. |
48 | `p` | number | How sure it was, 0 to 1. |
49 | `by` | text | Who decided: a model, or a rule. |
50 | `ms` | number | How long deciding took, in milliseconds. |
51 | `created_at` | time | When it decided (UTC). |
52 | `outcome` | text | What came of the answer; null while unresolved. |
53 | `outcome_at` | time | When the outcome was known; null while unresolved. |
54
55 ## runs
56
57 Every agent run and deploy, with its cost, turns and outcome. A repository's own check is in `checks`.
58
59 | field | type | meaning |
60 | --- | --- | --- |
61 | `id` | text | The run's id. |
62 | `repo_id` | text | The repository it ran for. |
63 | `kind` | text | `agent` or `deploy`. |
64 | `issue_id` | text | The issue or pull it was about; null when none. |
65 | `env` | text | For a deploy: `production` or `pull-<n>`; else empty. |
66 | `branch` | text | The branch an agent worked on, scrubbed. |
67 | `state` | text | `queued`, `running`, `ok`, `failed` or `cancelled`. |
68 | `reason` | text | Why it ran: `assigned`, `feedback`, `check_failed`, `push`, … |
69 | `actor` | text | The agent for an agent run; whoever triggered a deploy. A person is `p_` and 12 hex of a salted hash, the same on every row; a crew agent is its username. |
70 | `model` | text | The model the agent runs on; `default` when unset; empty for a deploy. |
71 | `summary` | text | One line on what happened, scrubbed; capped at 300 characters. |
72 | `cost_usd` | number | What the run cost, in US dollars (list price on a subscription). |
73 | `turns` | number | How many turns the model took. |
74 | `attempt` | number | How many times it was paused and queued again. |
75 | `created_at` | time | When it was queued (UTC). |
76 | `started_at` | time | When it started; null if it never did. |
77 | `finished_at` | time | When it ended; null while it has not. |
78
79 ## checks
80
81 Every run of a repository's own check, with the tests that failed.
82
83 | field | type | meaning |
84 | --- | --- | --- |
85 | `id` | text | The check run's id. |
86 | `repo_id` | text | The repository. |
87 | `issue_id` | text | The pull it ran for; null when none. |
88 | `commit_oid` | text | The commit it judged. |
89 | `state` | text | `queued`, `running`, `ok`, `failed` or `cancelled`. |
90 | `passed` | number | Tests that passed, when the output was recognised; else null. |
91 | `failed` | number | Tests that failed, when the output was recognised; else null. |
92 | `failed_names` | json | A JSON array of up to 50 failed test names, scrubbed. |
93 | `summary` | text | One line on the verdict, scrubbed; capped at 300 characters. |
94 | `created_at` | time | When it was queued (UTC). |
95 | `finished_at` | time | When it ended; null while it has not. |
96 | `duration_ms` | number | Milliseconds from start to end; null while unknown. |
97
98 ## pulls
99
100 Every pull, with how long it took from being told to shipped and what it cost.
101
102 | field | type | meaning |
103 | --- | --- | --- |
104 | `id` | text | The pull's id (the id of its issue row). |
105 | `repo_id` | text | The repository. |
106 | `number` | number | The pull's number in its repository. |
107 | `title` | text | Its title, scrubbed. |
108 | `author` | text | Who opened it. A person is `p_` and 12 hex of a salted hash, the same on every row; a crew agent is its username. |
109 | `state` | text | `open`, `closed` or `merged`. |
110 | `base_branch` | text | The branch it targets. |
111 | `head_branch` | text | The branch it comes from, scrubbed. |
112 | `closes` | json | A JSON array of the issue numbers its description closes. |
113 | `pillar` | text | The pillar it served (`P0 Trust`, `Later`, …), from the first issue it closes that serves one; null when none. |
114 | `told_at` | time | When the earliest person-written issue it closes was opened — the tell; null when none. |
115 | `created_at` | time | When it was opened (UTC). |
116 | `closed_at` | time | When it was closed or merged; null while open. |
117 | `merged_at` | time | When it merged; null if it has not. |
118 | `merged_by` | text | Who merged it. A person is `p_` and 12 hex of a salted hash, the same on every row; a crew agent is its username. |
119 | `tell_to_shipped_hours` | number | Hours from `told_at` to `merged_at`; null unless both. |
120 | `cost_usd` | number | What the agent runs on this pull and the issues it closes cost, in US dollars. |
121
122 ## usage
123
124 What each agent run spent: tokens, cost, wall time. Request-level use of the forge's pages is not recorded yet.
125
126 | field | type | meaning |
127 | --- | --- | --- |
128 | `run_id` | text | The run it belongs to. |
129 | `repo_id` | text | The repository. |
130 | `issue_id` | text | The issue it worked on; null when none. |
131 | `agent` | text | The agent's username; null on old lines. |
132 | `model` | text | The agent's model; `default` when unset. |
133 | `subscription` | text | The credential the run worked on, as a salted hash (`s_` + 12 hex) — never the credential. |
134 | `kind` | text | `build`, `plan`, `review` or `check`. |
135 | `tokens_in` | number | Every input token the model read, cache included. |
136 | `tokens_out` | number | Output tokens. |
137 | `cost_usd` | number | The provider's reported cost, in US dollars. |
138 | `wall_ms` | number | Milliseconds from claim to end. |
139 | `outcome` | text | `ok`, `failed`, `paused` or `running`. |
140 | `landed_pull` | text | The id of the merged pull this run's issue was shipped by; null when none (yet). |
141 | `at` | time | When the run ended or last reported (UTC). |
142
scripts/export-dataset.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * Export the forge's dataset (`core/dataset.ts`).
3 *
4 * bun scripts/export-dataset.ts --repo owner/data commit to a private repository
5 * bun scripts/export-dataset.ts --out ./dataset write the files to a directory
6 * bun scripts/export-dataset.ts --schema print the schema document
7 *
8 * Reads the forge's data directory (`FORGE_APP_DATA`, else `./data`). The
9 * nightly export inside the running forge does the first of these by itself
10 * when `FORGE_DATASET_REPO` is set.
11 */
12
13 import { mkdirSync, writeFileSync } from "node:fs";
14 import { join } from "node:path";
15 import { parseArgs } from "node:util";
16 import { buildExport, publishDataset } from "../src/actions/dataset.ts";
17 import { createApp } from "../src/app.ts";
18 import { schemaDocument } from "../src/core/dataset.ts";
19
20 const { values } = parseArgs({
21 options: {
22 repo: { type: "string" },
23 out: { type: "string" },
24 schema: { type: "boolean", default: false },
25 },
26 });
27
28 if (values.schema) {
29 process.stdout.write(`${schemaDocument()}\n`);
30 process.exit(0);
31 }
32 if ((values.repo === undefined) === (values.out === undefined)) {
33 console.error("give exactly one of --repo owner/name or --out dir (or --schema)");
34 process.exit(2);
35 }
36
37 const app = createApp({
38 dataDir: process.env["FORGE_APP_DATA"] ?? "./data",
39 port: 0,
40 });
41 if (values.out !== undefined) {
42 const { files, manifest: m } = buildExport(app);
43 mkdirSync(values.out, { recursive: true });
44 for (const [file, text] of Object.entries(files)) writeFileSync(join(values.out, file), text);
45 writeFileSync(join(values.out, "manifest.json"), `${JSON.stringify(m, null, 2)}\n`);
46 console.log(`wrote ${Object.entries(m.tables).map(([t, x]) => `${t} ${x.rows}`).join(", ")} to ${values.out}`);
47 } else {
48 const done = await publishDataset(app, values.repo!);
49 if (!done.ok) {
50 console.error(done.error);
51 process.exit(1);
52 }
53 console.log(done.unchanged ? "nothing new since the last export" : `committed ${done.commit}`);
54 }
55 process.exit(0);
scripts/gate.ts +1
@@ -45,6 +45,7 @@ export const GATE: readonly string[] = [
4545 "test/review-lines.test.ts",
4646 "test/review-gate.test.ts",
4747 "test/crew-wrapup.test.ts",
48 "test/dataset.test.ts",
4849 "test/crew-limits.test.ts",
4950 "test/crew-parks.test.ts",
5051 "test/crew-sandbox.test.ts",
src/actions/dataset.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * Publishing the dataset: every table (`core/dataset.ts`) as a JSONL file,
3 * with the schema document and a manifest, committed to a private
4 * repository on this forge — so the history is git's and the crew can read
5 * it. Nightly from `startDatasetNightly`, or by hand with
6 * `scripts/export-dataset.ts`. State under the data directory: the salt
7 * that names people, and the manifest of the last export.
8 */
9
10 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11 import { join } from "node:path";
12 import type { App } from "../app.ts";
13 import {
14 schemaDocument,
15 TABLES,
16 tableRows,
17 toJsonl,
18 Privacy,
19 type TableName,
20 } from "../core/dataset.ts";
21 import { getRepo } from "../core/repos.ts";
22 import { getUserById } from "../core/users.ts";
23 import { commitToBranch } from "./repos.ts";
24
25 export interface TableFile {
26 readonly rows: number;
27 readonly bytes: number;
28 readonly sha256: string;
29 /**
30 * What decides whether the table grew: the same as `sha256`, except that
31 * `events` leaves out `push` events, because committing the export is one.
32 */
33 readonly stable: string;
34 }
35
36 export interface Manifest {
37 /** When this export was taken (UTC). */
38 readonly at: string;
39 /** The commit it landed in; empty when written to a directory only. */
40 readonly commit: string;
41 readonly tables: Readonly<Record<TableName, TableFile>>;
42 }
43
44 const dirOf = (app: App): string => join(app.config.dataDir, "dataset");
45
46 /** The secret that names people; made once, kept 0600, never exported. */
47 export function datasetSalt(app: App): string {
48 const dir = dirOf(app);
49 const path = join(dir, "salt");
50 if (existsSync(path)) return readFileSync(path, "utf8").trim();
51 mkdirSync(dir, { recursive: true });
52 const salt = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
53 writeFileSync(path, `${salt}\n`, { mode: 0o600 });
54 return salt;
55 }
56
57 export function lastExport(app: App): Manifest | undefined {
58 try {
59 return JSON.parse(readFileSync(join(dirOf(app), "manifest.json"), "utf8")) as Manifest;
60 } catch {
61 return undefined;
62 }
63 }
64
65 export interface Built {
66 readonly files: Record<string, string>;
67 readonly manifest: Manifest;
68 }
69
70 /** Every file of an export, in memory. */
71 export function buildExport(app: App, now = new Date(), ownerId?: string): Built {
72 // What leaves the forge is what its destination's owner already owns: with
73 // no owner (a local `--out`) it is the forge's admin reading in place.
74 const scope =
75 ownerId === undefined
76 ? undefined
77 : new Set(
78 app.db
79 .query<{ id: string }, [string]>("SELECT id FROM repo WHERE owner_id = ?1")
80 .all(ownerId)
81 .map((r) => r.id),
82 );
83 const w = scope === undefined ? {} : { scope };
84 const p = new Privacy(datasetSalt(app), app.db);
85 const files: Record<string, string> = {};
86 const tables = {} as Record<TableName, TableFile>;
87 for (const t of TABLES) {
88 const rows = tableRows(app.db, p, t, w);
89 const text = toJsonl(t, rows);
90 files[`${t}.jsonl`] = text;
91 const sha = (x: string): string => new Bun.CryptoHasher("sha256").update(x).digest("hex");
92 tables[t] = {
93 rows: rows.length,
94 bytes: Buffer.byteLength(text),
95 sha256: sha(text),
96 stable: t === "events" ? sha(toJsonl(t, rows.filter((r) => r["kind"] !== "push"))) : sha(text),
97 };
98 }
99 files["SCHEMA.md"] = schemaDocument();
100 return { files, manifest: { at: now.toISOString(), commit: "", tables } };
101 }
102
103 const grew = (a: Manifest | undefined, b: Manifest): boolean =>
104 a === undefined || TABLES.some((t) => a.tables[t]?.stable !== b.tables[t].stable);
105
106 export type Published =
107 | { ok: true; commit: string; unchanged: false; manifest: Manifest }
108 | { ok: true; unchanged: true }
outdated

High: the export reads every repository on the forge but publishes as repo.ownerId into one repository. Scope buildExport to what that owner can already read (admin), so the export cannot widen anyone's audience.

109 | { ok: false; error: string };
110
111 /** Export to the private repository `owner/name`. Nothing changed is not a commit. */
112 export async function publishDataset(app: App, slug: string, now = new Date()): Promise<Published> {
113 const [owner, name, ...rest] = slug.split("/");
114 const repo = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined;
115 if (!repo) return { ok: false, error: `no repository ${slug}` };
116 if (repo.visibility !== "private")
117 return { ok: false, error: `${slug} is not private; the dataset goes only to a private repository` };
118 const writer = getUserById(app.db, repo.ownerId);
119 if (!writer) return { ok: false, error: "the repository has no owner" };
120 const built = buildExport(app, now, repo.ownerId);
121 const before = lastExport(app);
122 if (before !== undefined && !grew(before, built.manifest)) {
123 // Looked and found nothing new: tonight is done, and the commit stays.
124 writeFileSync(join(dirOf(app), "manifest.json"), JSON.stringify({ ...before, at: built.manifest.at }));
125 return { ok: true, unchanged: true };
126 }
127 const files = { ...built.files, "manifest.json": `${JSON.stringify(built.manifest, null, 2)}\n` };
128 const done = await commitToBranch(app, writer, repo, {
129 message: `Dataset ${now.toISOString().slice(0, 10)}: ${TABLES.map((t) => `${t} ${built.manifest.tables[t].rows}`).join(", ")}`,
130 files: Object.entries(files).map(([path, content]) => ({ path, content })),
131 });
132 if (!done.ok) return { ok: false, error: JSON.stringify(done.error) };
133 const manifest: Manifest = { ...built.manifest, commit: done.value.commitOid };
134 mkdirSync(dirOf(app), { recursive: true });
135 writeFileSync(join(dirOf(app), "manifest.json"), JSON.stringify(manifest));
136 return { ok: true, commit: done.value.commitOid, unchanged: false, manifest };
137 }
138
139 const NIGHT_MS = 23 * 3_600_000;
140
141 /** Nightly: when the last export is a night old, publish. Off without a repository. */
142 export function startDatasetNightly(app: App, slug: string | undefined): { stop: () => void } {
143 if (!slug) return { stop: () => {} };
144 let busy = false;
145 const tick = async (): Promise<void> => {
146 if (busy) return;
147 const last = lastExport(app);
148 if (last !== undefined && Date.now() - Date.parse(last.at) < NIGHT_MS) return;
149 busy = true;
150 try {
151 const done = await publishDataset(app, slug);
152 if (!done.ok) app.log.warn("dataset export failed", { error: done.error });
153 } catch (e) {
154 app.log.warn("dataset export failed", { error: String(e) });
155 } finally {
156 busy = false;
157 }
158 };
159 const timer = setInterval(() => void tick(), 10 * 60_000);
160 return { stop: () => clearInterval(timer) };
161 }
src/core/dataset.ts added +883
@@ -0,0 +1,883 @@
1 /**
2 * The dataset: the forge's events, decisions, runs, checks, pulls and usage
3 * as plain rows, one table each, with a schema that names every field and
4 * its meaning (`docs/DATASET.md` is that schema, generated from here).
5 *
6 * One privacy rule, applied to every row of every table by `Privacy`:
7 * - a person (any user who is not a crew agent) is a salted hash,
8 * `p_` + 12 hex, the same everywhere so rows still join; a crew agent
9 * is its username, because the crew's names are not personal data;
10 * - free text is scrubbed: emails, tokens, credentials in URLs, long
11 * secret-looking runs and absolute paths are replaced by a marker;
12 * - an event payload keeps its shape but loses any value under a key that
13 * names a secret, and hashes any value under a key that names a person.
14 *
15 * Pure data in, plain rows out: no files, no network. `publish` writes them.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import { closesFromBody } from "./pulls.ts";
20 import { servedBy, pillarsOf } from "./pillars.ts";
21 import { getRepoById } from "./repos.ts";
22 import { eventAudience } from "./event_audience.ts";
23 import { eventSealed } from "./sealed.ts";
24
25 export const TABLES = [
26 "events",
27 "decisions",
28 "runs",
29 "checks",
30 "pulls",
31 "usage",
32 ] as const;
33 export type TableName = (typeof TABLES)[number];
34
35 export type Value = string | number | null;
36 export type Row = Record<string, Value>;
37
38 export interface Field {
39 readonly name: string;
40 readonly type: "text" | "number" | "time" | "json";
41 readonly meaning: string;
42 }
43
44 export interface Window {
45 /** Only rows from this instant on (ISO 8601). */
46 readonly since?: string;
47 /** Only this repository's rows. */
48 readonly repoId?: string;
49 /**
50 * Only these repositories' rows, and never a sealed issue or pull's. Set
51 * for anything that leaves the forge (the export); the admin's page and
52 * the planner's digest read in place and leave it out.
53 */
54 readonly scope?: ReadonlySet<string>;
55 }
56
57 const f = (
58 name: string,
59 type: Field["type"],
60 meaning: string,
61 ): Field => ({ name, type, meaning });
62
63 const WHO =
64 "A person is `p_` and 12 hex of a salted hash, the same on every row; a crew agent is its username.";
65
66 export const SCHEMA: Readonly<Record<TableName, { about: string; fields: readonly Field[] }>> = {
67 events: {
68 about: "Every event on the forge's bus, in the order it happened.",
69 fields: [
70 f("id", "text", "The event's id; ids sort by time."),
71 f("seq", "number", "The outbox sequence number, when it has one."),
72 f("kind", "text", "What happened, e.g. `pull.merged`."),
73 f("repo_id", "text", "The repository it happened in; null for the forge itself."),
74 f("actor", "text", `Who did it. ${WHO}`),
75 f("payload", "json", "The event's body, scrubbed; keys that name a secret read `[redacted]`; capped at 4000 characters."),
76 f("created_at", "time", "When it was appended (UTC)."),
77 ],
78 },
79 decisions: {
80 about: "Every fixed-choice decision the crew's decider made, and what came of it.",
81 fields: [
82 f("id", "text", "The decision's id."),
83 f("kind", "text", "`next`, `land`, `retry`, `lean` or `guard`."),
84 f("repo_id", "text", "The repository it was about."),
85 f("issue_id", "text", "The issue it was about; null when none."),
86 f("state", "json", "What the decider saw, scrubbed; capped at 4000 characters."),
87 f("answer", "text", "What it answered."),
88 f("p", "number", "How sure it was, 0 to 1."),
89 f("by", "text", "Who decided: a model, or a rule."),
90 f("ms", "number", "How long deciding took, in milliseconds."),
91 f("created_at", "time", "When it decided (UTC)."),
92 f("outcome", "text", "What came of the answer; null while unresolved."),
93 f("outcome_at", "time", "When the outcome was known; null while unresolved."),
94 ],
95 },
96 runs: {
97 about: "Every agent run and deploy, with its cost, turns and outcome. A repository's own check is in `checks`.",
98 fields: [
99 f("id", "text", "The run's id."),
100 f("repo_id", "text", "The repository it ran for."),
101 f("kind", "text", "`agent` or `deploy`."),
102 f("issue_id", "text", "The issue or pull it was about; null when none."),
103 f("env", "text", "For a deploy: `production` or `pull-<n>`; else empty."),
104 f("branch", "text", "The branch an agent worked on, scrubbed."),
105 f("state", "text", "`queued`, `running`, `ok`, `failed` or `cancelled`."),
106 f("reason", "text", "Why it ran: `assigned`, `feedback`, `check_failed`, `push`, …"),
107 f("actor", "text", `The agent for an agent run; whoever triggered a deploy. ${WHO}`),
108 f("model", "text", "The model the agent runs on; `default` when unset; empty for a deploy."),
109 f("summary", "text", "One line on what happened, scrubbed; capped at 300 characters."),
110 f("cost_usd", "number", "What the run cost, in US dollars (list price on a subscription)."),
111 f("turns", "number", "How many turns the model took."),
112 f("attempt", "number", "How many times it was paused and queued again."),
113 f("created_at", "time", "When it was queued (UTC)."),
114 f("started_at", "time", "When it started; null if it never did."),
115 f("finished_at", "time", "When it ended; null while it has not."),
116 ],
117 },
118 checks: {
119 about: "Every run of a repository's own check, with the tests that failed.",
120 fields: [
121 f("id", "text", "The check run's id."),
122 f("repo_id", "text", "The repository."),
123 f("issue_id", "text", "The pull it ran for; null when none."),
124 f("commit_oid", "text", "The commit it judged."),
125 f("state", "text", "`queued`, `running`, `ok`, `failed` or `cancelled`."),
126 f("passed", "number", "Tests that passed, when the output was recognised; else null."),
127 f("failed", "number", "Tests that failed, when the output was recognised; else null."),
128 f("failed_names", "json", "A JSON array of up to 50 failed test names, scrubbed."),
129 f("summary", "text", "One line on the verdict, scrubbed; capped at 300 characters."),
130 f("created_at", "time", "When it was queued (UTC)."),
131 f("finished_at", "time", "When it ended; null while it has not."),
132 f("duration_ms", "number", "Milliseconds from start to end; null while unknown."),
133 ],
134 },
135 pulls: {
136 about: "Every pull, with how long it took from being told to shipped and what it cost.",
137 fields: [
138 f("id", "text", "The pull's id (the id of its issue row)."),
139 f("repo_id", "text", "The repository."),
140 f("number", "number", "The pull's number in its repository."),
141 f("title", "text", "Its title, scrubbed."),
142 f("author", "text", `Who opened it. ${WHO}`),
143 f("state", "text", "`open`, `closed` or `merged`."),
144 f("base_branch", "text", "The branch it targets."),
145 f("head_branch", "text", "The branch it comes from, scrubbed."),
146 f("closes", "json", "A JSON array of the issue numbers its description closes."),
147 f("pillar", "text", "The pillar it served (`P0 Trust`, `Later`, …), from the first issue it closes that serves one; null when none."),
148 f("told_at", "time", "When the earliest person-written issue it closes was opened — the tell; null when none."),
149 f("created_at", "time", "When it was opened (UTC)."),
150 f("closed_at", "time", "When it was closed or merged; null while open."),
151 f("merged_at", "time", "When it merged; null if it has not."),
152 f("merged_by", "text", `Who merged it. ${WHO}`),
153 f("tell_to_shipped_hours", "number", "Hours from `told_at` to `merged_at`; null unless both."),
154 f("cost_usd", "number", "What the agent runs on this pull and the issues it closes cost, in US dollars."),
155 ],
156 },
157 usage: {
158 about: "What each agent run spent: tokens, cost, wall time. Request-level use of the forge's pages is not recorded yet.",
159 fields: [
160 f("run_id", "text", "The run it belongs to."),
161 f("repo_id", "text", "The repository."),
162 f("issue_id", "text", "The issue it worked on; null when none."),
163 f("agent", "text", "The agent's username; null on old lines."),
164 f("model", "text", "The agent's model; `default` when unset."),
165 f("subscription", "text", `The credential the run worked on, as a salted hash (\`s_\` + 12 hex) — never the credential.`),
166 f("kind", "text", "`build`, `plan`, `review` or `check`."),
167 f("tokens_in", "number", "Every input token the model read, cache included."),
168 f("tokens_out", "number", "Output tokens."),
169 f("cost_usd", "number", "The provider's reported cost, in US dollars."),
170 f("wall_ms", "number", "Milliseconds from claim to end."),
171 f("outcome", "text", "`ok`, `failed`, `paused` or `running`."),
172 f("landed_pull", "text", "The id of the merged pull this run's issue was shipped by; null when none (yet)."),
173 f("at", "time", "When the run ended or last reported (UTC)."),
174 ],
175 },
176 };
177
178 // ——— privacy ———
outdated

Low: secrets shorter than 32 characters, letter-only, or exactly 40/64 hex (many API keys are 40 hex) pass through. Don't rely on this; drop sensitive kinds at the source instead.

179
180 const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
181 const KNOWN_TOKEN =
182 /\b(?:forge_|sk-ant-|sk-|ghp_|gho_|github_pat_|xox[abp]-|AKIA|glpat-)[A-Za-z0-9_\-]{6,}/g;
183 const BEARER = /\b(?:Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
184 const URL_CREDS = /\/\/[^\s/@:]+:[^\s/@]+@/g;
185 /** A long unbroken run with letters and digits, that is not a plain commit id. */
186 const LONG_RUN = /[A-Za-z0-9+/_=-]{32,}/g;
187 const PATH = /(?<![\w:/.~-])(?:~|\.\.?)?(?:\/[\w.@+=,~-]+){2,}\/?/g;
188
189 const SECRET_KEY = /token|secret|password|passwd|cookie|authorization|api[_-]?key|private|credential|email|passphrase|^key$|_key$/i;
190 const PERSON_KEY = /^(?:actor|author|user|username|login|owner|by|merged_by|assignee|sender|recipient|requester|creator)(?:_name|_id)?$/i;
191
192 const PAYLOAD_CAP = 4000;
193
194 export class Privacy {
195 private readonly agents: Map<string, string>;
196 private readonly agentNames: Set<string>;
197 /** Lowercased username → user id, for everyone who is not a crew agent. */
198 private readonly people = new Map<string, string>();
199 private mentions: RegExp | undefined;
200
201 constructor(
202 private readonly salt: string,
203 db: Database,
204 ) {
205 this.agents = new Map();
206 this.agentNames = new Set();
207 for (const r of db
208 .query<{ id: string; username: string }, []>(
209 "SELECT id, username FROM user WHERE is_agent = 1",
210 )
211 .all()) {
212 this.agents.set(r.id, r.username);
213 this.agentNames.add(r.username.toLowerCase());
214 }
215 for (const r of db
216 .query<{ id: string; username: string }, []>(
217 "SELECT id, username FROM user WHERE is_agent = 0",
218 )
219 .all())
220 this.people.set(r.username.toLowerCase(), r.id);
outdated

Medium: name() hashes the username, but who() hashes the user id, so one person has two p_ names, which contradicts the doc. Resolve the username to a user id and hash that, and add a test that joins actor with a payload author.

221 }
222
223 /** A salted, truncated SHA-256: stable per forge, not reversible. */
224 hash(prefix: string, value: string): string {
225 const h = new Bun.CryptoHasher("sha256");
226 h.update(`${this.salt}\0${prefix}\0${value}`);
227 return `${prefix}_${h.digest("hex").slice(0, 12)}`;
228 }
229
230 /** A user id as the dataset names them. */
231 who(userId: string | null): string | null {
232 if (userId === null || userId === "") return null;
233 return this.agents.get(userId) ?? this.hash("p", userId);
234 }
235
236 /** A username that appeared in a payload: the same name as its user id gets. */
237 name(value: string): string {
238 const k = value.toLowerCase();
239 if (this.agentNames.has(k)) return value;
240 const id = this.people.get(k);
241 return id !== undefined ? this.hash("p", id) : this.hash("p", k);
242 }
243
244 /** `@name` for anyone, and a person's bare username when it is long enough to be no common word. */
245 private named(s: string): string {
246 if (this.people.size === 0) return s;
247 this.mentions ??= new RegExp(
248 `@([\\w-]+)|(?<![\\w@-])(${[...this.people.keys()]
249 .filter((n) => n.length >= 4)
250 .sort((a, b) => b.length - a.length)
251 .map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
252 .join("|") || "(?!)"})(?![\\w-])`,
253 "gi",
254 );
255 return s.replace(this.mentions, (m, at: string | undefined, bare: string | undefined) => {
256 const who = at ?? bare ?? "";
257 const k = who.toLowerCase();
258 if (this.agentNames.has(k)) return m;
259 if (at !== undefined && !this.people.has(k)) return m;
260 return `${at !== undefined ? "@" : ""}${this.name(who)}`;
261 });
262 }
263
264 /** Free text with everything that could identify a person or open a door removed. */
265 text(s: string | null | undefined, cap = 2000): string {
266 if (s === null || s === undefined) return "";
267 return this.named(s.replace(EMAIL, "[email]"))
268 .replace(URL_CREDS, "//[credentials]@")
269 .replace(KNOWN_TOKEN, "[token]")
270 .replace(BEARER, "[token]")
271 .replace(PATH, "[path]")
272 .replace(LONG_RUN, (run) =>
273 /^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(run) || !/\d/.test(run) || !/[A-Za-z]/.test(run)
274 ? run
275 : "[secret]",
276 )
277 .slice(0, cap);
278 }
279
280 private walk(value: unknown, key: string, depth: number): unknown {
281 if (depth > 8) return "[deep]";
282 if (SECRET_KEY.test(key)) return value === null || value === undefined ? value : "[redacted]";
283 if (typeof value === "string")
284 return PERSON_KEY.test(key) ? this.name(value) : this.text(value, 500);
285 if (Array.isArray(value))
286 return value.slice(0, 50).map((v) => this.walk(v, key, depth + 1));
287 if (value !== null && typeof value === "object") {
288 const out: Record<string, unknown> = {};
289 for (const [k, v] of Object.entries(value).slice(0, 50))
290 out[this.text(k, 60)] = this.walk(v, k, depth + 1);
291 return out;
292 }
293 return value;
294 }
295
296 /** A stored JSON text as scrubbed JSON text, capped. */
297 json(stored: string): string {
298 let parsed: unknown;
299 try {
300 parsed = JSON.parse(stored);
301 } catch {
302 return JSON.stringify(this.text(stored, 500));
303 }
304 const out = JSON.stringify(this.walk(parsed, "", 0));
305 return out.length <= PAYLOAD_CAP ? out : JSON.stringify({ truncated: true });
306 }
307 }
outdated

High: no audience filter. Admin/actor/app-only events (webhook.created with its URL, prompt., app.env_, report., run. of private apps) and every other user's private repository go into the export. Filter on eventAudience(kind) === "readers" and on repositories the dataset owner may admin.

308
309 // ——— the tables ———
310
311 const after = (column: string, w: Window, args: string[]): string => {
312 if (w.since === undefined) return "";
313 args.push(w.since);
314 return ` AND ${column} >= ?${args.length}`;
315 };
316 const inRepo = (column: string, w: Window, args: string[]): string => {
317 let out = "";
318 if (w.repoId !== undefined) {
319 args.push(w.repoId);
320 out += ` AND ${column} = ?${args.length}`;
321 }
322 if (w.scope !== undefined) {
323 args.push(JSON.stringify([...w.scope]));
324 out += ` AND ${column} IN (SELECT value FROM json_each(?${args.length}))`;
325 }
326 return out;
327 };
328 /** Rows about a sealed issue or pull stay out of anything scoped. */
329 const unsealed = (column: string, w: Window): string =>
330 w.scope === undefined
331 ? ""
332 : ` AND (${column} IS NULL OR ${column} NOT IN (SELECT id FROM issue WHERE sealed = 1))`;
333
334 function modelsOf(db: Database): Map<string, string> {
335 const out = new Map<string, string>();
336 for (const r of db
337 .query<{ user_id: string; model: string }, []>("SELECT user_id, model FROM agent")
338 .all())
339 out.set(r.user_id, r.model === "" ? "default" : r.model);
340 return out;
341 }
342
343 /** An event for anyone who reads the repository, about nothing sealed. */
344 function readable(
345 db: Database,
346 e: { kind: string; repo_id: string | null; payload: string },
347 ): boolean {
348 if (eventAudience(e.kind) !== "readers" || e.repo_id === null) return false;
349 try {
350 const payload = JSON.parse(e.payload) as unknown;
351 if (typeof payload !== "object" || payload === null || Array.isArray(payload))
352 return true;
353 return !eventSealed(db, { repoId: e.repo_id, payload: payload as Record<string, unknown> });
354 } catch {
355 return true;
356 }
357 }
358
359 export function eventsRows(db: Database, p: Privacy, w: Window = {}): Row[] {
360 const args: string[] = [];
361 const where = after("created_at", w, args) + inRepo("repo_id", w, args);
362 return db
363 .query<
364 {
365 id: string;
366 seq: number | null;
367 kind: string;
368 repo_id: string | null;
369 actor_id: string | null;
370 payload: string;
371 created_at: string;
372 },
373 string[]
374 >(`SELECT id, seq, kind, repo_id, actor_id, payload, created_at FROM event WHERE 1=1${where} ORDER BY id`)
375 .all(...args)
376 .filter((e) => w.scope === undefined || readable(db, e))
377 .map((e) => ({
378 id: e.id,
379 seq: e.seq,
380 kind: e.kind,
381 repo_id: e.repo_id,
382 actor: p.who(e.actor_id),
383 payload: p.json(e.payload),
384 created_at: e.created_at,
385 }));
386 }
387
388 export function decisionsRows(db: Database, p: Privacy, w: Window = {}): Row[] {
389 const args: string[] = [];
390 const where = after("created_at", w, args) + inRepo("repo_id", w, args);
391 return db
392 .query<
393 {
394 id: string;
395 kind: string;
396 repo_id: string;
397 issue_id: string | null;
398 state: string;
399 answer: string;
400 p: number;
401 by: string;
402 ms: number;
403 created_at: string;
404 outcome: string | null;
405 outcome_at: string | null;
406 },
407 string[]
408 >(`SELECT * FROM decision WHERE 1=1${where}${unsealed("issue_id", w)} ORDER BY id`)
409 .all(...args)
410 .map((d) => ({
411 id: d.id,
412 kind: d.kind,
413 repo_id: d.repo_id,
414 issue_id: d.issue_id,
415 state: p.json(d.state),
416 answer: p.text(d.answer, 300),
417 p: d.p,
418 by: p.text(d.by, 100),
419 ms: d.ms,
420 created_at: d.created_at,
421 outcome: d.outcome === null ? null : p.text(d.outcome, 300),
422 outcome_at: d.outcome_at,
423 }));
424 }
425
426 interface RunRow {
427 id: string;
428 repo_id: string;
429 kind: string;
430 issue_id: string | null;
431 env: string;
432 commit_oid: string;
433 branch: string;
434 state: string;
435 summary: string;
436 actor_id: string | null;
437 reason: string;
438 cost_usd: number;
439 turns: number;
440 attempt: number;
441 check_detail: string;
442 created_at: string;
443 started_at: string | null;
444 finished_at: string | null;
445 }
446
447 function runsOf(db: Database, kinds: string, w: Window): RunRow[] {
448 const args: string[] = [];
449 const where = after("created_at", w, args) + inRepo("repo_id", w, args);
450 return db
451 .query<RunRow, string[]>(
452 `SELECT id, repo_id, kind, issue_id, env, commit_oid, branch, state, summary, actor_id,
453 reason, cost_usd, turns, attempt, check_detail, created_at, started_at, finished_at
454 FROM run WHERE kind ${kinds}${where}${unsealed("issue_id", w)} ORDER BY id`,
455 )
456 .all(...args);
457 }
458
459 export function runsRows(db: Database, p: Privacy, w: Window = {}): Row[] {
460 const models = modelsOf(db);
461 return runsOf(db, "IN ('agent','deploy')", w).map((r) => ({
462 id: r.id,
463 repo_id: r.repo_id,
464 kind: r.kind,
465 issue_id: r.issue_id,
466 env: r.env,
467 branch: p.text(r.branch, 200),
468 state: r.state,
469 reason: r.reason,
470 actor: p.who(r.actor_id),
471 model: r.kind === "agent" && r.actor_id !== null ? (models.get(r.actor_id) ?? "") : "",
472 // A deploy's summary is the app's own output; only an agent's is the crew's.
473 summary: r.kind === "agent" ? p.text(r.summary, 300) : "",
474 cost_usd: r.cost_usd,
475 turns: r.turns,
476 attempt: r.attempt,
477 created_at: r.created_at,
478 started_at: r.started_at,
479 finished_at: r.finished_at,
480 }));
481 }
482
483 export function checksRows(db: Database, p: Privacy, w: Window = {}): Row[] {
484 return runsOf(db, "= 'check'", w).map((r) => {
485 let detail: { passed?: number; failed?: number; names?: unknown } = {};
486 try {
487 if (r.check_detail !== "") detail = JSON.parse(r.check_detail);
488 } catch {
489 // Unrecognised output: no counts, no names.
490 }
491 const names = Array.isArray(detail.names)
492 ? detail.names.filter((n): n is string => typeof n === "string").slice(0, 50).map((n) => p.text(n, 200))
493 : [];
494 const num = (n: unknown): number | null => (typeof n === "number" && Number.isFinite(n) ? n : null);
495 return {
496 id: r.id,
497 repo_id: r.repo_id,
498 issue_id: r.issue_id,
499 commit_oid: r.commit_oid,
500 state: r.state,
501 passed: num(detail.passed),
502 failed: num(detail.failed),
503 failed_names: JSON.stringify(names),
504 summary: p.text(r.summary, 300),
505 created_at: r.created_at,
506 finished_at: r.finished_at,
507 duration_ms:
508 r.started_at !== null && r.finished_at !== null
509 ? Math.max(0, Date.parse(r.finished_at) - Date.parse(r.started_at))
510 : null,
511 };
512 });
513 }
514
515 export interface PullFacts {
516 readonly rows: Row[];
517 /** Issue id → the merged pull that shipped it (the pull's own id too). */
518 readonly shippedBy: Map<string, string>;
519 }
520
521 export function pullFacts(db: Database, p: Privacy, w: Window): PullFacts {
522 const args: string[] = [];
523 const where = after("i.created_at", w, args) + inRepo("i.repo_id", w, args);
524 const pulls = db
525 .query<
526 {
527 id: string;
528 repo_id: string;
529 number: number;
530 title: string;
531 body: string;
532 author_id: string;
533 state: string;
534 created_at: string;
535 closed_at: string | null;
536 base_branch: string;
537 head_branch: string;
538 merged_at: string | null;
539 merged_by: string | null;
540 },
541 string[]
542 >(
543 `SELECT i.id, i.repo_id, i.number, i.title, i.body, i.author_id, i.state, i.created_at,
544 i.closed_at, p.base_branch, p.head_branch, p.merged_at, p.merged_by
545 FROM pull p JOIN issue i ON i.id = p.issue_id WHERE 1=1${where}${w.scope === undefined ? "" : " AND i.sealed = 0"} ORDER BY i.id`,
546 )
547 .all(...args);
548 const byNumber = db.query<{ id: string; created_at: string; author_agent: number }, [string, number]>(
549 `SELECT i.id, i.created_at, u.is_agent AS author_agent FROM issue i JOIN user u ON u.id = i.author_id
550 WHERE i.repo_id = ?1 AND i.number = ?2`,
551 );
552 const costOf = db.query<{ c: number | null }, [string]>(
553 "SELECT SUM(cost_usd) AS c FROM usage WHERE issue_id = ?1",
554 );
555 const pillars = new Map<string, Map<string, string>>();
556 const servedIn = (repoId: string): Map<string, string> => {
557 let m = pillars.get(repoId);
558 if (m === undefined) {
559 const repo = getRepoById(db, repoId);
560 m = repo === undefined ? new Map() : servedBy(db, pillarsOf(db, repo));
561 pillars.set(repoId, m);
562 }
563 return m;
564 };
565 const shippedBy = new Map<string, string>();
566 const rows: Row[] = pulls.map((pull) => {
567 const closes = closesFromBody(pull.body);
568 const closed = closes
569 .map((n) => byNumber.get(pull.repo_id, n))
570 .filter((c): c is NonNullable<typeof c> => c !== null && c !== undefined);
571 const served = servedIn(pull.repo_id);
572 const pillar =
573 [...closed.map((c) => c.id), pull.id].map((id) => served.get(id)).find((x) => x !== undefined) ?? null;
574 const tells = closed.filter((c) => c.author_agent === 0).map((c) => c.created_at).sort();
575 const toldAt = tells[0] ?? null;
576 if (pull.merged_at !== null) {
577 shippedBy.set(pull.id, pull.id);
578 for (const c of closed) shippedBy.set(c.id, pull.id);
579 }
580 let cost = 0;
581 for (const id of new Set([pull.id, ...closed.map((c) => c.id)])) cost += costOf.get(id)?.c ?? 0;
582 return {
583 id: pull.id,
584 repo_id: pull.repo_id,
585 number: pull.number,
586 title: p.text(pull.title, 300),
587 author: p.who(pull.author_id),
588 state: pull.merged_at !== null ? "merged" : pull.state,
589 base_branch: p.text(pull.base_branch, 200),
590 head_branch: p.text(pull.head_branch, 200),
591 closes: JSON.stringify(closes),
592 pillar,
593 told_at: toldAt,
594 created_at: pull.created_at,
595 closed_at: pull.closed_at,
596 merged_at: pull.merged_at,
597 merged_by: p.who(pull.merged_by),
598 tell_to_shipped_hours:
599 toldAt !== null && pull.merged_at !== null
600 ? Math.round(((Date.parse(pull.merged_at) - Date.parse(toldAt)) / 3_600_000) * 100) / 100
601 : null,
602 cost_usd: Math.round(cost * 1e6) / 1e6,
603 };
604 });
605 return { rows, shippedBy };
606 }
607
608 export function pullsRows(db: Database, p: Privacy, w: Window = {}): Row[] {
609 return pullFacts(db, p, w).rows;
610 }
611
612 export function usageRows(db: Database, p: Privacy, w: Window = {}, facts?: PullFacts): Row[] {
613 const models = modelsOf(db);
614 const { shippedBy } = facts ?? pullFacts(db, p, { ...(w.repoId === undefined ? {} : { repoId: w.repoId }), ...(w.scope === undefined ? {} : { scope: w.scope }) });
615 const names = new Map<string, string>();
616 for (const r of db.query<{ id: string; username: string }, []>("SELECT id, username FROM user WHERE is_agent = 1").all())
617 names.set(r.id, r.username);
618 const args: string[] = [];
619 const where = after("at", w, args) + inRepo("repo_id", w, args);
620 return db
621 .query<
622 {
623 run_id: string;
624 repo_id: string;
625 issue_id: string | null;
626 agent_id: string | null;
627 subscription_id: string | null;
628 kind: string;
629 tokens_in: number;
630 tokens_out: number;
631 cost_usd: number;
632 wall_ms: number;
633 outcome: string;
634 at: string;
635 },
636 string[]
637 >(`SELECT * FROM usage WHERE 1=1${where}${unsealed("issue_id", w)} ORDER BY run_id`)
638 .all(...args)
639 .map((u) => ({
640 run_id: u.run_id,
641 repo_id: u.repo_id,
642 issue_id: u.issue_id,
643 agent: u.agent_id === null ? null : (names.get(u.agent_id) ?? p.who(u.agent_id)),
644 model: u.agent_id === null ? "default" : (models.get(u.agent_id) ?? "default"),
645 subscription: u.subscription_id === null ? null : p.hash("s", u.subscription_id),
646 kind: u.kind,
647 tokens_in: u.tokens_in,
648 tokens_out: u.tokens_out,
649 cost_usd: u.cost_usd,
650 wall_ms: u.wall_ms,
651 outcome: u.outcome,
652 landed_pull: u.issue_id === null ? null : (shippedBy.get(u.issue_id) ?? null),
653 at: u.at,
654 }));
655 }
656
657 const BUILDERS: Record<TableName, (db: Database, p: Privacy, w?: Window) => Row[]> = {
658 events: eventsRows,
659 decisions: decisionsRows,
660 runs: runsRows,
661 checks: checksRows,
662 pulls: pullsRows,
663 usage: usageRows,
664 };
665
666 export function tableRows(db: Database, p: Privacy, table: TableName, w: Window = {}): Row[] {
667 return BUILDERS[table](db, p, w);
668 }
669
670 /** One table as JSONL: one object per line, keys in schema order. */
671 export function toJsonl(table: TableName, rows: readonly Row[]): string {
672 const keys = SCHEMA[table].fields.map((x) => x.name);
673 return rows.map((r) => JSON.stringify(Object.fromEntries(keys.map((k) => [k, r[k] ?? null])))).join("\n") + (rows.length > 0 ? "\n" : "");
674 }
675
676 export function fromJsonl(text: string): Row[] {
677 return text
678 .split("\n")
679 .filter((l) => l !== "")
680 .map((l) => JSON.parse(l) as Row);
681 }
682
683 // ——— the schema document ———
684
685 export function schemaDocument(): string {
686 const out = [
687 "# The forge's dataset",
688 "",
689 "<!-- Generated from `SCHEMA` in `src/core/dataset.ts` by `bun scripts/export-dataset.ts --schema`; edit it there. -->",
690 "",
691 "One JSONL file per table, one object per line, keys in the order below; `null` is unknown or not applicable. Times are ISO 8601, UTC. Ids sort by time. Rows are sorted by id.",
692 "",
693 "## Getting it",
694 "",
695 "- Nightly, inside the running forge: set `FORGE_DATASET_REPO=owner/data` to a **private** repository on the forge. The export commits the six files, `SCHEMA.md` and `manifest.json` there when something grew; the history is git's.",
696 "- By hand: `bun scripts/export-dataset.ts --repo owner/data`, or `--out ./dir` to write the files without a repository.",
697 "- The forge's admin sees what it holds and what it already answers at `/data`; the planner is given the last week of it before it plans.",
698 "- The salt is kept in `$FORGE_APP_DATA/dataset/salt` and is never exported. Page opens are not recorded yet, so \"which pages nobody opens\" waits for a table.",
699 "",
700 "## Privacy, one rule everywhere",
701 "",
702 "- A person is `p_` + 12 hex of a SHA-256 salted with a secret that never leaves the forge: the same person has the same name on every row, and nobody can be read back from it. A crew agent is its username.",
703 "- Free text has emails, tokens, credentials in URLs, long secret-looking runs and absolute paths replaced by `[email]`, `[token]`, `[credentials]`, `[secret]` and `[path]`.",
704 "- Only what the owner of the dataset repository already reads leaves the forge: their own repositories' rows, events meant for a repository's readers (`webhook.*`, `prompt.*`, `secret.*`, `mail.*`, `report.*`, `run.*`, `app.*`, `look.*`, `repo.settings_updated` and the like stay behind), nothing about a sealed issue or pull, and no deploy summaries.",
705 "- Usernames in free text (`@mentions`, and a username of four letters or more) are replaced by the person's `p_` name.",
706 "- Event payloads keep their shape; a value under a key that names a secret (token, secret, password, cookie, key, email, …) reads `[redacted]`, and a value under a key that names a person is hashed like a person.",
707 "",
708 ];
709 for (const t of TABLES) {
710 out.push(`## ${t}`, "", SCHEMA[t].about, "", "| field | type | meaning |", "| --- | --- | --- |");
711 for (const x of SCHEMA[t].fields) out.push(`| \`${x.name}\` | ${x.type} | ${x.meaning.replace(/\|/g, "\\|")} |`);
712 out.push("");
713 }
714 return out.join("\n");
715 }
716
717 // ——— what the dataset holds ———
718
719 const COUNTS: Record<TableName, string> = {
720 events: "SELECT COUNT(*) n, MAX(created_at) t FROM event",
721 decisions: "SELECT COUNT(*) n, MAX(created_at) t FROM decision",
722 runs: "SELECT COUNT(*) n, MAX(created_at) t FROM run WHERE kind IN ('agent','deploy')",
723 checks: "SELECT COUNT(*) n, MAX(created_at) t FROM run WHERE kind = 'check'",
724 pulls: "SELECT COUNT(*) n, MAX(created_at) t FROM pull p JOIN issue i ON i.id = p.issue_id",
725 usage: "SELECT COUNT(*) n, MAX(at) t FROM usage",
726 };
727
728 export interface TableStat {
729 readonly table: TableName;
730 readonly rows: number;
731 readonly latest: string | null;
732 }
733
734 export function datasetStats(db: Database): TableStat[] {
735 return TABLES.map((table) => {
736 const r = db.query<{ n: number; t: string | null }, []>(COUNTS[table]).get();
737 return { table, rows: r?.n ?? 0, latest: r?.t ?? null };
738 });
739 }
740
741 // ——— the questions it answers ———
742
743 const median = (xs: number[]): number => {
744 const s = [...xs].sort((a, b) => a - b);
745 const m = s.length >> 1;
746 return s.length === 0 ? 0 : s.length % 2 === 1 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
747 };
748 const round2 = (n: number): number => Math.round(n * 100) / 100;
749
750 export interface PillarTime {
751 readonly pillar: string;
752 readonly shipped: number;
753 readonly medianHours: number;
754 }
755
756 /** Time from tell to shipped, by pillar: merged pulls that closed a person's issue. */
757 export function tellToShipped(pulls: readonly Row[]): PillarTime[] {
758 const by = new Map<string, number[]>();
759 for (const r of pulls) {
760 if (typeof r["tell_to_shipped_hours"] !== "number") continue;
761 const k = typeof r["pillar"] === "string" ? r["pillar"] : "no pillar";
762 by.set(k, [...(by.get(k) ?? []), r["tell_to_shipped_hours"]]);
763 }
764 return [...by]
765 .map(([pillar, hours]) => ({ pillar, shipped: hours.length, medianHours: round2(median(hours)) }))
766 .sort((a, b) => b.shipped - a.shipped || a.pillar.localeCompare(b.pillar));
767 }
768
769 export interface AgentCost {
770 readonly agent: string;
771 readonly model: string;
772 readonly landed: number;
773 readonly costUsd: number;
774 readonly perLandedUsd: number | null;
775 }
776
777 /** Cost per landed pull, by agent and model: all the agent's spend over the pulls its runs shipped. */
778 export function costPerLanded(usage: readonly Row[]): AgentCost[] {
779 const by = new Map<string, { agent: string; model: string; cost: number; pulls: Set<string> }>();
780 for (const u of usage) {
781 const agent = typeof u["agent"] === "string" ? u["agent"] : "unknown";
782 const model = typeof u["model"] === "string" ? u["model"] : "default";
783 const e = by.get(`${agent}\0${model}`) ?? { agent, model, cost: 0, pulls: new Set() };
784 e.cost += typeof u["cost_usd"] === "number" ? u["cost_usd"] : 0;
785 if (typeof u["landed_pull"] === "string") e.pulls.add(u["landed_pull"]);
786 by.set(`${agent}\0${model}`, e);
787 }
788 return [...by.values()]
789 .map((e) => ({
790 agent: e.agent,
791 model: e.model,
792 landed: e.pulls.size,
793 costUsd: round2(e.cost),
794 perLandedUsd: e.pulls.size === 0 ? null : round2(e.cost / e.pulls.size),
795 }))
796 .sort((a, b) => b.costUsd - a.costUsd);
797 }
798
799 export interface FailingTest {
800 readonly name: string;
801 readonly failures: number;
802 }
803
804 /** Which tests fail most across failed checks. */
805 export function failingChecks(checks: readonly Row[], top = 10): FailingTest[] {
806 const n = new Map<string, number>();
807 for (const c of checks) {
808 if (c["state"] !== "failed" || typeof c["failed_names"] !== "string") continue;
809 let names: unknown;
810 try {
811 names = JSON.parse(c["failed_names"]);
812 } catch {
813 continue;
814 }
815 if (Array.isArray(names))
816 for (const x of names) if (typeof x === "string") n.set(x, (n.get(x) ?? 0) + 1);
817 }
818 return [...n]
819 .map(([name, failures]) => ({ name, failures }))
820 .sort((a, b) => b.failures - a.failures || a.name.localeCompare(b.name))
821 .slice(0, top);
822 }
823
824 // ——— the last week, for the planner ———
825
826 export const WEEK_MS = 7 * 24 * 3_600_000;
827
828 export interface WeekDigest {
829 readonly since: string;
830 readonly landed: number;
831 readonly landedByPillar: readonly { pillar: string; landed: number }[];
832 readonly parked: number;
833 readonly costUsd: number;
834 readonly perLandedUsd: number | null;
835 readonly checksFailed: number;
836 readonly topFailing: readonly FailingTest[];
837 }
838
839 export function weekDigest(db: Database, repoId: string, now = new Date()): WeekDigest {
840 const since = new Date(now.getTime() - WEEK_MS).toISOString();
841 // The hash needs a salt only to name people; the digest names none.
842 const p = new Privacy("digest", db);
843 const w = { repoId };
844 const facts = pullFacts(db, p, w);
845 const merged = facts.rows.filter((r) => typeof r["merged_at"] === "string" && (r["merged_at"] as string) >= since);
846 const by = new Map<string, number>();
847 for (const r of merged) {
848 const k = typeof r["pillar"] === "string" ? r["pillar"] : "no pillar";
849 by.set(k, (by.get(k) ?? 0) + 1);
850 }
851 const usage = usageRows(db, p, { repoId, since }, facts);
852 const cost = usage.reduce((s, u) => s + (typeof u["cost_usd"] === "number" ? u["cost_usd"] : 0), 0);
853 const checks = checksRows(db, p, { repoId, since });
854 const parked =
855 db
856 .query<{ n: number }, [string, string]>(
857 `SELECT COUNT(*) n FROM comment c JOIN issue i ON i.id = c.issue_id
858 WHERE i.repo_id = ?1 AND c.created_at >= ?2 AND c.body LIKE 'Parked by the crew%'`,
859 )
860 .get(repoId, since)?.n ?? 0;
861 return {
862 since,
863 landed: merged.length,
864 landedByPillar: [...by].map(([pillar, landed]) => ({ pillar, landed })).sort((a, b) => b.landed - a.landed),
865 parked,
866 costUsd: round2(cost),
867 perLandedUsd: merged.length === 0 ? null : round2(cost / merged.length),
868 checksFailed: checks.filter((c) => c["state"] === "failed").length,
869 topFailing: failingChecks(checks, 3),
870 };
871 }
872
873 /** The digest as the lines a planner is told, and told to say in its wave. */
874 export function weekLines(d: WeekDigest): string[] {
875 const usd = (n: number): string => `$${n.toFixed(2)}`;
876 return [
877 `Last week, from the forge's dataset (since ${d.since.slice(0, 10)}):`,
878 `- Landed: ${d.landed} pull${d.landed === 1 ? "" : "s"}${d.landedByPillar.length > 0 ? ` (${d.landedByPillar.map((x) => `${x.pillar} ${x.landed}`).join(", ")})` : ""}.`,
879 `- Parked: ${d.parked} time${d.parked === 1 ? "" : "s"}.`,
880 `- Cost: ${usd(d.costUsd)}${d.perLandedUsd === null ? ", nothing landed to divide it by" : `, ${usd(d.perLandedUsd)} per landed pull`}.`,
881 `- Checks failed: ${d.checksFailed}${d.topFailing.length > 0 ? `; most often ${d.topFailing.map((t) => `"${t.name}" (${t.failures})`).join(", ")}` : ""}.`,
882 ];
883 }
src/core/reserved.ts +1
@@ -63,6 +63,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6363 "audit.csv",
6464 "big",
6565 "board",
66 "data",
6667 "events",
6768 "explore",
6869 "fleet",
src/crew/autonomy.ts +16
@@ -12,6 +12,7 @@
1212 * repository's origin.
1313 */
1414
15 import { weekDigest, weekLines } from "../core/dataset.ts";
1516 import type { Database } from "bun:sqlite";
1617 import type { App } from "../app.ts";
1718 import {
@@ -407,6 +408,21 @@ export async function driveRepo(
407408 return "idle";
408409 }
409410
411 /**
412 * The last week of this repository as the dataset holds it (`core/dataset.ts`):
413 * what landed, what parked, what it cost, which checks failed. The lines a
414 * planner is given before it plans, so the wave it proposes can answer them.
415 * A repository the dataset cannot read yields nothing, and plans as it did.
416 */
417 export function lastWeekFor(app: App, repo: Repo, now = new Date()): string[] {
418 try {
419 return weekLines(weekDigest(app.db, repo.id, now));
420 } catch (e) {
421 log.warn("last week unreadable", { repo: `${repo.ownerName}/${repo.name}`, error: String(e) });
422 return [];
423 }
424 }
425
410426 /** The map is thin below this many ready issues; the planner refills it. */
411427 const THIN_MAP = 3;
412428
src/crew/brief.ts +8
@@ -164,6 +164,8 @@ export interface TaskInput extends BriefInput {
164164 readonly looks?: readonly string[] | undefined;
165165 /** For a planner: the issues the crew parked twice, with why. */
166166 readonly parkedTwice?: readonly HandedOver[] | undefined;
167 /** For a planner: what the last week's dataset says (`autonomy.lastWeekFor`). */
168 readonly lastWeek?: readonly string[] | undefined;
167169 /** For a planner: the issue deferred work waits behind, if there is one. */
168170 readonly laterGate?: number | undefined;
169171 }
@@ -246,6 +248,12 @@ function taskBody(input: TaskInput): string {
246248 for (const c of talk) out.push(quote(c.authorName, c.body));
247249 }
248250 if (handed.length > 0) out.push("", ...handed);
251 if (input.role === "planner" && (input.lastWeek ?? []).length > 0)
252 out.push(
253 "",
254 ...input.lastWeek!,
255 `Plan with it: say so in the wave you propose — comment on this issue, starting "Last week:", in two sentences: what landed, parked and cost, and how this wave answers it.`,
256 );
249257 out.push(
250258 "",
251259 `Work it on the branch \`${input.branch}\` and push when done.`,
src/crew/runner.ts +2
@@ -82,6 +82,7 @@ import {
8282 whenText,
8383 } from "./limits.ts";
8484 import { interruptedSummary } from "./interrupted.ts";
85 import { lastWeekFor } from "./autonomy.ts";
8586 import { laterGate } from "./later.ts";
8687 import { parkedTwice } from "./parks.ts";
8788 import { noteLimit } from "../core/standing.ts";
@@ -810,6 +811,7 @@ async function work(
810811 ? {
811812 parkedTwice: parkedTwice(app.db, [repo]),
812813 laterGate: laterGate(app.db, repo.id),
814 lastWeek: lastWeekFor(app, repo),
813815 }
814816 : {}),
815817 checkKind:
src/http/server.ts +2
@@ -82,6 +82,7 @@ import { confirmPage, searchPage } from "../web/pages/search.ts";
8282 import { followingSubmit } from "../web/pages/following.ts";
8383 import { reconnectSubmit } from "../web/pages/frozen.ts";
8484 import { activityAtom } from "../web/feeds.ts";
85 import { dataPage } from "../web/pages/data.ts";
8586 import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
8687 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
8788 import {
@@ -570,6 +571,7 @@ export function buildRouter(): Router<Handler> {
570571 router.add("GET", "/-/confirm", confirmPage);
571572 router.add("GET", "/new", newRepoPage);
572573 router.add("GET", "/audit", auditPage);
574 router.add("GET", "/data", dataPage);
573575 router.add("GET", "/audit.csv", auditCsv);
574576 router.add("POST", "/audit/:owner/:name/probe", auditProbeSubmit);
575577 router.add("POST", "/new", newRepoSubmit);
src/main.ts +5
@@ -21,6 +21,7 @@ import { resolveAppDomain } from "./apps/host.ts";
2121 import { requeueAbandonedChecks, startChecks } from "./checks/service.ts";
2222 import { startLooks } from "./looks/service.ts";
2323 import { startProbes } from "./contract/probes.ts";
24 import { startDatasetNightly } from "./actions/dataset.ts";
2425 import { startSnapshots } from "./snapshot/service.ts";
2526 import { resolveDestination } from "./snapshot/destination.ts";
2627 import { releaseOrphans } from "./core/run_secret.ts";
@@ -254,6 +255,9 @@ const snapshots = startSnapshots(
254255 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
255256 },
256257 );
258 // The dataset: nightly, to the private repository FORGE_DATASET_REPO names
259 // (`owner/data`); off without it.
260 const dataset = startDatasetNightly(app, process.env["FORGE_DATASET_REPO"]);
257261 const crewHeldOff = crewOffInPreview();
258262 if (appsOn && crewHeldOff)
259263 app.log.info(CREW_OFF_IN_PREVIEW, {
@@ -413,6 +417,7 @@ function shutdown(): void {
413417 looks?.stop(),
414418 probes?.stop(),
415419 snapshots.stop(),
420 dataset.stop(),
416421 ])
417422 .catch(() => {})
418423 .then(() => {
src/web/pages/data.ts added +150
@@ -0,0 +1,150 @@
1 /**
2 * The dataset's page (`core/dataset.ts`), for a forge admin: what it holds,
3 * how big, when it last grew, and the questions it already answers. The
4 * answers are read from the same rows the export writes, held for a minute
5 * so the page stays quick on a forge with a long history.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { lastExport } from "../../actions/dataset.ts";
10 import {
11 costPerLanded,
12 datasetStats,
13 failingChecks,
14 Privacy,
15 pullFacts,
16 checksRows,
17 tellToShipped,
18 usageRows,
19 type AgentCost,
20 type FailingTest,
21 type PillarTime,
22 } from "../../core/dataset.ts";
23 import type { Ctx } from "../../http/context.ts";
24 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
25 import { html, type Html } from "../html.ts";
26 import { page } from "../layout.ts";
27 import { card, empty, icon, time } from "../ui.ts";
28 import { accountSections } from "./origins.ts";
29
30 interface Answers {
31 readonly at: number;
32 readonly tell: PillarTime[];
33 readonly cost: AgentCost[];
34 readonly failing: FailingTest[];
35 }
36
37 const HELD_MS = 60_000;
38 const held = new WeakMap<Database, Answers>();
39
40 function answers(db: Database): Answers {
41 const have = held.get(db);
42 if (have && Date.now() - have.at < HELD_MS) return have;
43 // Names are never shown from these rows, so the salt is immaterial.
44 const p = new Privacy("page", db);
45 const facts = pullFacts(db, p, {});
46 const fresh: Answers = {
outdated

Low: on a cache miss this runs a synchronous full scan of pulls and usage, and usageRows runs pullFacts again. Compute it once, or do it off the request path.

47 at: Date.now(),
48 tell: tellToShipped(facts.rows),
49 cost: costPerLanded(usageRows(db, p, {}, facts)),
50 failing: failingChecks(checksRows(db, p)),
51 };
52 held.set(db, fresh);
53 return fresh;
54 }
55
56 const bytes = (n: number): string =>
57 n >= 1_048_576 ? `${(n / 1_048_576).toFixed(1)} MB` : n >= 1024 ? `${(n / 1024).toFixed(1)} kB` : `${n} B`;
58 const usd = (n: number): string => `$${n.toFixed(2)}`;
59 const none = (what: string): Html => html`<p class="card-body muted small">${what}</p>`;
60
61 // GET /data
62 export function dataPage(ctx: Ctx): Response {
63 if (!ctx.auth.user) return signInFirst(ctx);
64 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
65 const stats = datasetStats(ctx.app.db);
66 const last = lastExport(ctx.app);
67 const a = answers(ctx.app.db);
68 return page({
69 ctx,
70 title: "Dataset",
71 description: "What the forge's dataset holds, and what it already answers.",
72 body: html`<div class="page-head">
73 <h1>Dataset</h1>
74 <p class="muted">
75 The forge's events, decisions, runs, checks, pulls and usage as one
76 documented dataset, exported nightly to a private repository
77 (<code>FORGE_DATASET_REPO</code>). Personal data is hashed or removed
78 by one rule; <code>docs/DATASET.md</code> names every field.
79 ${last
80 ? html`Last export ${time(last.at)}${last.commit
81 ? html`, commit <code>${last.commit.slice(0, 8)}</code>`
82 : null}.`
83 : "Nothing has been exported yet."}
84 </p>
85 </div>
86 ${settingsLayout(
87 accountSections("dataset", { admin: true }),
88 html`${card(
89 html`<table class="table" data-dense>
90 <thead>
91 <tr>
92 <th scope="col">Table</th>
93 <th scope="col" class="num">Rows now</th>
94 <th scope="col">Newest row</th>
95 <th scope="col" class="num">Exported rows</th>
96 <th scope="col" class="num">Exported size</th>
97 </tr>
98 </thead>
99 <tbody>
100 ${stats.map((s) => {
101 const x = last?.tables[s.table];
102 return html`<tr data-table="${s.table}">
103 <th scope="row"><code>${s.table}</code></th>
104 <td class="num">${String(s.rows)}</td>
105 <td>${s.latest ? time(s.latest) : "—"}</td>
106 <td class="num">${x ? String(x.rows) : "—"}</td>
107 <td class="num">${x ? bytes(x.bytes) : "—"}</td>
108 </tr>`;
109 })}
110 </tbody>
111 </table>`,
112 { head: html`${icon("activity")}<h2>What it holds</h2>`, pad: false },
113 )}
114 ${card(
115 a.tell.length === 0
116 ? none("No pull has merged that closed a person's issue yet.")
117 : html`<table class="table" data-dense data-question="tell-to-shipped">
118 <thead><tr><th scope="col">Pillar</th><th scope="col" class="num">Shipped</th><th scope="col" class="num">Median hours, tell to shipped</th></tr></thead>
119 <tbody>${a.tell.map((t) => html`<tr><th scope="row">${t.pillar}</th><td class="num">${String(t.shipped)}</td><td class="num">${String(t.medianHours)}</td></tr>`)}</tbody>
120 </table>`,
121 { head: html`<h2>Time from tell to shipped, by pillar</h2>`, pad: false },
122 )}
123 ${card(
124 a.cost.length === 0
125 ? none("No agent run has spent anything yet.")
126 : html`<table class="table" data-dense data-question="cost-per-landed">
127 <thead><tr><th scope="col">Agent</th><th scope="col">Model</th><th scope="col" class="num">Landed</th><th scope="col" class="num">Spent</th><th scope="col" class="num">Per landed pull</th></tr></thead>
128 <tbody>${a.cost.map((c) => html`<tr><th scope="row">${c.agent}</th><td>${c.model}</td><td class="num">${String(c.landed)}</td><td class="num">${usd(c.costUsd)}</td><td class="num">${c.perLandedUsd === null ? "—" : usd(c.perLandedUsd)}</td></tr>`)}</tbody>
129 </table>`,
130 { head: html`<h2>Cost per landed pull, by agent and model</h2>`, pad: false },
131 )}
132 ${card(
133 a.failing.length === 0
134 ? none("No check has failed with a test named.")
135 : html`<table class="table" data-dense data-question="failing-checks">
136 <thead><tr><th scope="col">Test</th><th scope="col" class="num">Failures</th></tr></thead>
137 <tbody>${a.failing.map((t) => html`<tr><th scope="row">${t.name}</th><td class="num">${String(t.failures)}</td></tr>`)}</tbody>
138 </table>`,
139 { head: html`<h2>Which checks fail most</h2>`, pad: false },
140 )}
141 ${card(
142 none(
143 "Not answerable yet: the forge does not record which pages are opened. Usage today is the agents' runs; a page-open record is the next table.",
144 ),
145 { head: html`<h2>Which pages nobody opens</h2>`, pad: false },
146 )}`,
147 "Account settings",
148 )}`,
149 });
150 }
src/web/pages/origins.ts +7
@@ -78,6 +78,7 @@ export type AccountSection =
7878 | "accounts"
7979 | "subscriptions"
8080 | "backups"
81 | "dataset"
8182 | "secrets"
8283 | "capacity"
8384 | "cloud";
@@ -137,6 +138,12 @@ export function accountSections(
137138 icon: "download" as const,
138139 current: current === "backups",
139140 },
141 {
142 label: "Dataset",
143 href: "/data",
144 icon: "download" as const,
145 current: current === "dataset",
146 },
140147 ]
141148 : []),
142149 {
test/dataset.test.ts added +272
@@ -0,0 +1,272 @@
1 /**
2 * The dataset: each table round-trips through JSONL, no email, token or raw
3 * path with ids reaches any file, the schema names every field exported,
4 * the questions it answers come out right, the nightly export commits to a
5 * private repository only, and the planner is told the last week.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { readFileSync } from "node:fs";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { buildExport, lastExport, publishDataset } from "../src/actions/dataset.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import {
17 costPerLanded,
18 failingChecks,
19 fromJsonl,
20 Privacy,
21 SCHEMA,
22 schemaDocument,
23 TABLES,
24 tableRows,
25 tellToShipped,
26 toJsonl,
27 weekDigest,
28 } from "../src/core/dataset.ts";
29 import type { Repo } from "../src/core/repos.ts";
30 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
31 import { createUser, type User } from "../src/core/users.ts";
32 import { recordDecision } from "../src/core/decisions.ts";
33 import { recordUsage } from "../src/core/usage.ts";
34 import { lastWeekFor } from "../src/crew/autonomy.ts";
35 import { taskPrompt, type TaskInput } from "../src/crew/brief.ts";
36 import { runGit } from "../src/git/env.ts";
37 import type { Ctx } from "../src/http/context.ts";
38 import { dataPage } from "../src/web/pages/data.ts";
39
40 const EMAIL = "[email protected]";
41 const TOKEN = "forge_AbCdEf0123456789AbCdEf0123456789xyz";
42 const PATH = "/data/crew/scout/01m23vygyffx5hg2f5vm8r74sr/1139/src/x.ts";
43 const LONG = "Zx9Qw8Er7Ty6Ui5Op4As3Df2Gh1Jk0Lm9Nb8Vc7";
44 const NOW = new Date("2026-10-14T12:00:00.000Z");
45
46 describe("the dataset", () => {
47 let dir: string;
48 let app: App;
49 let alice: User;
50 let bob: User;
51 let repo: Repo;
52 let data: Repo;
53 let agentId: string;
54
55 const issue = (id: string, n: number, author: string, kind: string, at: string, body = "", title = "t") =>
56 app.db
57 .query(
58 "INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
59 )
60 .run(id, repo.id, n, kind, title, body, author, at);
61
62 beforeAll(async () => {
63 dir = await mkdtemp(join(tmpdir(), "forge-dataset-"));
64 app = createApp({ dataDir: dir, port: 0 });
65 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
66 const b = await createUser(app.db, { trusted: true, username: "bobby", email: EMAIL, password: "a-good-passphrase" });
67 if (!a.ok || !b.ok) throw new Error("users");
68 alice = a.value;
69 bob = b.value;
70 const ag = await createAgent(app, alice, { username: "builder", model: "sonnet" });
71 if (!ag.ok) throw new Error(String(ag.error));
72 agentId = ag.value.user.id;
73 const r = await createRepo(app, alice, { name: "app", visibility: "private" });
74 const d = await createRepo(app, alice, { name: "data", visibility: "private" });
75 if (!r.ok || !d.ok) throw new Error("repos");
76 repo = r.value;
77 data = d.value;
78
79 // Bob told the forge (#1); the builder opened pull #2 closing it; it merged 10 h later.
80 issue("i1", 1, bob.id, "issue", "2026-10-12T00:00:00.000Z", `mail ${EMAIL} ${TOKEN}`, `fix ${PATH}`);
81 issue("i2", 2, agentId, "pull", "2026-10-12T05:00:00.000Z", "Closes #1");
82 app.db
83 .query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at, merged_by) VALUES ('i2','main','builder/1','a','b','2026-10-12T10:00:00.000Z',?1)")
84 .run(alice.id);
85 app.db.query("INSERT INTO comment (id, issue_id, author_id, body, created_at) VALUES ('c1','i1',?1,'Parked by the crew: nope',?2)").run(alice.id, "2026-10-13T00:00:00.000Z");
86
87 const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: "i1", actorId: agentId });
88 claimRun(app.db, run.id);
89 finishRun(app.db, run.id, { state: "ok", summary: `edited ${PATH} for ${EMAIL}`, costUsd: 1.5, turns: 4 });
90 recordUsage(app.db, { runId: run.id, repoId: repo.id, issueId: "i1", agentId, subscriptionId: "platform", tokensIn: 10, tokensOut: 5, costUsd: 1.5, wallMs: 900, outcome: "ok", at: "2026-10-12T06:00:00.000Z" });
91 const check = createRun(app.db, { repoId: repo.id, kind: "check", issueId: "i2" });
92 claimRun(app.db, check.id);
93 finishRun(app.db, check.id, { state: "failed", summary: "1 failed", checkDetail: { passed: 3, failed: 1, names: [`test/a.test.ts > breaks for ${EMAIL}`] } });
94 recordDecision(app.db, { kind: "land", repoId: repo.id, issueId: "i2", state: { note: PATH, apiKey: TOKEN, by: "bobby", long: LONG }, answer: "yes", p: 0.9, by: "rule", ms: 3 });
95 app.bus.append({ kind: "pull.merged", repoId: repo.id, actorId: bob.id, payload: { email: EMAIL, note: `at ${PATH}`, token: TOKEN, author: "bobby", agent: "builder" } });
96 });
97 afterAll(async () => {
98 app.close();
99 await rm(dir, { recursive: true, force: true });
100 });
101
102 test("every table round-trips through JSONL, with rows to read back", () => {
103 const p = new Privacy("salt", app.db);
104 for (const t of TABLES) {
105 const rows = tableRows(app.db, p, t);
106 expect(rows.length).toBeGreaterThan(0);
107 expect(fromJsonl(toJsonl(t, rows))).toEqual(rows.map((r) => Object.fromEntries(SCHEMA[t].fields.map((f) => [f.name, r[f.name] ?? null]))));
108 }
109 });
110
111 test("the schema names every field a row carries, and the document is the committed one", () => {
112 const p = new Privacy("salt", app.db);
113 const doc = schemaDocument();
114 for (const t of TABLES) {
115 const fields = SCHEMA[t].fields.map((f) => f.name);
116 for (const row of tableRows(app.db, p, t)) expect(Object.keys(row).sort()).toEqual([...fields].sort());
117 for (const f of fields) expect(doc).toContain(`| \`${f}\` |`);
118 for (const f of SCHEMA[t].fields) expect(f.meaning.length).toBeGreaterThan(5);
119 }
120 expect(readFileSync(join(import.meta.dir, "..", "docs", "DATASET.md"), "utf8")).toBe(`${doc}\n`);
121 });
122
123 test("no email, token or raw path appears in any file, and people are hashed the same everywhere", () => {
124 const { files } = buildExport(app, NOW);
125 const all = Object.entries(files).filter(([n]) => n !== "SCHEMA.md").map(([, t]) => t).join("\n");
126 for (const secret of [EMAIL, "[email protected]", TOKEN, LONG, PATH, "/data/crew", "01m23vygyffx5hg2f5vm8r74sr", "apiKey\":\"forge_", "bobby", "a-good-passphrase"])
127 expect(all).not.toContain(secret);
128 expect(all).not.toMatch(/[\w.+-]+@[\w-]+\.[a-z]{2,}/i);
129 expect(all).toContain("[email]");
130 expect(all).toContain("[path]");
131 expect(all).toContain("[redacted]");
132 expect(all).toContain("builder");
133 const p = new Privacy("salt", app.db);
134 const ev = tableRows(app.db, p, "events").find((e) => e["kind"] === "pull.merged")!;
135 expect(ev["actor"]).toBe(p.who(bob.id));
136 expect(String(ev["actor"])).toMatch(/^p_[0-9a-f]{12}$/);
137 expect(new Privacy("other", app.db).who(bob.id)).not.toBe(p.who(bob.id));
138 // The salt itself stays out of every file.
139 const salt = readFileSync(join(dir, "dataset", "salt"), "utf8").trim();
140 expect(all).not.toContain(salt);
141 });
142
143 test("the questions it answers come out of the rows", () => {
144 const p = new Privacy("salt", app.db);
145 const pulls = tableRows(app.db, p, "pulls");
146 expect(pulls[0]!["tell_to_shipped_hours"]).toBe(10);
147 expect(tellToShipped(pulls)).toEqual([{ pillar: "no pillar", shipped: 1, medianHours: 10 }]);
148 expect(costPerLanded(tableRows(app.db, p, "usage"))).toEqual([{ agent: "builder", model: "sonnet", landed: 1, costUsd: 1.5, perLandedUsd: 1.5 }]);
149 expect(failingChecks(tableRows(app.db, p, "checks"))).toEqual([{ name: "test/a.test.ts > breaks for [email]", failures: 1 }]);
150 });
151
152 test("the last week is landed, parked, cost and failures, and the planner is told", () => {
153 const d = weekDigest(app.db, repo.id, NOW);
154 expect(d).toMatchObject({ landed: 1, parked: 1, costUsd: 1.5, perLandedUsd: 1.5, checksFailed: 1 });
155 expect(weekDigest(app.db, repo.id, new Date("2026-12-01T00:00:00Z"))).toMatchObject({ landed: 0, parked: 0, costUsd: 0, perLandedUsd: null });
156 const lines = lastWeekFor(app, repo, NOW);
157 const prompt = (role: string) =>
158 taskPrompt({
159 agent: { user: { username: "planner", displayName: "" }, brief: "" },
160 repo: { ownerName: "alice", name: "app", defaultBranch: "main" },
161 issue: { number: 9, title: "Direction", body: "go", authorName: "alice" },
162 reason: "assigned",
163 role,
164 comments: [],
165 reviews: [],
166 reviewComments: [],
167 since: "",
168 branch: "planner/9",
169 lastWeek: lines,
170 } as unknown as TaskInput);
171 expect(prompt("planner")).toContain("Last week, from the forge's dataset");
172 expect(prompt("planner")).toContain("Landed: 1 pull");
173 expect(prompt("planner")).toContain('starting "Last week:"');
174 expect(prompt("builder")).not.toContain("Last week");
175 });
176
177 test("it is published to a private repository, once, and never to a public one", async () => {
178 expect(await publishDataset(app, "alice/nowhere")).toMatchObject({ ok: false });
179 const pub = await createRepo(app, alice, { name: "open", visibility: "public" });
180 if (!pub.ok) throw new Error("repo");
181 expect(await publishDataset(app, "alice/open")).toMatchObject({ ok: false, error: expect.stringContaining("not private") });
182 const first = await publishDataset(app, "alice/data", NOW);
183 expect(first).toMatchObject({ ok: true, unchanged: false });
184 const bare = join(app.reposRoot, "alice", "data.git");
185 const shown = await runGit(["show", `${data.defaultBranch}:SCHEMA.md`], { cwd: bare });
186 expect(shown.ok && shown.value.toString()).toContain("# The forge's dataset");
187 const events = await runGit(["show", `${data.defaultBranch}:events.jsonl`], { cwd: bare });
188 expect(events.ok && events.value.toString()).toContain("pull.merged");
189 expect(lastExport(app)?.tables.events.rows).toBeGreaterThan(0);
190 expect(await publishDataset(app, "alice/data", new Date(NOW.getTime() + 1000))).toEqual({ ok: true, unchanged: true });
191 });
192
193 test("/data is for the admin alone", async () => {
194 expect(Object.keys(buildExport(app, NOW).files).sort()).toEqual([...TABLES.map((t) => `${t}.jsonl`), "SCHEMA.md"].sort());
195 const get = (user: User | undefined) =>
196 dataPage({
197 app,
198 request: new Request("http://forge.test/data"),
199 url: new URL("http://forge.test/data"),
200 params: {},
201 auth: { user, scope: undefined, via: user ? "session" : "none" },
202 theme: undefined,
203 } satisfies Ctx);
204 const page = get(alice);
205 expect(page.status).toBe(200);
206 const text = await page.text();
207 for (const t of TABLES) expect(text).toContain(`data-table="${t}"`);
208 expect(text).toContain("Time from tell to shipped");
209 expect(text).not.toContain(EMAIL);
210 expect(get(bob).status).toBe(404);
211 expect(get(undefined).status).not.toBe(200);
212 });
213 });
214
215 describe("the dataset keeps to its audience", () => {
216 let dir: string;
217 let app: App;
218 let alice: User;
219 let carol: User;
220
221 beforeAll(async () => {
222 dir = await mkdtemp(join(tmpdir(), "forge-dataset-aud-"));
223 app = createApp({ dataDir: dir, port: 0 });
224 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
225 const c = await createUser(app.db, { trusted: true, username: "carolyn", email: "[email protected]", password: "a-good-passphrase" });
226 if (!a.ok || !c.ok) throw new Error("users");
227 alice = a.value;
228 carol = c.value;
229 });
230 afterAll(async () => {
231 app.close();
232 await rm(dir, { recursive: true, force: true });
233 });
234
235 test("admin-only, app-only, sealed and other people's events never reach events.jsonl", async () => {
236 const mine = await createRepo(app, alice, { name: "mine", visibility: "private" });
237 const hers = await createRepo(app, carol, { name: "hers", visibility: "private" });
238 const data = await createRepo(app, alice, { name: "data", visibility: "private" });
239 if (!mine.ok || !hers.ok || !data.ok) throw new Error("repos");
240 const secretUrl = "https://hooks.example.com/services/T0AAAAAAA/B0BBBBBBB/xYz12345abcdEFGH";
241 app.bus.append({ kind: "webhook.created", repoId: mine.value.id, actorId: alice.id, payload: { url: secretUrl } });
242 app.bus.append({ kind: "app.env_set", repoId: mine.value.id, actorId: alice.id, payload: { name: "DB_PASSWORD_NAME" } });
243 app.bus.append({ kind: "run.finished", repoId: mine.value.id, actorId: alice.id, payload: { summary: "private output" } });
244 app.bus.append({ kind: "issue.opened", repoId: hers.value.id, actorId: carol.id, payload: { number: 1, title: "carol's own" } });
245 app.db
246 .query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, created_at, sealed) VALUES ('s1',?1,7,'issue','vuln','details',?2,'2026-10-12T00:00:00.000Z',1)")
247 .run(mine.value.id, alice.id);
248 app.bus.append({ kind: "issue.opened", repoId: mine.value.id, actorId: alice.id, payload: { number: 7, title: "vuln" } });
249 app.bus.append({ kind: "issue.opened", repoId: mine.value.id, actorId: alice.id, payload: { number: 8, title: "plain issue" } });
250
251 const built = buildExport(app, NOW, alice.id);
252 const events = built.files["events.jsonl"]!;
253 for (const leak of ["webhook.created", "hooks.example.com", "xYz12345", "app.env_set", "DB_PASSWORD_NAME", "run.finished", "private output", "carol's own", "vuln"])
254 expect(events).not.toContain(leak);
255 expect(events).toContain("plain issue");
256 expect(built.files["pulls.jsonl"]).not.toContain("vuln");
257 // Every row belongs to a repository the owner owns.
258 for (const t of TABLES)
259 for (const row of fromJsonl(built.files[`${t}.jsonl`]!))
260 if (row["repo_id"] !== null) expect([mine.value.id, data.value.id]).toContain(String(row["repo_id"]));
261 });
262
263 test("one person has one name, in an actor and in a payload and in free text", () => {
264 const p = new Privacy("salt", app.db);
265 expect(p.name("carolyn")).toBe(String(p.who(carol.id)));
266 expect(p.name("CarolYN")).toBe(String(p.who(carol.id)));
267 expect(p.text("thanks @carolyn and carolyn!")).toBe(`thanks @${p.who(carol.id)} and ${p.who(carol.id)}!`);
268 app.bus.append({ kind: "issue.assigned", repoId: undefined, actorId: carol.id, payload: { assignee: "carolyn" } });
269 const row = tableRows(app.db, p, "events").find((e) => e["kind"] === "issue.assigned")!;
270 expect(String(row["actor"])).toBe(JSON.parse(String(row["payload"])).assignee);
271 });
272 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs