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 #16693
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/1139-a-dataset-as-we-go-the-forge-s-events-de → main 0 commits fork 6 threads · 6 unresolved
23 files
changed +1827
−4
- docs/DATASET.md
- docs/REFERENCE.md
- docs/design/attention-budget.json
- docs/design/audit.md
- docs/features/dataset.md
- scripts/export-dataset.ts
- src/actions/dataset.ts
- src/core/dataset.ts
- src/core/reserved.ts
- src/crew/autonomy.ts
- src/crew/brief.ts
- src/crew/runner.ts
- src/http/marks/dataset.json
- src/http/server.ts
- src/main.ts
- src/tui/screens/dataset.ts
- src/view/doc_sections.ts
- src/web/pages/dataset.ts
- src/web/pages/origins.ts
- test/dataset.test.ts
- test/forge-looks.test.ts
- test/job-slices.test.ts
- test/palette-roster.test.ts
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 `/dataset`; 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 three 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 |
docs/REFERENCE.md +1
| @@ -514,6 +514,7 @@ Once a minute the forge measures its landing rate, names the one cause binding i | ||
| 514 | 514 | - [](README.md): the documentation index, by what you want to do. |
| 515 | 515 | - [](REFERENCE.md): this page. |
| 516 | 516 | - The guide, in order: [](guide-what-a-forge-is.md), [](guide-first-app.md), [](guide-tell-the-crew.md), [](guide-ship-and-undo.md), [](guide-your-apps.md), [](guide-hosting.md), [](guide-own-ai.md), [](guide-agents.md), [](guide-backups-moving.md), [](guide-settings.md), [](guide-when-wrong.md). |
| 517 | - [](DATASET.md): the forge's dataset, one JSONL file per table, every field named. | |
| 517 | 518 | - [](WRITING.md): how to write documentation for the forge. |
| 518 | 519 | - [](DEVELOP.md) — developing the forge: tests, checks, the gate, lint and types. |
| 519 | 520 | - [](DEPENDENCIES.md) — every package in `package.json` and why it is there; the gate refuses a new one without its line. |
docs/design/attention-budget.json +3 −3
| @@ -113,16 +113,16 @@ | ||
| 113 | 113 | }, |
| 114 | 114 | "settings": { |
| 115 | 115 | "390": { |
| 116 | "words": 146, | |
| 116 | "words": 147, | |
| 117 | 117 | "blocks": 32, |
| 118 | 118 | "colours": 1 |
| 119 | 119 | }, |
| 120 | 120 | "1280": { |
| 121 | "words": 146, | |
| 121 | "words": 147, | |
| 122 | 122 | "blocks": 32, |
| 123 | 123 | "colours": 1 |
| 124 | 124 | }, |
| 125 | "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had." | |
| 125 | "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word." | |
| 126 | 126 | }, |
| 127 | 127 | "search": { |
| 128 | 128 | "390": { |
docs/design/audit.md +1
| @@ -66,6 +66,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 66 | 66 | - `/boards/data` — `pages/boards.ts` · the boards' query/data surface · `/board` · none seen. |
| 67 | 67 | - `/asks` — `studio/asks_page.ts` · what the crew is waiting on me for · `/` "needs me" list · colours 2. |
| 68 | 68 | - `/data` — `pages/data.ts` · the SQLite files I may see, their tables and rows, secrets masked · `/system` · none seen. |
| 69 | - `/dataset` — `pages/dataset.ts` · what the forge's dataset holds and what it already answers, admin only · Settings, Dataset · none seen. | |
| 69 | 70 | - `/asked` — `studio/asked_page.ts` · what I answered, as a record · `/asks` · none seen. |
| 70 | 71 | - `/review` — `studio/review_page.ts` · every ask waiting on me, one row each, newest first · `/asks` (same asks, with buttons) · none seen. |
| 71 | 72 | - `/flow` — `pages/flow.ts` · the pipeline from ready issue to live deploy, and the bottleneck · `/system`, `/board`, `/` · none seen. A topbar button points here. |
docs/features/dataset.md added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | --- | |
| 2 | topic: Backups and moving | |
| 3 | row: The forge's events and decisions as a dataset in a private repository | |
| 4 | --- | |
| 5 | # The dataset | |
| 6 | ||
| 7 | The forge's events, decisions, runs, checks, pulls and usage as JSONL, one file per table, every field named in [](../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 `/dataset` (Settings → Dataset); the terminal has the same view under `Dataset` in the palette (`src/tui/screens/dataset.ts`); it has no MCP view yet. |
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); |
src/actions/dataset.ts added +199
| @@ -0,0 +1,199 @@ | ||
| 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 { during } from "../perf/jobs.ts"; | |
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { | |
| 16 | checksRows, | |
| 17 | costPerLanded, | |
| 18 | failingChecks, | |
| 19 | pullFacts, | |
| 20 | schemaDocument, | |
| 21 | tellToShipped, | |
| 22 | usageRows, | |
| 23 | TABLES, | |
| 24 | tableRows, | |
| 25 | toJsonl, | |
| 26 | Privacy, | |
| 27 | type AgentCost, | |
| 28 | type FailingTest, | |
| 29 | type PillarTime, | |
| 30 | type TableName, | |
| 31 | } from "../core/dataset.ts"; | |
| 32 | import { getRepo } from "../core/repos.ts"; | |
| 33 | import { getUserById } from "../core/users.ts"; | |
| 34 | import { commitToBranch } from "./repos.ts"; | |
| 35 | ||
| 36 | export interface TableFile { | |
| 37 | readonly rows: number; | |
| 38 | readonly bytes: number; | |
| 39 | readonly sha256: string; | |
| 40 | /** | |
| 41 | * What decides whether the table grew: the same as `sha256`, except that | |
| 42 | * `events` leaves out `push` events, because committing the export is one. | |
| 43 | */ | |
| 44 | readonly stable: string; | |
| 45 | } | |
| 46 | ||
| 47 | export interface Manifest { | |
| 48 | /** When this export was taken (UTC). */ | |
| 49 | readonly at: string; | |
| 50 | /** The commit it landed in; empty when written to a directory only. */ | |
| 51 | readonly commit: string; | |
| 52 | readonly tables: Readonly<Record<TableName, TableFile>>; | |
| 53 | } | |
| 54 | ||
| 55 | const dirOf = (app: App): string => join(app.config.dataDir, "dataset"); | |
| 56 | ||
| 57 | /** The secret that names people; made once, kept 0600, never exported. */ | |
| 58 | export function datasetSalt(app: App): string { | |
| 59 | const dir = dirOf(app); | |
| 60 | const path = join(dir, "salt"); | |
| 61 | if (existsSync(path)) return readFileSync(path, "utf8").trim(); | |
| 62 | mkdirSync(dir, { recursive: true }); | |
| 63 | const salt = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex"); | |
| 64 | writeFileSync(path, `${salt}\n`, { mode: 0o600 }); | |
| 65 | return salt; | |
| 66 | } | |
| 67 | ||
| 68 | export function lastExport(app: App): Manifest | undefined { | |
| 69 | try { | |
| 70 | return JSON.parse(readFileSync(join(dirOf(app), "manifest.json"), "utf8")) as Manifest; | |
| 71 | } catch { | |
| 72 | return undefined; | |
| 73 | } | |
| 74 | } | |
| 75 | ||
| 76 | export interface Built { | |
| 77 | readonly files: Record<string, string>; | |
| 78 | readonly manifest: Manifest; | |
| 79 | } | |
| 80 | ||
| 81 | /** Every file of an export, in memory. */ | |
| 82 | export function buildExport(app: App, now = new Date(), ownerId?: string): Built { | |
| 83 | // What leaves the forge is what its destination's owner already owns: with | |
| 84 | // no owner (a local `--out`) it is the forge's admin reading in place. | |
| 85 | const scope = | |
| 86 | ownerId === undefined | |
| 87 | ? undefined | |
| 88 | : new Set( | |
| 89 | app.db | |
| 90 | .query<{ id: string }, [string]>("SELECT id FROM repo WHERE owner_id = ?1") | |
| 91 | .all(ownerId) | |
| 92 | .map((r) => r.id), | |
| 93 | ); | |
| 94 | const w = scope === undefined ? {} : { scope }; | |
| 95 | const p = new Privacy(datasetSalt(app), app.db); | |
| 96 | const files: Record<string, string> = {}; | |
| 97 | const tables = {} as Record<TableName, TableFile>; | |
| 98 | for (const t of TABLES) { | |
| 99 | const rows = tableRows(app.db, p, t, w); | |
| 100 | const text = toJsonl(t, rows); | |
| 101 | files[`${t}.jsonl`] = text; | |
| 102 | const sha = (x: string): string => new Bun.CryptoHasher("sha256").update(x).digest("hex"); | |
| 103 | tables[t] = { | |
| 104 | rows: rows.length, | |
| 105 | bytes: Buffer.byteLength(text), | |
| 106 | sha256: sha(text), | |
| 107 | stable: t === "events" ? sha(toJsonl(t, rows.filter((r) => r["kind"] !== "push"))) : sha(text), | |
| 108 | }; | |
| 109 | } | |
| 110 | files["SCHEMA.md"] = schemaDocument(); | |
| 111 | return { files, manifest: { at: now.toISOString(), commit: "", tables } }; | |
| 112 | } | |
| 113 | ||
| 114 | const grew = (a: Manifest | undefined, b: Manifest): boolean => | |
| 115 | a === undefined || TABLES.some((t) => a.tables[t]?.stable !== b.tables[t].stable); | |
| 116 | ||
| 117 | export type Published = | |
| 118 | | { ok: true; commit: string; unchanged: false; manifest: Manifest } | |
| 119 | | { ok: true; unchanged: true } | |
| 120 | | { ok: false; error: string }; | |
| 121 | ||
| 122 | /** Export to the private repository `owner/name`. Nothing changed is not a commit. */ | |
| 123 | export async function publishDataset(app: App, slug: string, now = new Date()): Promise<Published> { | |
| 124 | const [owner, name, ...rest] = slug.split("/"); | |
| 125 | const repo = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined; | |
| 126 | if (!repo) return { ok: false, error: `no repository ${slug}` }; | |
| 127 | if (repo.visibility !== "private") | |
| 128 | return { ok: false, error: `${slug} is not private; the dataset goes only to a private repository` }; | |
| 129 | const writer = getUserById(app.db, repo.ownerId); | |
| 130 | if (!writer) return { ok: false, error: "the repository has no owner" }; | |
| 131 | const built = buildExport(app, now, repo.ownerId); | |
| 132 | const before = lastExport(app); | |
| 133 | if (before !== undefined && !grew(before, built.manifest)) { | |
| 134 | // Looked and found nothing new: tonight is done, and the commit stays. | |
| 135 | writeFileSync(join(dirOf(app), "manifest.json"), JSON.stringify({ ...before, at: built.manifest.at })); | |
| 136 | return { ok: true, unchanged: true }; | |
| 137 | } | |
| 138 | const files = { ...built.files, "manifest.json": `${JSON.stringify(built.manifest, null, 2)}\n` }; | |
| 139 | const done = await commitToBranch(app, writer, repo, { | |
| 140 | message: `Dataset ${now.toISOString().slice(0, 10)}: ${TABLES.map((t) => `${t} ${built.manifest.tables[t].rows}`).join(", ")}`, | |
| 141 | files: Object.entries(files).map(([path, content]) => ({ path, content })), | |
| 142 | }); | |
| 143 | if (!done.ok) return { ok: false, error: JSON.stringify(done.error) }; | |
| 144 | const manifest: Manifest = { ...built.manifest, commit: done.value.commitOid }; | |
| 145 | mkdirSync(dirOf(app), { recursive: true }); | |
| 146 | writeFileSync(join(dirOf(app), "manifest.json"), JSON.stringify(manifest)); | |
| 147 | return { ok: true, commit: done.value.commitOid, unchanged: false, manifest }; | |
| 148 | } | |
| 149 | ||
| 150 | const NIGHT_MS = 23 * 3_600_000; | |
| 151 | ||
| 152 | /** Nightly: when the last export is a night old, publish. Off without a repository. */ | |
| 153 | export function startDatasetNightly(app: App, slug: string | undefined): { stop: () => void } { | |
| 154 | if (!slug) return { stop: () => {} }; | |
| 155 | let busy = false; | |
| 156 | const tick = async (): Promise<void> => { | |
| 157 | if (busy) return; | |
| 158 | const last = lastExport(app); | |
| 159 | if (last !== undefined && Date.now() - Date.parse(last.at) < NIGHT_MS) return; | |
| 160 | busy = true; | |
| 161 | try { | |
| 162 | const done = await publishDataset(app, slug); | |
| 163 | if (!done.ok) app.log.warn("dataset export failed", { error: done.error }); | |
| 164 | } catch (e) { | |
| 165 | app.log.warn("dataset export failed", { error: String(e) }); | |
| 166 | } finally { | |
| 167 | busy = false; | |
| 168 | } | |
| 169 | }; | |
| 170 | const timer = setInterval(() => void during("dataset-export", tick), 10 * 60_000); | |
| 171 | return { stop: () => clearInterval(timer) }; | |
| 172 | } | |
| 173 | ||
| 174 | /** The questions the dataset already answers, held a minute per database. */ | |
| 175 | export interface Answers { | |
| 176 | readonly at: number; | |
| 177 | readonly tell: PillarTime[]; | |
| 178 | readonly cost: AgentCost[]; | |
| 179 | readonly failing: FailingTest[]; | |
| 180 | } | |
| 181 | ||
| 182 | const HELD_MS = 60_000; | |
| 183 | const held = new WeakMap<Database, Answers>(); | |
| 184 | ||
| 185 | export function datasetAnswers(db: Database): Answers { | |
| 186 | const have = held.get(db); | |
| 187 | if (have && Date.now() - have.at < HELD_MS) return have; | |
| 188 | // Names are never shown from these rows, so the salt is immaterial. | |
| 189 | const p = new Privacy("page", db); | |
| 190 | const facts = pullFacts(db, p, {}); | |
| 191 | const fresh: Answers = { | |
| 192 | at: Date.now(), | |
| 193 | tell: tellToShipped(facts.rows), | |
| 194 | cost: costPerLanded(usageRows(db, p, {}, facts)), | |
| 195 | failing: failingChecks(checksRows(db, p)), | |
| 196 | }; | |
| 197 | held.set(db, fresh); | |
| 198 | return fresh; | |
| 199 | } |
src/core/dataset.ts added +885
| @@ -0,0 +1,885 @@ | ||
| 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 ——— | |
| 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 | /** | |
| 188 | * A long run passes only as a commit id or a slug of words: separators, no digits mixed with | |
| 189 | * letters, no long segment. | |
| 190 | */ | |
| 191 | const plainRun = (run: string): boolean => | |
| 192 | /^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(run) || | |
| 193 | (/[-_/+=]/.test(run) && !(/\d/.test(run) && /[A-Za-z]/.test(run)) && run.split(/[-_/+=]+/).every((x) => x.length < 24)); | |
| 194 | const PATH = /(?<![\w:/.~-])(?:~|\.\.?)?(?:\/[\w.@+=,~-]+){2,}\/?/g; | |
| 195 | ||
| 196 | const SECRET_KEY = /token|secret|password|passwd|cookie|authorization|api[_-]?key|private|credential|email|passphrase|^key$|_key$/i; | |
| 197 | const PERSON_KEY = /^(?:actor|author|user|username|login|owner|by|merged_by|assignee|sender|recipient|requester|creator)(?:_name|_id)?$/i; | |
| 198 | ||
| 199 | const PAYLOAD_CAP = 4000; | |
| 200 | ||
| 201 | export class Privacy { | |
| 202 | private readonly agents: Map<string, string>; | |
| 203 | private readonly agentNames: Set<string>; | |
| 204 | /** Lowercased username → user id, for everyone who is not a crew agent. */ | |
| 205 | private readonly people = new Map<string, string>(); | |
| 206 | private mentions: RegExp | undefined; | |
| 207 | ||
| 208 | constructor( | |
| 209 | private readonly salt: string, | |
| 210 | db: Database, | |
| 211 | ) { | |
| 212 | this.agents = new Map(); | |
| 213 | this.agentNames = new Set(); | |
| 214 | for (const r of db | |
| 215 | .query<{ id: string; username: string }, []>( | |
| 216 | "SELECT id, username FROM user WHERE is_agent = 1", | |
| 217 | ) | |
| 218 | .all()) { | |
| 219 | this.agents.set(r.id, r.username); | |
| 220 | this.agentNames.add(r.username.toLowerCase()); | |
| 221 | } | |
| 222 | for (const r of db | |
| 223 | .query<{ id: string; username: string }, []>( | |
| 224 | "SELECT id, username FROM user WHERE is_agent = 0", | |
| 225 | ) | |
| 226 | .all()) | |
| 227 | this.people.set(r.username.toLowerCase(), r.id); | |
| 228 | } | |
| 229 | ||
| 230 | /** A salted, truncated SHA-256: stable per forge, not reversible. */ | |
| 231 | hash(prefix: string, value: string): string { | |
| 232 | const h = new Bun.CryptoHasher("sha256"); | |
| 233 | h.update(`${this.salt}\0${prefix}\0${value}`); | |
| 234 | return `${prefix}_${h.digest("hex").slice(0, 12)}`; | |
| 235 | } | |
| 236 | ||
| 237 | /** A user id as the dataset names them. */ | |
| 238 | who(userId: string | null): string | null { | |
| 239 | if (userId === null || userId === "") return null; | |
| 240 | return this.agents.get(userId) ?? this.hash("p", userId); | |
| 241 | } | |
| 242 | ||
| 243 | /** A username that appeared in a payload: the same name as its user id gets. */ | |
| 244 | name(value: string): string { | |
| 245 | const k = value.toLowerCase(); | |
| 246 | if (this.agentNames.has(k)) return value; | |
| 247 | // A name no user holds (a deleted account) has no id to share with who(): it hashes by name. | |
| 248 | const id = this.people.get(k); | |
| 249 | return id !== undefined ? this.hash("p", id) : this.hash("p", k); | |
| 250 | } | |
| 251 | ||
| 252 | /** | |
| 253 | * `@name` for anyone, and a person's bare username of three letters or more. | |
| 254 | */ | |
| 255 | private named(s: string): string { | |
| 256 | if (this.people.size === 0) return s; | |
| 257 | this.mentions ??= new RegExp( | |
| 258 | `@([\\w-]+)|(?<![\\w@-])(${[...this.people.keys()] | |
| 259 | .filter((n) => n.length >= 3) | |
| 260 | .sort((a, b) => b.length - a.length) | |
| 261 | .map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) | |
| 262 | .join("|") || "(?!)"})(?![\\w-])`, | |
| 263 | "gi", | |
| 264 | ); | |
| 265 | return s.replace(this.mentions, (m, at: string | undefined, bare: string | undefined) => { | |
| 266 | const who = at ?? bare ?? ""; | |
| 267 | const k = who.toLowerCase(); | |
| 268 | if (this.agentNames.has(k)) return m; | |
| 269 | if (at !== undefined && !this.people.has(k)) return m; | |
| 270 | return `${at !== undefined ? "@" : ""}${this.name(who)}`; | |
| 271 | }); | |
| 272 | } | |
| 273 | ||
| 274 | /** Free text with everything that could identify a person or open a door removed. */ | |
| 275 | text(s: string | null | undefined, cap = 2000): string { | |
| 276 | if (s === null || s === undefined) return ""; | |
| 277 | return this.named(s.replace(EMAIL, "[email]")) | |
| 278 | .replace(URL_CREDS, "//[credentials]@") | |
| 279 | .replace(KNOWN_TOKEN, "[token]") | |
| 280 | .replace(BEARER, "[token]") | |
| 281 | .replace(PATH, "[path]") | |
| 282 | .replace(LONG_RUN, (run) => (plainRun(run) ? run : "[secret]")) | |
| 283 | .slice(0, cap); | |
| 284 | } | |
| 285 | ||
| 286 | private walk(value: unknown, key: string, depth: number): unknown { | |
| 287 | if (depth > 8) return "[deep]"; | |
| 288 | if (SECRET_KEY.test(key)) return value === null || value === undefined ? value : "[redacted]"; | |
| 289 | if (typeof value === "string") | |
| 290 | return PERSON_KEY.test(key) ? this.name(value) : this.text(value, 500); | |
| 291 | if (Array.isArray(value)) | |
| 292 | return value.slice(0, 50).map((v) => this.walk(v, key, depth + 1)); | |
| 293 | if (value !== null && typeof value === "object") { | |
| 294 | const out: Record<string, unknown> = {}; | |
| 295 | for (const [k, v] of Object.entries(value).slice(0, 50)) | |
| 296 | out[this.text(k, 60)] = this.walk(v, k, depth + 1); | |
| 297 | return out; | |
| 298 | } | |
| 299 | return value; | |
| 300 | } | |
| 301 | ||
| 302 | /** A stored JSON text as scrubbed JSON text, capped. */ | |
| 303 | json(stored: string): string { | |
| 304 | let parsed: unknown; | |
| 305 | try { | |
| 306 | parsed = JSON.parse(stored); | |
| 307 | } catch { | |
| 308 | return JSON.stringify(this.text(stored, 500)); | |
| 309 | } | |
| 310 | const out = JSON.stringify(this.walk(parsed, "", 0)); | |
| 311 | return out.length <= PAYLOAD_CAP ? out : JSON.stringify({ truncated: true }); | |
| 312 | } | |
| 313 | } | |
| 314 | ||
| 315 | // ——— the tables ——— | |
| 316 | ||
| 317 | const after = (column: string, w: Window, args: string[]): string => { | |
| 318 | if (w.since === undefined) return ""; | |
| 319 | args.push(w.since); | |
| 320 | return ` AND ${column} >= ?${args.length}`; | |
| 321 | }; | |
| 322 | const inRepo = (column: string, w: Window, args: string[]): string => { | |
| 323 | let out = ""; | |
| 324 | if (w.repoId !== undefined) { | |
| 325 | args.push(w.repoId); | |
| 326 | out += ` AND ${column} = ?${args.length}`; | |
| 327 | } | |
| 328 | if (w.scope !== undefined) { | |
| 329 | args.push(JSON.stringify([...w.scope])); | |
| 330 | out += ` AND ${column} IN (SELECT value FROM json_each(?${args.length}))`; | |
| 331 | } | |
| 332 | return out; | |
| 333 | }; | |
| 334 | /** Rows about a sealed issue or pull stay out of anything scoped. */ | |
| 335 | const unsealed = (column: string, w: Window): string => | |
| 336 | w.scope === undefined | |
| 337 | ? "" | |
| 338 | : ` AND (${column} IS NULL OR ${column} NOT IN (SELECT id FROM issue WHERE sealed = 1))`; | |
| 339 | ||
| 340 | function modelsOf(db: Database): Map<string, string> { | |
| 341 | const out = new Map<string, string>(); | |
| 342 | for (const r of db | |
| 343 | .query<{ user_id: string; model: string }, []>("SELECT user_id, model FROM agent") | |
| 344 | .all()) | |
| 345 | out.set(r.user_id, r.model === "" ? "default" : r.model); | |
| 346 | return out; | |
| 347 | } | |
| 348 | ||
| 349 | /** An event for anyone who reads the repository, about nothing sealed. */ | |
| 350 | function readable( | |
| 351 | db: Database, | |
| 352 | e: { kind: string; repo_id: string | null; payload: string }, | |
| 353 | ): boolean { | |
| 354 | if (eventAudience(e.kind) !== "readers" || e.repo_id === null) return false; | |
| 355 | try { | |
| 356 | const payload = JSON.parse(e.payload) as unknown; | |
| 357 | if (typeof payload !== "object" || payload === null || Array.isArray(payload)) | |
| 358 | return true; | |
| 359 | return !eventSealed(db, { repoId: e.repo_id, payload: payload as Record<string, unknown> }); | |
| 360 | } catch { | |
| 361 | return true; | |
| 362 | } | |
| 363 | } | |
| 364 | ||
| 365 | export function eventsRows(db: Database, p: Privacy, w: Window = {}): Row[] { | |
| 366 | const args: string[] = []; | |
| 367 | const where = after("created_at", w, args) + inRepo("repo_id", w, args); | |
| 368 | return db | |
| 369 | .query< | |
| 370 | { | |
| 371 | id: string; | |
| 372 | seq: number | null; | |
| 373 | kind: string; | |
| 374 | repo_id: string | null; | |
| 375 | actor_id: string | null; | |
| 376 | payload: string; | |
| 377 | created_at: string; | |
| 378 | }, | |
| 379 | string[] | |
| 380 | >(`SELECT id, seq, kind, repo_id, actor_id, payload, created_at FROM event WHERE 1=1${where} ORDER BY id`) | |
| 381 | .all(...args) | |
| 382 | .filter((e) => w.scope === undefined || readable(db, e)) | |
| 383 | .map((e) => ({ | |
| 384 | id: e.id, | |
| 385 | seq: e.seq, | |
| 386 | kind: e.kind, | |
| 387 | repo_id: e.repo_id, | |
| 388 | actor: p.who(e.actor_id), | |
| 389 | payload: p.json(e.payload), | |
| 390 | created_at: e.created_at, | |
| 391 | })); | |
| 392 | } | |
| 393 | ||
| 394 | export function decisionsRows(db: Database, p: Privacy, w: Window = {}): Row[] { | |
| 395 | const args: string[] = []; | |
| 396 | const where = after("created_at", w, args) + inRepo("repo_id", w, args); | |
| 397 | return db | |
| 398 | .query< | |
| 399 | { | |
| 400 | id: string; | |
| 401 | kind: string; | |
| 402 | repo_id: string; | |
| 403 | issue_id: string | null; | |
| 404 | state: string; | |
| 405 | answer: string; | |
| 406 | p: number; | |
| 407 | by: string; | |
| 408 | ms: number; | |
| 409 | created_at: string; | |
| 410 | outcome: string | null; | |
| 411 | outcome_at: string | null; | |
| 412 | }, | |
| 413 | string[] | |
| 414 | >(`SELECT * FROM decision WHERE 1=1${where}${unsealed("issue_id", w)} ORDER BY id`) | |
| 415 | .all(...args) | |
| 416 | .map((d) => ({ | |
| 417 | id: d.id, | |
| 418 | kind: d.kind, | |
| 419 | repo_id: d.repo_id, | |
| 420 | issue_id: d.issue_id, | |
| 421 | state: p.json(d.state), | |
| 422 | answer: p.text(d.answer, 300), | |
| 423 | p: d.p, | |
| 424 | by: p.text(d.by, 100), | |
| 425 | ms: d.ms, | |
| 426 | created_at: d.created_at, | |
| 427 | outcome: d.outcome === null ? null : p.text(d.outcome, 300), | |
| 428 | outcome_at: d.outcome_at, | |
| 429 | })); | |
| 430 | } | |
| 431 | ||
| 432 | interface RunRow { | |
| 433 | id: string; | |
| 434 | repo_id: string; | |
| 435 | kind: string; | |
| 436 | issue_id: string | null; | |
| 437 | env: string; | |
| 438 | commit_oid: string; | |
| 439 | branch: string; | |
| 440 | state: string; | |
| 441 | summary: string; | |
| 442 | actor_id: string | null; | |
| 443 | reason: string; | |
| 444 | cost_usd: number; | |
| 445 | turns: number; | |
| 446 | attempt: number; | |
| 447 | check_detail: string; | |
| 448 | created_at: string; | |
| 449 | started_at: string | null; | |
| 450 | finished_at: string | null; | |
| 451 | } | |
| 452 | ||
| 453 | function runsOf(db: Database, kinds: string, w: Window): RunRow[] { | |
| 454 | const args: string[] = []; | |
| 455 | const where = after("created_at", w, args) + inRepo("repo_id", w, args); | |
| 456 | return db | |
| 457 | .query<RunRow, string[]>( | |
| 458 | `SELECT id, repo_id, kind, issue_id, env, commit_oid, branch, state, summary, actor_id, | |
| 459 | reason, cost_usd, turns, attempt, check_detail, created_at, started_at, finished_at | |
| 460 | FROM run WHERE kind ${kinds}${where}${unsealed("issue_id", w)} ORDER BY id`, | |
| 461 | ) | |
| 462 | .all(...args); | |
| 463 | } | |
| 464 | ||
| 465 | export function runsRows(db: Database, p: Privacy, w: Window = {}): Row[] { | |
| 466 | const models = modelsOf(db); | |
| 467 | return runsOf(db, "IN ('agent','deploy')", w).map((r) => ({ | |
| 468 | id: r.id, | |
| 469 | repo_id: r.repo_id, | |
| 470 | kind: r.kind, | |
| 471 | issue_id: r.issue_id, | |
| 472 | env: r.env, | |
| 473 | branch: p.text(r.branch, 200), | |
| 474 | state: r.state, | |
| 475 | reason: r.reason, | |
| 476 | actor: p.who(r.actor_id), | |
| 477 | model: r.kind === "agent" && r.actor_id !== null ? (models.get(r.actor_id) ?? "") : "", | |
| 478 | // A deploy's summary is the app's own output; only an agent's is the crew's. | |
| 479 | summary: r.kind === "agent" ? p.text(r.summary, 300) : "", | |
| 480 | cost_usd: r.cost_usd, | |
| 481 | turns: r.turns, | |
| 482 | attempt: r.attempt, | |
| 483 | created_at: r.created_at, | |
| 484 | started_at: r.started_at, | |
| 485 | finished_at: r.finished_at, | |
| 486 | })); | |
| 487 | } | |
| 488 | ||
| 489 | export function checksRows(db: Database, p: Privacy, w: Window = {}): Row[] { | |
| 490 | return runsOf(db, "= 'check'", w).map((r) => { | |
| 491 | let detail: { passed?: number; failed?: number; names?: unknown } = {}; | |
| 492 | try { | |
| 493 | if (r.check_detail !== "") detail = JSON.parse(r.check_detail); | |
| 494 | } catch { | |
| 495 | // Unrecognised output: no counts, no names. | |
| 496 | } | |
| 497 | const names = Array.isArray(detail.names) | |
| 498 | ? detail.names.filter((n): n is string => typeof n === "string").slice(0, 50).map((n) => p.text(n, 200)) | |
| 499 | : []; | |
| 500 | const num = (n: unknown): number | null => (typeof n === "number" && Number.isFinite(n) ? n : null); | |
| 501 | return { | |
| 502 | id: r.id, | |
| 503 | repo_id: r.repo_id, | |
| 504 | issue_id: r.issue_id, | |
| 505 | commit_oid: r.commit_oid, | |
| 506 | state: r.state, | |
| 507 | passed: num(detail.passed), | |
| 508 | failed: num(detail.failed), | |
| 509 | failed_names: JSON.stringify(names), | |
| 510 | summary: p.text(r.summary, 300), | |
| 511 | created_at: r.created_at, | |
| 512 | finished_at: r.finished_at, | |
| 513 | duration_ms: | |
| 514 | r.started_at !== null && r.finished_at !== null | |
| 515 | ? Math.max(0, Date.parse(r.finished_at) - Date.parse(r.started_at)) | |
| 516 | : null, | |
| 517 | }; | |
| 518 | }); | |
| 519 | } | |
| 520 | ||
| 521 | export interface PullFacts { | |
| 522 | readonly rows: Row[]; | |
| 523 | /** Issue id → the merged pull that shipped it (the pull's own id too). */ | |
| 524 | readonly shippedBy: Map<string, string>; | |
| 525 | } | |
| 526 | ||
| 527 | export function pullFacts(db: Database, p: Privacy, w: Window): PullFacts { | |
| 528 | const args: string[] = []; | |
| 529 | const where = after("i.created_at", w, args) + inRepo("i.repo_id", w, args); | |
| 530 | const pulls = db | |
| 531 | .query< | |
| 532 | { | |
| 533 | id: string; | |
| 534 | repo_id: string; | |
| 535 | number: number; | |
| 536 | title: string; | |
| 537 | body: string; | |
| 538 | author_id: string; | |
| 539 | state: string; | |
| 540 | created_at: string; | |
| 541 | closed_at: string | null; | |
| 542 | base_branch: string; | |
| 543 | head_branch: string; | |
| 544 | merged_at: string | null; | |
| 545 | merged_by: string | null; | |
| 546 | }, | |
| 547 | string[] | |
| 548 | >( | |
| 549 | `SELECT i.id, i.repo_id, i.number, i.title, i.body, i.author_id, i.state, i.created_at, | |
| 550 | i.closed_at, p.base_branch, p.head_branch, p.merged_at, p.merged_by | |
| 551 | 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`, | |
| 552 | ) | |
| 553 | .all(...args); | |
| 554 | const byNumber = db.query<{ id: string; created_at: string; author_agent: number; sealed: number }, [string, number]>( | |
| 555 | `SELECT i.id, i.created_at, i.sealed, u.is_agent AS author_agent FROM issue i JOIN user u ON u.id = i.author_id | |
| 556 | WHERE i.repo_id = ?1 AND i.number = ?2`, | |
| 557 | ); | |
| 558 | const costOf = db.query<{ c: number | null }, [string]>( | |
| 559 | "SELECT SUM(cost_usd) AS c FROM usage WHERE issue_id = ?1", | |
| 560 | ); | |
| 561 | const pillars = new Map<string, Map<string, string>>(); | |
| 562 | const servedIn = (repoId: string): Map<string, string> => { | |
| 563 | let m = pillars.get(repoId); | |
| 564 | if (m === undefined) { | |
| 565 | const repo = getRepoById(db, repoId); | |
| 566 | m = repo === undefined ? new Map() : servedBy(db, pillarsOf(db, repo)); | |
| 567 | pillars.set(repoId, m); | |
| 568 | } | |
| 569 | return m; | |
| 570 | }; | |
| 571 | const shippedBy = new Map<string, string>(); | |
| 572 | const rows: Row[] = pulls.map((pull) => { | |
| 573 | // A scoped export names no sealed issue a pull closes: not its number, its time, or its cost. | |
| 574 | const found = closesFromBody(pull.body).map((n) => ({ n, c: byNumber.get(pull.repo_id, n) })); | |
| 575 | const kept = found.filter((x) => w.scope === undefined || x.c?.sealed !== 1); | |
| 576 | const closes = kept.map((x) => x.n); | |
| 577 | const closed = kept.map((x) => x.c).filter((c): c is NonNullable<typeof c> => c !== null && c !== undefined); | |
| 578 | const served = servedIn(pull.repo_id); | |
| 579 | const pillar = | |
| 580 | [...closed.map((c) => c.id), pull.id].map((id) => served.get(id)).find((x) => x !== undefined) ?? null; | |
| 581 | const tells = closed.filter((c) => c.author_agent === 0).map((c) => c.created_at).sort(); | |
| 582 | const toldAt = tells[0] ?? null; | |
| 583 | if (pull.merged_at !== null) { | |
| 584 | shippedBy.set(pull.id, pull.id); | |
| 585 | for (const c of closed) shippedBy.set(c.id, pull.id); | |
| 586 | } | |
| 587 | let cost = 0; | |
| 588 | for (const id of new Set([pull.id, ...closed.map((c) => c.id)])) cost += costOf.get(id)?.c ?? 0; | |
| 589 | return { | |
| 590 | id: pull.id, | |
| 591 | repo_id: pull.repo_id, | |
| 592 | number: pull.number, | |
| 593 | title: p.text(pull.title, 300), | |
| 594 | author: p.who(pull.author_id), | |
| 595 | state: pull.merged_at !== null ? "merged" : pull.state, | |
| 596 | base_branch: p.text(pull.base_branch, 200), | |
| 597 | head_branch: p.text(pull.head_branch, 200), | |
| 598 | closes: JSON.stringify(closes), | |
| 599 | pillar, | |
| 600 | told_at: toldAt, | |
| 601 | created_at: pull.created_at, | |
| 602 | closed_at: pull.closed_at, | |
| 603 | merged_at: pull.merged_at, | |
| 604 | merged_by: p.who(pull.merged_by), | |
| 605 | tell_to_shipped_hours: | |
| 606 | toldAt !== null && pull.merged_at !== null | |
| 607 | ? Math.round(((Date.parse(pull.merged_at) - Date.parse(toldAt)) / 3_600_000) * 100) / 100 | |
| 608 | : null, | |
| 609 | cost_usd: Math.round(cost * 1e6) / 1e6, | |
| 610 | }; | |
| 611 | }); | |
| 612 | return { rows, shippedBy }; | |
| 613 | } | |
| 614 | ||
| 615 | export function pullsRows(db: Database, p: Privacy, w: Window = {}): Row[] { | |
| 616 | return pullFacts(db, p, w).rows; | |
| 617 | } | |
| 618 | ||
| 619 | export function usageRows(db: Database, p: Privacy, w: Window = {}, facts?: PullFacts): Row[] { | |
| 620 | const models = modelsOf(db); | |
| 621 | const { shippedBy } = facts ?? pullFacts(db, p, { ...(w.repoId === undefined ? {} : { repoId: w.repoId }), ...(w.scope === undefined ? {} : { scope: w.scope }) }); | |
| 622 | const names = new Map<string, string>(); | |
| 623 | for (const r of db.query<{ id: string; username: string }, []>("SELECT id, username FROM user WHERE is_agent = 1").all()) | |
| 624 | names.set(r.id, r.username); | |
| 625 | const args: string[] = []; | |
| 626 | const where = after("at", w, args) + inRepo("repo_id", w, args); | |
| 627 | return db | |
| 628 | .query< | |
| 629 | { | |
| 630 | run_id: string; | |
| 631 | repo_id: string; | |
| 632 | issue_id: string | null; | |
| 633 | agent_id: string | null; | |
| 634 | subscription_id: string | null; | |
| 635 | kind: string; | |
| 636 | tokens_in: number; | |
| 637 | tokens_out: number; | |
| 638 | cost_usd: number; | |
| 639 | wall_ms: number; | |
| 640 | outcome: string; | |
| 641 | at: string; | |
| 642 | }, | |
| 643 | string[] | |
| 644 | >(`SELECT * FROM usage WHERE 1=1${where}${unsealed("issue_id", w)} ORDER BY run_id`) | |
| 645 | .all(...args) | |
| 646 | .map((u) => ({ | |
| 647 | run_id: u.run_id, | |
| 648 | repo_id: u.repo_id, | |
| 649 | issue_id: u.issue_id, | |
| 650 | agent: u.agent_id === null ? null : (names.get(u.agent_id) ?? p.who(u.agent_id)), | |
| 651 | model: u.agent_id === null ? "default" : (models.get(u.agent_id) ?? "default"), | |
| 652 | subscription: u.subscription_id === null ? null : p.hash("s", u.subscription_id), | |
| 653 | kind: u.kind, | |
| 654 | tokens_in: u.tokens_in, | |
| 655 | tokens_out: u.tokens_out, | |
| 656 | cost_usd: u.cost_usd, | |
| 657 | wall_ms: u.wall_ms, | |
| 658 | outcome: u.outcome, | |
| 659 | landed_pull: u.issue_id === null ? null : (shippedBy.get(u.issue_id) ?? null), | |
| 660 | at: u.at, | |
| 661 | })); | |
| 662 | } | |
| 663 | ||
| 664 | const BUILDERS: Record<TableName, (db: Database, p: Privacy, w?: Window) => Row[]> = { | |
| 665 | events: eventsRows, | |
| 666 | decisions: decisionsRows, | |
| 667 | runs: runsRows, | |
| 668 | checks: checksRows, | |
| 669 | pulls: pullsRows, | |
| 670 | usage: usageRows, | |
| 671 | }; | |
| 672 | ||
| 673 | export function tableRows(db: Database, p: Privacy, table: TableName, w: Window = {}): Row[] { | |
| 674 | return BUILDERS[table](db, p, w); | |
| 675 | } | |
| 676 | ||
| 677 | /** One table as JSONL: one object per line, keys in schema order. */ | |
| 678 | export function toJsonl(table: TableName, rows: readonly Row[]): string { | |
| 679 | const keys = SCHEMA[table].fields.map((x) => x.name); | |
| 680 | return rows.map((r) => JSON.stringify(Object.fromEntries(keys.map((k) => [k, r[k] ?? null])))).join("\n") + (rows.length > 0 ? "\n" : ""); | |
| 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 `/dataset`; 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 three 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 | /** | |
| 778 | * Cost per landed pull, by agent and model: all the agent's spend over the pulls its runs shipped. | |
| 779 | */ | |
| 780 | export function costPerLanded(usage: readonly Row[]): AgentCost[] { | |
| 781 | const by = new Map<string, { agent: string; model: string; cost: number; pulls: Set<string> }>(); | |
| 782 | for (const u of usage) { | |
| 783 | const agent = typeof u["agent"] === "string" ? u["agent"] : "unknown"; | |
| 784 | const model = typeof u["model"] === "string" ? u["model"] : "default"; | |
| 785 | const e = by.get(`${agent}\0${model}`) ?? { agent, model, cost: 0, pulls: new Set() }; | |
| 786 | e.cost += typeof u["cost_usd"] === "number" ? u["cost_usd"] : 0; | |
| 787 | if (typeof u["landed_pull"] === "string") e.pulls.add(u["landed_pull"]); | |
| 788 | by.set(`${agent}\0${model}`, e); | |
| 789 | } | |
| 790 | return [...by.values()] | |
| 791 | .map((e) => ({ | |
| 792 | agent: e.agent, | |
| 793 | model: e.model, | |
| 794 | landed: e.pulls.size, | |
| 795 | costUsd: round2(e.cost), | |
| 796 | perLandedUsd: e.pulls.size === 0 ? null : round2(e.cost / e.pulls.size), | |
| 797 | })) | |
| 798 | .sort((a, b) => b.costUsd - a.costUsd); | |
| 799 | } | |
| 800 | ||
| 801 | export interface FailingTest { | |
| 802 | readonly name: string; | |
| 803 | readonly failures: number; | |
| 804 | } | |
| 805 | ||
| 806 | /** Which tests fail most across failed checks. */ | |
| 807 | export function failingChecks(checks: readonly Row[], top = 10): FailingTest[] { | |
| 808 | const n = new Map<string, number>(); | |
| 809 | for (const c of checks) { | |
| 810 | if (c["state"] !== "failed" || typeof c["failed_names"] !== "string") continue; | |
| 811 | let names: unknown; | |
| 812 | try { | |
| 813 | names = JSON.parse(c["failed_names"]); | |
| 814 | } catch { | |
| 815 | continue; | |
| 816 | } | |
| 817 | if (Array.isArray(names)) | |
| 818 | for (const x of names) if (typeof x === "string") n.set(x, (n.get(x) ?? 0) + 1); | |
| 819 | } | |
| 820 | return [...n] | |
| 821 | .map(([name, failures]) => ({ name, failures })) | |
| 822 | .sort((a, b) => b.failures - a.failures || a.name.localeCompare(b.name)) | |
| 823 | .slice(0, top); | |
| 824 | } | |
| 825 | ||
| 826 | // ——— the last week, for the planner ——— | |
| 827 | ||
| 828 | export const WEEK_MS = 7 * 24 * 3_600_000; | |
| 829 | ||
| 830 | export interface WeekDigest { | |
| 831 | readonly since: string; | |
| 832 | readonly landed: number; | |
| 833 | readonly landedByPillar: readonly { pillar: string; landed: number }[]; | |
| 834 | readonly parked: number; | |
| 835 | readonly costUsd: number; | |
| 836 | readonly perLandedUsd: number | null; | |
| 837 | readonly checksFailed: number; | |
| 838 | readonly topFailing: readonly FailingTest[]; | |
| 839 | } | |
| 840 | ||
| 841 | export function weekDigest(db: Database, repoId: string, now = new Date()): WeekDigest { | |
| 842 | const since = new Date(now.getTime() - WEEK_MS).toISOString(); | |
| 843 | // The hash needs a salt only to name people; the digest names none. | |
| 844 | const p = new Privacy("digest", db); | |
| 845 | const w = { repoId }; | |
| 846 | const facts = pullFacts(db, p, w); | |
| 847 | const merged = facts.rows.filter((r) => typeof r["merged_at"] === "string" && (r["merged_at"] as string) >= since); | |
| 848 | const by = new Map<string, number>(); | |
| 849 | for (const r of merged) { | |
| 850 | const k = typeof r["pillar"] === "string" ? r["pillar"] : "no pillar"; | |
| 851 | by.set(k, (by.get(k) ?? 0) + 1); | |
| 852 | } | |
| 853 | const usage = usageRows(db, p, { repoId, since }, facts); | |
| 854 | const cost = usage.reduce((s, u) => s + (typeof u["cost_usd"] === "number" ? u["cost_usd"] : 0), 0); | |
| 855 | const checks = checksRows(db, p, { repoId, since }); | |
| 856 | const parked = | |
| 857 | db | |
| 858 | .query<{ n: number }, [string, string]>( | |
| 859 | `SELECT COUNT(*) n FROM comment c JOIN issue i ON i.id = c.issue_id | |
| 860 | WHERE i.repo_id = ?1 AND c.created_at >= ?2 AND c.body LIKE 'Parked by the crew%'`, | |
| 861 | ) | |
| 862 | .get(repoId, since)?.n ?? 0; | |
| 863 | return { | |
| 864 | since, | |
| 865 | landed: merged.length, | |
| 866 | landedByPillar: [...by].map(([pillar, landed]) => ({ pillar, landed })).sort((a, b) => b.landed - a.landed), | |
| 867 | parked, | |
| 868 | costUsd: round2(cost), | |
| 869 | perLandedUsd: merged.length === 0 ? null : round2(cost / merged.length), | |
| 870 | checksFailed: checks.filter((c) => c["state"] === "failed").length, | |
| 871 | topFailing: failingChecks(checks, 3), | |
| 872 | }; | |
| 873 | } | |
| 874 | ||
| 875 | /** The digest as the lines a planner is told, and told to say in its wave. */ | |
| 876 | export function weekLines(d: WeekDigest): string[] { | |
| 877 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 878 | return [ | |
| 879 | `Last week, from the forge's dataset (since ${d.since.slice(0, 10)}):`, | |
| 880 | `- Landed: ${d.landed} pull${d.landed === 1 ? "" : "s"}${d.landedByPillar.length > 0 ? ` (${d.landedByPillar.map((x) => `${x.pillar} ${x.landed}`).join(", ")})` : ""}.`, | |
| 881 | `- Parked: ${d.parked} time${d.parked === 1 ? "" : "s"}.`, | |
| 882 | `- Cost: ${usd(d.costUsd)}${d.perLandedUsd === null ? ", nothing landed to divide it by" : `, ${usd(d.perLandedUsd)} per landed pull`}.`, | |
| 883 | `- Checks failed: ${d.checksFailed}${d.topFailing.length > 0 ? `; most often ${d.topFailing.map((t) => `"${t.name}" (${t.failures})`).join(", ")}` : ""}.`, | |
| 884 | ]; | |
| 885 | } |
src/core/reserved.ts +1
src/crew/autonomy.ts +16
| @@ -19,6 +19,7 @@ import { betsInUse } from "../core/bets.ts"; | ||
| 19 | 19 | import { onlyListDocs, resolveListConflicts } from "../actions/list-conflicts.ts"; |
| 20 | 20 | import { closedToday, closeStale } from "./stale_pulls.ts"; |
| 21 | 21 | import { sweepApprovedWeek } from "./approved_week.ts"; |
| 22 | import { weekDigest, weekLines } from "../core/dataset.ts"; | |
| 22 | 23 | import type { Database } from "bun:sqlite"; |
| 23 | 24 | import type { App } from "../app.ts"; |
| 24 | 25 | import { ceilingReached, forgeCeiling } from "../flow/ceiling.ts"; |
| @@ -462,6 +463,21 @@ export function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], now: | ||
| 462 | 463 | */ |
| 463 | 464 | export type Drove = "off" | "paused" | "waiting" | "full" | "picked" | "planned" | "idle" | "stalled"; |
| 464 | 465 | |
| 466 | /** | |
| 467 | * The last week of this repository as the dataset holds it (`core/dataset.ts`): | |
| 468 | * what landed, what parked, what it cost, which checks failed. The lines a | |
| 469 | * planner is given before it plans, so the wave it proposes can answer them. | |
| 470 | * A repository the dataset cannot read yields nothing, and plans as it did. | |
| 471 | */ | |
| 472 | export function lastWeekFor(app: App, repo: Repo, now = new Date()): string[] { | |
| 473 | try { | |
| 474 | return weekLines(weekDigest(app.db, repo.id, now)); | |
| 475 | } catch (e) { | |
| 476 | log.warn("last week unreadable", { repo: `${repo.ownerName}/${repo.name}`, error: String(e) }); | |
| 477 | return []; | |
| 478 | } | |
| 479 | } | |
| 480 | ||
| 465 | 481 | /** |
| 466 | 482 | * One turn of the loop for one repository. Returns what it did, for the |
| 467 | 483 | * log and for tests; the effects are an assignment (which the crew turns |
src/crew/brief.ts +13 −1
| @@ -354,6 +354,8 @@ export interface TaskInput extends BriefInput { | ||
| 354 | 354 | readonly parkedTwice?: readonly HandedOver[] | undefined; |
| 355 | 355 | /** For a planner: the limbs a person handed over to re-plan as fewer, larger pieces. */ |
| 356 | 356 | readonly limbs?: readonly HandedLimb[] | undefined; |
| 357 | /** For a planner: what the last week's dataset says (`autonomy.lastWeekFor`). */ | |
| 358 | readonly lastWeek?: readonly string[] | undefined; | |
| 357 | 359 | /** For a planner: the issue deferred work waits behind, if there is one. */ |
| 358 | 360 | readonly laterGate?: number | undefined; |
| 359 | 361 | /** For a planner: nothing ready can start, and what holds it (`held.ts`). */ |
| @@ -490,7 +492,7 @@ function taskBody(input: TaskInput): string { | ||
| 490 | 492 | const { issue } = input; |
| 491 | 493 | const out: string[] = []; |
| 492 | 494 | const isAgent = (name: string): boolean => name === input.agent.user.username; |
| 493 | const handed = [earlierParkLines(input), parkedTwiceLines(input), landedLines(input), limbLines(input), stuckLines(input), teamLines(input), hotLines(input), holdLines(input)] | |
| 495 | const handed = [earlierParkLines(input), parkedTwiceLines(input), landedLines(input), lastWeekLines(input), limbLines(input), stuckLines(input), teamLines(input), hotLines(input), holdLines(input)] | |
| 494 | 496 | .filter((lines) => lines.length > 0) |
| 495 | 497 | .flatMap((lines, n) => (n === 0 ? lines : ["", ...lines])); |
| 496 | 498 | const readers = input.readers ?? new Set<string>(); |
| @@ -855,6 +857,16 @@ export function earlierParkLines(input: TaskInput): string[] { | ||
| 855 | 857 | ]; |
| 856 | 858 | } |
| 857 | 859 | |
| 860 | /** What a planner is told of last week, and how to answer it. */ | |
| 861 | function lastWeekLines(input: TaskInput): string[] { | |
| 862 | const week = input.role === "planner" ? (input.lastWeek ?? []) : []; | |
| 863 | if (week.length === 0) return []; | |
| 864 | return [ | |
| 865 | ...week, | |
| 866 | '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.', | |
| 867 | ]; | |
| 868 | } | |
| 869 | ||
| 858 | 870 | /** |
| 859 | 871 | * What a planner is told of the issues the crew parked twice: each with |
| 860 | 872 | * every reason and whose it is, and the states it may leave one in — split, |
src/crew/runner.ts +2
| @@ -172,6 +172,7 @@ import { | ||
| 172 | 172 | } from "./limits.ts"; |
| 173 | 173 | import { clearStaleLocks, lockedOut } from "./locks.ts"; |
| 174 | 174 | import { interruptedSummary, interruptionOf, landedPullOf, landedSummary, settleLanded } from "./interrupted.ts"; |
| 175 | import { lastWeekFor } from "./autonomy.ts"; | |
| 175 | 176 | import { laterGate } from "./later.ts"; |
| 176 | 177 | import { MERGES_CLEAN_NOW, mergesCleanNow } from "./clean_now.ts"; |
| 177 | 178 | import { handedLimbs } from "./handed_limbs.ts"; |
| @@ -1513,6 +1514,7 @@ async function work( | ||
| 1513 | 1514 | ], |
| 1514 | 1515 | limbs: handedLimbs(app, repo), |
| 1515 | 1516 | laterGate: laterGate(app.db, repo.id), |
| 1517 | lastWeek: lastWeekFor(app, repo), | |
| 1516 | 1518 | ...(() => { |
| 1517 | 1519 | const held = heldNow(app, repo); |
| 1518 | 1520 | return { |
src/http/marks/dataset.json added +7
src/http/server.ts +2
| @@ -51,6 +51,7 @@ import { bottleneckPage } from "../web/pages/bottleneck.ts"; | ||
| 51 | 51 | import { contributePage } from "../web/pages/contribute.ts"; |
| 52 | 52 | import { designComponentsPage } from "../web/pages/design-components.ts"; |
| 53 | 53 | import { pipelinePage } from "../web/pages/pipeline.ts"; |
| 54 | import { datasetPage } from "../web/pages/dataset.ts"; | |
| 54 | 55 | import { adminDataPage, appDataCsv, appDataPage, dataPage } from "../web/pages/data.ts"; |
| 55 | 56 | import { fleetAct, fleetReceipt, fleetUndo } from "../web/pages/fleet-ops.ts"; |
| 56 | 57 | import { maintenanceDuty, maintenanceDismiss, maintenanceQuiet, maintenanceUnquiet, maintenanceReopen, maintenanceJson, maintenancePage, maintenancePrepare, maintenanceResume, staleAction, mergedAction, previewAction } from "../web/pages/maintenance.ts"; |
| @@ -1144,6 +1145,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1144 | 1145 | router.add("POST", "/:owner/:name/display", displayChoose); |
| 1145 | 1146 | router.add("GET", "/now/:stage", nowPage); |
| 1146 | 1147 | router.add("GET", "/audit", auditPage); |
| 1148 | router.add("GET", "/dataset", datasetPage); | |
| 1147 | 1149 | router.add("GET", "/releases", releasesPage); |
| 1148 | 1150 | // The forge's own documentation: a redirect built from configuration only. |
| 1149 | 1151 | router.add("GET", "/privacy", privacyPage); |
src/main.ts +5
| @@ -81,6 +81,7 @@ import { startMaintain } from "./maintain/runner.ts"; | ||
| 81 | 81 | import { startMirrorOut } from "./origins/mirror-out.ts"; |
| 82 | 82 | import { startMirrorPulls } from "./origins/mirror-pulls.ts"; |
| 83 | 83 | import { startProbes } from "./contract/probes.ts"; |
| 84 | import { startDatasetNightly } from "./actions/dataset.ts"; | |
| 84 | 85 | import { startRoutines } from "./crew/routines.ts"; |
| 85 | 86 | import { startNightly } from "./nightly/service.ts"; |
| 86 | 87 | import { startSnapshots } from "./snapshot/service.ts"; |
| @@ -746,6 +747,9 @@ const snapshots = startSnapshots( | ||
| 746 | 747 | passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined, |
| 747 | 748 | }, |
| 748 | 749 | ); |
| 750 | // The dataset: nightly, to the private repository FORGE_DATASET_REPO names | |
| 751 | // (`owner/data`); off without it. | |
| 752 | const dataset = startDatasetNightly(app, process.env["FORGE_DATASET_REPO"]); | |
| 749 | 753 | // What the machine uses (boards/sampler.ts): the pod, each cell and the |
| 750 | 754 | // node, every 15 s into a ring the `machine` board source reads. |
| 751 | 755 | const sampler = startSampler(app, {}); |
| @@ -1276,6 +1280,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1276 | 1280 | probes?.stop(), |
| 1277 | 1281 | nightly?.stop(), |
| 1278 | 1282 | snapshots.stop(), |
| 1283 | dataset.stop(), | |
| 1279 | 1284 | sampler.stop(), |
| 1280 | 1285 | stopRetention(), |
| 1281 | 1286 | memorySampler.stop(), |
src/tui/screens/dataset.ts added +71
| @@ -0,0 +1,71 @@ | ||
| 1 | /** | |
| 2 | * The dataset in the terminal: what the forge's dataset holds (a line a table), | |
| 3 | * when it last grew, and the questions it already answers, as /dataset reads | |
| 4 | * them. Gated as the page is: a forge admin who is a person. Read-only. | |
| 5 | */ | |
| 6 | ||
| 7 | import { datasetAnswers, lastExport } from "../../actions/dataset.ts"; | |
| 8 | import { datasetStats } from "../../core/dataset.ts"; | |
| 9 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 10 | import { binding } from "../app/keys.ts"; | |
| 11 | import type { Session } from "../session.ts"; | |
| 12 | import { style } from "../term/style.ts"; | |
| 13 | import { pad } from "../term/width.ts"; | |
| 14 | import { Scroll, drawLines, hitScroll } from "./common.ts"; | |
| 15 | import type { PaletteEntry } from "./entries.ts"; | |
| 16 | ||
| 17 | const mayRead = (session: Session): boolean => session.user?.kind !== "agent" && session.user?.isAdmin === true; | |
| 18 | ||
| 19 | /** The screen's lines; empty for anyone the gate refuses. */ | |
| 20 | export function datasetLines(session: Session): string[] { | |
| 21 | if (!mayRead(session)) return []; | |
| 22 | const db = session.app.db; | |
| 23 | const last = lastExport(session.app); | |
| 24 | const a = datasetAnswers(db); | |
| 25 | const lines = [last ? `Last export ${new Date(last.at).toISOString()}${last.commit ? `, commit ${last.commit.slice(0, 8)}` : ""}.` : "Nothing has been exported yet.", ""]; | |
| 26 | lines.push(`${pad("Table", 12)}${pad("Rows now", 10)}Exported`); | |
| 27 | for (const s of datasetStats(db)) lines.push(`${pad(s.table, 12)}${pad(String(s.rows), 10)}${last?.tables[s.table]?.rows ?? "—"}`); | |
| 28 | if (a.tell.length > 0) lines.push("", "Time from tell to shipped, by pillar (median hours)"); | |
| 29 | for (const t of a.tell) lines.push(` ${pad(t.pillar, 20)}${pad(String(t.shipped), 6)}${t.medianHours}`); | |
| 30 | if (a.cost.length > 0) lines.push("", "Cost per landed pull, by agent and model"); | |
| 31 | for (const c of a.cost) lines.push(` ${pad(c.agent, 16)}${pad(c.model, 24)}${pad(String(c.landed), 5)}$${c.costUsd.toFixed(2)}${c.perLandedUsd === null ? "" : ` $${c.perLandedUsd.toFixed(2)} each`}`); | |
| 32 | if (a.failing.length > 0) lines.push("", "Which checks fail most"); | |
| 33 | for (const f of a.failing) lines.push(` ${pad(String(f.failures), 5)}${f.name}`); | |
| 34 | return lines; | |
| 35 | } | |
| 36 | ||
| 37 | export function datasetScreen(session: Session, ctx: Ctx): Screen { | |
| 38 | const scroll = new Scroll(); | |
| 39 | let lines = datasetLines(session); | |
| 40 | return { | |
| 41 | title: "Dataset", | |
| 42 | keys: [binding(["j", "k"], "scroll"), binding(["g"], "read again"), binding(["esc", "q"], "back")], | |
| 43 | render(area, s) { | |
| 44 | const c = ctx.theme.c; | |
| 45 | drawLines(s, area, c, scroll, lines.map((text) => [{ text, style: style(text.startsWith(" ") ? c.mutedFg : c.fg, c.bg) }])); | |
| 46 | hitScroll(ctx, area, scroll, lines.length); | |
| 47 | }, | |
| 48 | key(e) { | |
| 49 | if (scroll.key(e, lines.length)) return true; | |
| 50 | if (e.key === "g") { | |
| 51 | lines = datasetLines(session); | |
| 52 | return true; | |
| 53 | } | |
| 54 | if (e.key === "esc" || e.key === "q") { | |
| 55 | ctx.pop(); | |
| 56 | return true; | |
| 57 | } | |
| 58 | return false; | |
| 59 | }, | |
| 60 | }; | |
| 61 | } | |
| 62 | ||
| 63 | export const entry: PaletteEntry = { | |
| 64 | rank: 112, | |
| 65 | id: "dataset", | |
| 66 | title: "Dataset", | |
| 67 | hint: "what the forge's dataset holds, and what it already answers", | |
| 68 | after: ["bottleneck", "system"], | |
| 69 | offered: mayRead, | |
| 70 | run: (session, ctx) => ctx.push(datasetScreen(session, ctx)), | |
| 71 | }; |
src/view/doc_sections.ts +1
| @@ -47,6 +47,7 @@ export const DOC_LINES: Record<string, Line> = { | ||
| 47 | 47 | "CLUSTER.md": ["run", "Checks as Kubernetes Jobs."], |
| 48 | 48 | |
| 49 | 49 | "APPS.md": ["reference", "Apps, previews and runs, and their rules."], |
| 50 | "DATASET.md": ["reference", "Every field of the forge's JSONL dataset.", "Dataset"], | |
| 50 | 51 | "CREW.md": ["reference", "The crew, the forge's AI agents: runs, review, spend."], |
| 51 | 52 | "STUDIO.md": ["reference", "The web interface, page by page."], |
| 52 | 53 | "TOUR.md": ["reference", "Every feature, by every door."], |
src/web/pages/dataset.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 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 { datasetAnswers as answers, lastExport } from "../../actions/dataset.ts"; | |
| 9 | import { datasetStats } from "../../core/dataset.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 12 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 13 | import { html } from "../html.ts"; | |
| 14 | import { page } from "../layout.ts"; | |
| 15 | import { time } from "../ui.ts"; | |
| 16 | import { accountSections } from "./origins.ts"; | |
| 17 | ||
| 18 | const bytes = (n: number): string => | |
| 19 | n >= 1_048_576 ? `${(n / 1_048_576).toFixed(1)} MB` : n >= 1024 ? `${(n / 1024).toFixed(1)} kB` : `${n} B`; | |
| 20 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 21 | ||
| 22 | // GET /dataset | |
| 23 | export function datasetPage(ctx: Ctx): Response { | |
| 24 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 25 | const rendering = performance.now(); | |
| 26 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 27 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 28 | const stats = datasetStats(ctx.app.db); | |
| 29 | const last = lastExport(ctx.app); | |
| 30 | const a = answers(ctx.app.db); | |
| 31 | const response = page({ | |
| 32 | ctx, | |
| 33 | title: "Dataset", | |
| 34 | description: "What the forge's dataset holds, and what it already answers.", | |
| 35 | body: html`${pageHead("Dataset", { | |
| 36 | sub: html`The forge's own record, exported nightly as one documented dataset${last | |
| 37 | ? html`; last export ${time(last.at)}${last.commit ? html`, commit <code>${last.commit.slice(0, 8)}</code>` : null}.` | |
| 38 | : "; nothing has been exported yet."}`, | |
| 39 | })} | |
| 40 | ${settingsLayout( | |
| 41 | accountSections("dataset", { admin: true }), | |
| 42 | html`<section data-section="tables"> | |
| 43 | <h2>What it holds</h2> | |
| 44 | <table class="table" data-dense> | |
| 45 | <thead> | |
| 46 | <tr> | |
| 47 | <th scope="col">Table</th> | |
| 48 | <th scope="col" class="num">Rows now</th> | |
| 49 | <th scope="col">Newest row</th> | |
| 50 | <th scope="col" class="num">Exported rows</th> | |
| 51 | <th scope="col" class="num">Exported size</th> | |
| 52 | </tr> | |
| 53 | </thead> | |
| 54 | <tbody> | |
| 55 | ${stats.map((s) => { | |
| 56 | const x = last?.tables[s.table]; | |
| 57 | return html`<tr data-table="${s.table}"> | |
| 58 | <th scope="row"><code>${s.table}</code></th> | |
| 59 | <td class="num">${String(s.rows)}</td> | |
| 60 | <td>${s.latest ? time(s.latest) : "—"}</td> | |
| 61 | <td class="num">${x ? String(x.rows) : "—"}</td> | |
| 62 | <td class="num">${x ? bytes(x.bytes) : "—"}</td> | |
| 63 | </tr>`; | |
| 64 | })} | |
| 65 | </tbody> | |
| 66 | </table> | |
| 67 | </section> | |
| 68 | ${a.tell.length === 0 | |
| 69 | ? null | |
| 70 | : html`<section data-section="tell-to-shipped"> | |
| 71 | <h2>Time from tell to shipped, by pillar</h2> | |
| 72 | <table class="table" data-dense data-question="tell-to-shipped"> | |
| 73 | <thead><tr><th scope="col">Pillar</th><th scope="col" class="num">Shipped</th><th scope="col" class="num">Median hours</th></tr></thead> | |
| 74 | <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> | |
| 75 | </table> | |
| 76 | </section>`} | |
| 77 | ${a.cost.length === 0 | |
| 78 | ? null | |
| 79 | : html`<section data-section="cost-per-landed"> | |
| 80 | <h2>Cost per landed pull, by agent and model</h2> | |
| 81 | <table class="table" data-dense data-question="cost-per-landed"> | |
| 82 | <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> | |
| 83 | <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> | |
| 84 | </table> | |
| 85 | </section>`} | |
| 86 | ${a.failing.length === 0 | |
| 87 | ? null | |
| 88 | : html`<section data-section="failing-checks"> | |
| 89 | <h2>Which checks fail most</h2> | |
| 90 | <table class="table" data-dense data-question="failing-checks"> | |
| 91 | <thead><tr><th scope="col">Test</th><th scope="col" class="num">Failures</th></tr></thead> | |
| 92 | <tbody>${a.failing.map((t) => html`<tr><th scope="row">${t.name}</th><td class="num">${String(t.failures)}</td></tr>`)}</tbody> | |
| 93 | </table> | |
| 94 | </section>`}`, | |
| 95 | "Account settings", | |
| 96 | )}`, | |
| 97 | }); | |
| 98 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 99 | return response; | |
| 100 | } | |
src/web/pages/origins.ts +2
| @@ -121,6 +121,7 @@ export type AccountSection = | ||
| 121 | 121 | | "people" |
| 122 | 122 | | "subscriptions" |
| 123 | 123 | | "backups" |
| 124 | | "dataset" | |
| 124 | 125 | | "traffic" |
| 125 | 126 | | "secrets" |
| 126 | 127 | | "devices" |
| @@ -192,6 +193,7 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 192 | 193 | ["This forge", "Features", "/settings/features", "rocket", (c) => c === "features", true], |
| 193 | 194 | ["This forge", "Packs", "/settings/packs", "rocket", (c) => c === "packs", true], |
| 194 | 195 | ["This forge", "Backups", "/settings/backups", "download", (c) => c === "backups", true], |
| 196 | ["This forge", "Dataset", "/dataset", "download", (c) => c === "dataset", true], | |
| 195 | 197 | ]; |
| 196 | 198 | |
| 197 | 199 | export function accountSections( |
test/dataset.test.ts added +311
| @@ -0,0 +1,311 @@ | ||
| 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 | Privacy, | |
| 20 | pullsRows, | |
| 21 | SCHEMA, | |
| 22 | schemaDocument, | |
| 23 | TABLES, | |
| 24 | tableRows, | |
| 25 | tellToShipped, | |
| 26 | toJsonl, | |
| 27 | weekDigest, | |
| 28 | } from "../src/core/dataset.ts"; | |
| 29 | import { createRepo as makeRepo, 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 { Session } from "../src/tui/forge.ts"; | |
| 38 | import type { Ctx } from "../src/http/context.ts"; | |
| 39 | import { datasetPage } from "../src/web/pages/dataset.ts"; | |
| 40 | ||
| 41 | const EMAIL = "[email protected]"; | |
| 42 | const TOKEN = "forge_AbCdEf0123456789AbCdEf0123456789xyz"; | |
| 43 | const PATH = "/data/crew/scout/01m23vygyffx5hg2f5vm8r74sr/1139/src/x.ts"; | |
| 44 | const LONG = "Zx9Qw8Er7Ty6Ui5Op4As3Df2Gh1Jk0Lm9Nb8Vc7"; | |
| 45 | const NOW = new Date("2026-10-14T12:00:00.000Z"); | |
| 46 | ||
| 47 | const fromJsonl = (text: string): Record<string, unknown>[] => | |
| 48 | text | |
| 49 | .split("\n") | |
| 50 | .filter((l) => l !== "") | |
| 51 | .map((l) => JSON.parse(l) as Record<string, unknown>); | |
| 52 | ||
| 53 | describe("the dataset", () => { | |
| 54 | let dir: string; | |
| 55 | let app: App; | |
| 56 | let alice: User; | |
| 57 | let bob: User; | |
| 58 | let repo: Repo; | |
| 59 | let data: Repo; | |
| 60 | let agentId: string; | |
| 61 | ||
| 62 | const issue = (id: string, n: number, author: string, kind: string, at: string, body = "", title = "t") => | |
| 63 | app.db | |
| 64 | .query( | |
| 65 | "INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)", | |
| 66 | ) | |
| 67 | .run(id, repo.id, n, kind, title, body, author, at); | |
| 68 | ||
| 69 | beforeAll(async () => { | |
| 70 | dir = await mkdtemp(join(tmpdir(), "forge-dataset-")); | |
| 71 | app = createApp({ dataDir: dir, port: 0 }); | |
| 72 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 73 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bobby", email: EMAIL, password: "a-good-passphrase" }); | |
| 74 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 75 | alice = a.value; | |
| 76 | bob = b.value; | |
| 77 | const ag = await createAgent(app, alice, { username: "builder", model: "sonnet" }); | |
| 78 | if (!ag.ok) throw new Error(String(ag.error)); | |
| 79 | agentId = ag.value.user.id; | |
| 80 | const r = await createRepo(app, alice, { name: "app", visibility: "private" }); | |
| 81 | const d = await createRepo(app, alice, { name: "data", visibility: "private" }); | |
| 82 | if (!r.ok || !d.ok) throw new Error("repos"); | |
| 83 | repo = r.value; | |
| 84 | data = d.value; | |
| 85 | ||
| 86 | // Bob told the forge (#1); the builder opened pull #2 closing it; it merged 10 h later. | |
| 87 | issue("i1", 1, bob.id, "issue", "2026-10-12T00:00:00.000Z", `mail ${EMAIL} ${TOKEN}`, `fix ${PATH}`); | |
| 88 | issue("i2", 2, agentId, "pull", "2026-10-12T05:00:00.000Z", "Closes #1"); | |
| 89 | app.db | |
| 90 | .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)") | |
| 91 | .run(alice.id); | |
| 92 | 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"); | |
| 93 | ||
| 94 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: "i1", actorId: agentId }); | |
| 95 | claimRun(app.db, run.id); | |
| 96 | finishRun(app.db, run.id, { state: "ok", summary: `edited ${PATH} for ${EMAIL}`, costUsd: 1.5, turns: 4 }); | |
| 97 | 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" }); | |
| 98 | const check = createRun(app.db, { repoId: repo.id, kind: "check", issueId: "i2" }); | |
| 99 | claimRun(app.db, check.id); | |
| 100 | finishRun(app.db, check.id, { state: "failed", summary: "1 failed", checkDetail: { passed: 3, failed: 1, names: [`test/a.test.ts > breaks for ${EMAIL}`] } }); | |
| 101 | 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 }); | |
| 102 | app.bus.append({ kind: "pull.merged", repoId: repo.id, actorId: bob.id, payload: { email: EMAIL, note: `at ${PATH}`, token: TOKEN, author: "bobby", agent: "builder" } }); | |
| 103 | }); | |
| 104 | afterAll(async () => { | |
| 105 | app.close(); | |
| 106 | await rm(dir, { recursive: true, force: true }); | |
| 107 | }); | |
| 108 | ||
| 109 | test("every table round-trips through JSONL, with rows to read back", () => { | |
| 110 | const p = new Privacy("salt", app.db); | |
| 111 | for (const t of TABLES) { | |
| 112 | const rows = tableRows(app.db, p, t); | |
| 113 | expect(rows.length).toBeGreaterThan(0); | |
| 114 | expect(fromJsonl(toJsonl(t, rows))).toEqual(rows.map((r) => Object.fromEntries(SCHEMA[t].fields.map((f) => [f.name, r[f.name] ?? null])))); | |
| 115 | } | |
| 116 | }); | |
| 117 | ||
| 118 | test("the schema names every field a row carries, and the document is the committed one", () => { | |
| 119 | const p = new Privacy("salt", app.db); | |
| 120 | const doc = schemaDocument(); | |
| 121 | for (const t of TABLES) { | |
| 122 | const fields = SCHEMA[t].fields.map((f) => f.name); | |
| 123 | for (const row of tableRows(app.db, p, t)) expect(Object.keys(row).sort()).toEqual([...fields].sort()); | |
| 124 | for (const f of fields) expect(doc).toContain(`| \`${f}\` |`); | |
| 125 | for (const f of SCHEMA[t].fields) expect(f.meaning.length).toBeGreaterThan(5); | |
| 126 | } | |
| 127 | expect(readFileSync(join(import.meta.dir, "..", "docs", "DATASET.md"), "utf8")).toBe(`${doc}\n`); | |
| 128 | }); | |
| 129 | ||
| 130 | test("no email, token or raw path appears in any file, and people are hashed the same everywhere", () => { | |
| 131 | const { files } = buildExport(app, NOW); | |
| 132 | const all = Object.entries(files).filter(([n]) => n !== "SCHEMA.md").map(([, t]) => t).join("\n"); | |
| 133 | for (const secret of [EMAIL, "[email protected]", TOKEN, LONG, PATH, "/data/crew", "01m23vygyffx5hg2f5vm8r74sr", "apiKey\":\"forge_", "bobby", "a-good-passphrase"]) | |
| 134 | expect(all).not.toContain(secret); | |
| 135 | expect(all).not.toMatch(/[\w.+-]+@[\w-]+\.[a-z]{2,}/i); | |
| 136 | expect(all).toContain("[email]"); | |
| 137 | expect(all).toContain("[path]"); | |
| 138 | expect(all).toContain("[redacted]"); | |
| 139 | expect(all).toContain("builder"); | |
| 140 | const p = new Privacy("salt", app.db); | |
| 141 | const ev = tableRows(app.db, p, "events").find((e) => e["kind"] === "pull.merged")!; | |
| 142 | expect(ev["actor"]).toBe(p.who(bob.id)); | |
| 143 | expect(String(ev["actor"])).toMatch(/^p_[0-9a-f]{12}$/); | |
| 144 | expect(new Privacy("other", app.db).who(bob.id)).not.toBe(p.who(bob.id)); | |
| 145 | // The salt itself stays out of every file. | |
| 146 | const salt = readFileSync(join(dir, "dataset", "salt"), "utf8").trim(); | |
| 147 | expect(all).not.toContain(salt); | |
| 148 | }); | |
| 149 | ||
| 150 | test("the questions it answers come out of the rows", () => { | |
| 151 | const p = new Privacy("salt", app.db); | |
| 152 | const pulls = tableRows(app.db, p, "pulls"); | |
| 153 | expect(pulls[0]!["tell_to_shipped_hours"]).toBe(10); | |
| 154 | expect(tellToShipped(pulls)).toEqual([{ pillar: "no pillar", shipped: 1, medianHours: 10 }]); | |
| 155 | expect(costPerLanded(tableRows(app.db, p, "usage"))).toEqual([{ agent: "builder", model: "sonnet", landed: 1, costUsd: 1.5, perLandedUsd: 1.5 }]); | |
| 156 | expect(failingChecks(tableRows(app.db, p, "checks"))).toEqual([{ name: "test/a.test.ts > breaks for [email]", failures: 1 }]); | |
| 157 | }); | |
| 158 | ||
| 159 | test("the last week is landed, parked, cost and failures, and the planner is told", () => { | |
| 160 | const d = weekDigest(app.db, repo.id, NOW); | |
| 161 | expect(d).toMatchObject({ landed: 1, parked: 1, costUsd: 1.5, perLandedUsd: 1.5, checksFailed: 1 }); | |
| 162 | expect(weekDigest(app.db, repo.id, new Date("2026-12-01T00:00:00Z"))).toMatchObject({ landed: 0, parked: 0, costUsd: 0, perLandedUsd: null }); | |
| 163 | const lines = lastWeekFor(app, repo, NOW); | |
| 164 | const prompt = (role: string) => | |
| 165 | taskPrompt({ | |
| 166 | agent: { user: { username: "planner", displayName: "" }, brief: "" }, | |
| 167 | repo: { ownerName: "alice", name: "app", defaultBranch: "main" }, | |
| 168 | issue: { number: 9, title: "Direction", body: "go", authorName: "alice" }, | |
| 169 | reason: "assigned", | |
| 170 | role, | |
| 171 | comments: [], | |
| 172 | reviews: [], | |
| 173 | reviewComments: [], | |
| 174 | since: "", | |
| 175 | branch: "planner/9", | |
| 176 | lastWeek: lines, | |
| 177 | } as unknown as TaskInput); | |
| 178 | expect(prompt("planner")).toContain("Last week, from the forge's dataset"); | |
| 179 | expect(prompt("planner")).toContain("Landed: 1 pull"); | |
| 180 | expect(prompt("planner")).toContain('starting "Last week:"'); | |
| 181 | expect(prompt("builder")).not.toContain("Last week"); | |
| 182 | }); | |
| 183 | ||
| 184 | test("it is published to a private repository, once, and never to a public one", async () => { | |
| 185 | expect(await publishDataset(app, "alice/nowhere")).toMatchObject({ ok: false }); | |
| 186 | const pub = await createRepo(app, alice, { name: "open", visibility: "public" }); | |
| 187 | if (!pub.ok) throw new Error("repo"); | |
| 188 | expect(await publishDataset(app, "alice/open")).toMatchObject({ ok: false, error: expect.stringContaining("not private") }); | |
| 189 | const first = await publishDataset(app, "alice/data", NOW); | |
| 190 | expect(first).toMatchObject({ ok: true, unchanged: false }); | |
| 191 | const bare = join(app.reposRoot, "alice", "data.git"); | |
| 192 | const shown = await runGit(["show", `${data.defaultBranch}:SCHEMA.md`], { cwd: bare }); | |
| 193 | expect(shown.ok && shown.value.toString()).toContain("# The forge's dataset"); | |
| 194 | const events = await runGit(["show", `${data.defaultBranch}:events.jsonl`], { cwd: bare }); | |
| 195 | expect(events.ok && events.value.toString()).toContain("pull.merged"); | |
| 196 | expect(lastExport(app)?.tables.events.rows).toBeGreaterThan(0); | |
| 197 | expect(await publishDataset(app, "alice/data", new Date(NOW.getTime() + 1000))).toEqual({ ok: true, unchanged: true }); | |
| 198 | }); | |
| 199 | ||
| 200 | test("/dataset is for the admin alone", async () => { | |
| 201 | expect(Object.keys(buildExport(app, NOW).files).sort()).toEqual([...TABLES.map((t) => `${t}.jsonl`), "SCHEMA.md"].sort()); | |
| 202 | const get = (user: User | undefined) => | |
| 203 | datasetPage({ | |
| 204 | app, | |
| 205 | request: new Request("http://forge.test/dataset"), | |
| 206 | url: new URL("http://forge.test/dataset"), | |
| 207 | params: {}, | |
| 208 | auth: { user, scope: undefined, via: user ? "session" : "none" }, | |
| 209 | theme: undefined, | |
| 210 | } satisfies Ctx); | |
| 211 | const page = get(alice); | |
| 212 | expect(page.status).toBe(200); | |
| 213 | const text = await page.text(); | |
| 214 | for (const t of TABLES) expect(text).toContain(`data-table="${t}"`); | |
| 215 | expect(text).toContain("Time from tell to shipped"); | |
| 216 | expect(text).not.toContain(EMAIL); | |
| 217 | expect(get(bob).status).toBe(404); | |
| 218 | expect(get(undefined).status).not.toBe(200); | |
| 219 | }); | |
| 220 | ||
| 221 | test("the terminal screen shows a forge admin the tables and nobody else", async () => { | |
| 222 | const { datasetLines, entry } = await import("../src/tui/screens/dataset.ts"); | |
| 223 | const sessionOf = (user: User) => new Session(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user }); | |
| 224 | const text = datasetLines(sessionOf(alice)).join("\n"); | |
| 225 | for (const t of ["events", "decisions", "runs", "checks", "pulls", "usage"]) expect(text).toContain(t); | |
| 226 | expect(datasetLines(sessionOf(bob))).toEqual([]); | |
| 227 | expect(entry.offered(sessionOf(alice))).toBe(true); | |
| 228 | expect(entry.offered(sessionOf(bob))).toBe(false); | |
| 229 | }); | |
| 230 | }); | |
| 231 | ||
| 232 | describe("the dataset keeps to its audience", () => { | |
| 233 | let dir: string; | |
| 234 | let app: App; | |
| 235 | let alice: User; | |
| 236 | let carol: User; | |
| 237 | ||
| 238 | beforeAll(async () => { | |
| 239 | dir = await mkdtemp(join(tmpdir(), "forge-dataset-aud-")); | |
| 240 | app = createApp({ dataDir: dir, port: 0 }); | |
| 241 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 242 | const c = await createUser(app.db, { origin: "seed", trusted: true, username: "carolyn", email: "[email protected]", password: "a-good-passphrase" }); | |
| 243 | if (!a.ok || !c.ok) throw new Error("users"); | |
| 244 | alice = a.value; | |
| 245 | carol = c.value; | |
| 246 | }); | |
| 247 | afterAll(async () => { | |
| 248 | app.close(); | |
| 249 | await rm(dir, { recursive: true, force: true }); | |
| 250 | }); | |
| 251 | ||
| 252 | test("admin-only, app-only, sealed and other people's events never reach events.jsonl", async () => { | |
| 253 | const mine = await createRepo(app, alice, { name: "mine", visibility: "private" }); | |
| 254 | const hers = await makeRepo(app.db, app.reposRoot, { ownerId: carol.id, name: "hers", visibility: "private", description: "" }); | |
| 255 | const data = await createRepo(app, alice, { name: "data", visibility: "private" }); | |
| 256 | if (!mine.ok || !hers.ok || !data.ok) throw new Error("repos " + JSON.stringify([mine, hers, data].map((x) => x.ok ? "ok" : x.error))); | |
| 257 | const secretUrl = "https://hooks.example.com/services/T0AAAAAAA/B0BBBBBBB/xYz12345abcdEFGH"; | |
| 258 | app.bus.append({ kind: "webhook.created", repoId: mine.value.id, actorId: alice.id, payload: { url: secretUrl } }); | |
| 259 | app.bus.append({ kind: "app.env_set", repoId: mine.value.id, actorId: alice.id, payload: { name: "DB_PASSWORD_NAME" } }); | |
| 260 | app.bus.append({ kind: "run.finished", repoId: mine.value.id, actorId: alice.id, payload: { summary: "private output" } }); | |
| 261 | app.bus.append({ kind: "issue.opened", repoId: hers.value.id, actorId: carol.id, payload: { number: 1, title: "carol's own" } }); | |
| 262 | app.db | |
| 263 | .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)") | |
| 264 | .run(mine.value.id, alice.id); | |
| 265 | app.bus.append({ kind: "issue.opened", repoId: mine.value.id, actorId: alice.id, payload: { number: 7, title: "vuln" } }); | |
| 266 | app.bus.append({ kind: "issue.opened", repoId: mine.value.id, actorId: alice.id, payload: { number: 8, title: "plain issue" } }); | |
| 267 | ||
| 268 | const built = buildExport(app, NOW, alice.id); | |
| 269 | const events = built.files["events.jsonl"]!; | |
| 270 | for (const leak of ["webhook.created", "hooks.example.com", "xYz12345", "app.env_set", "DB_PASSWORD_NAME", "run.finished", "private output", "carol's own", "vuln"]) | |
| 271 | expect(events).not.toContain(leak); | |
| 272 | expect(events).toContain("plain issue"); | |
| 273 | expect(built.files["pulls.jsonl"]).not.toContain("vuln"); | |
| 274 | // Every row belongs to a repository the owner owns. | |
| 275 | for (const t of TABLES) | |
| 276 | for (const row of fromJsonl(built.files[`${t}.jsonl`]!)) | |
| 277 | if (row["repo_id"] !== null) expect([mine.value.id, data.value.id]).toContain(String(row["repo_id"])); | |
| 278 | }); | |
| 279 | ||
| 280 | test("a scoped export names no sealed issue a pull closes", async () => { | |
| 281 | const mine = await createRepo(app, alice, { name: "closer", visibility: "private" }); | |
| 282 | if (!mine.ok) throw new Error("repo"); | |
| 283 | const at = "2026-10-12T00:00:00.000Z"; | |
| 284 | const add = app.db.query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, created_at, sealed) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)"); | |
| 285 | add.run("sx1", mine.value.id, 21, "issue", "hidden", "", alice.id, at, 1); | |
| 286 | add.run("sx2", mine.value.id, 22, "pull", "fix", "Closes #21", alice.id, at, 0); | |
| 287 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES ('sx2','main','fix/1','a','b')").run(); | |
| 288 | const rows = pullsRows(app.db, new Privacy("salt", app.db), { scope: new Set([mine.value.id]) }); | |
| 289 | const row = rows.find((r) => r["id"] === "sx2")!; | |
| 290 | expect(row["closes"]).toBe("[]"); | |
| 291 | expect(row["told_at"]).toBeNull(); | |
| 292 | }); | |
| 293 | ||
| 294 | test("a long run of letters or digits alone is a secret; a slug and a commit id are not", () => { | |
| 295 | const p = new Privacy("salt", app.db); | |
| 296 | expect(p.text(`key ${"q".repeat(40)}`)).toBe("key [secret]"); | |
| 297 | expect(p.text(`id ${"7".repeat(36)}`)).toBe("id [secret]"); | |
| 298 | expect(p.text(`commit ${"ab12".repeat(10)}`)).toBe(`commit ${"ab12".repeat(10)}`); | |
| 299 | expect(p.text("branch scout-a-dataset-as-we-go-the-forges-events")).toContain("scout-a-dataset"); | |
| 300 | }); | |
| 301 | ||
| 302 | test("one person has one name, in an actor and in a payload and in free text", () => { | |
| 303 | const p = new Privacy("salt", app.db); | |
| 304 | expect(p.name("carolyn")).toBe(String(p.who(carol.id))); | |
| 305 | expect(p.name("CarolYN")).toBe(String(p.who(carol.id))); | |
| 306 | expect(p.text("thanks @carolyn and carolyn!")).toBe(`thanks @${p.who(carol.id)} and ${p.who(carol.id)}!`); | |
| 307 | app.bus.append({ kind: "issue.assigned", repoId: undefined, actorId: carol.id, payload: { assignee: "carolyn" } }); | |
| 308 | const row = tableRows(app.db, p, "events").find((e) => e["kind"] === "issue.assigned")!; | |
| 309 | expect(String(row["actor"])).toBe(JSON.parse(String(row["payload"])).assignee); | |
| 310 | }); | |
| 311 | }); |
test/forge-looks.test.ts +1
| @@ -36,6 +36,7 @@ const NOT_A_PAGE: Record<string, string> = { | ||
| 36 | 36 | "/settings": "a form of fields; its slot went to the open help of /boards and /settings/crew (#11170); covered by test/account-help.test.ts", |
| 37 | 37 | "/new": "a form that fills from its link; its slot went to the open help of /boards and /settings/crew (#11170)", |
| 38 | 38 | "/pinned": "no picture: its slot went to /settings/crew, the crew page; covered by test/pinned-page.test.ts", |
| 39 | "/dataset": "no picture: not in app.looks; admin only, a guest sees the not-found page, and the page is covered by test/dataset.test.ts", | |
| 39 | 40 | "/data": "no picture: not in app.looks; a guest sees the not-found page and the page is covered by its own tests", |
| 40 | 41 | "/asked": "no picture: its slot went to /notes, the page that now leads with a person's thoughts; /asked is covered by test/asked.test.ts", |
| 41 | 42 | "/forges": "no picture: its slot went to the preview's /waves and /milestones; the page is covered by its own tests", |
test/job-slices.test.ts +1
| @@ -273,6 +273,7 @@ const UNTIMED: Record<string, string> = { | ||
| 273 | 273 | "pinned-watch": "a one-shot timer between the pinned watch's looks at a pinned deploy (actions/pinned_watch.ts WATCH.sleep); it only resolves the sleep, no work of its own; pinned-watch tests drive the watch with a short sleep", |
| 274 | 274 | "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three", |
| 275 | 275 | "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock", |
| 276 | "dataset-export": "every 10 minutes reads the last export's time and returns unless a night has passed; the publish itself runs once a night in actions/dataset.ts publishDataset and is off without a dataset repository; dataset tests drive publishDataset directly", | |
| 276 | 277 | "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly", |
| 277 | 278 | "meter-watch": "one indexed read of held-full windows every 15 minutes, and a status fetch only while one is held full; meter-watch.test.ts drives it with a fake fetcher; the fixture holds no window", |
| 278 | 279 | "talk-live": "a one-shot timer in talkStream (web/pages/talk.ts), armed only while a person has /talk open and a reply is being written: it sends that one stream its latest live frame, at most one per 125 ms, drawing a block of at most 20,000 characters; talk-live.test.ts drives the stream and counts its frames", |
test/palette-roster.test.ts +1
| @@ -149,6 +149,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 149 | 149 | ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"], |
| 150 | 150 | ["maintenanceweek", "Maintenance, last 7 days", "what each maintenance worker found and did this week"], |
| 151 | 151 | ["offsite", "Off-site backup", "where the sealed lane writes, when it last succeeded, and the last restore drill"], |
| 152 | ["dataset", "Dataset", "what the forge's dataset holds, and what it already answers"], | |
| 152 | 153 | ["capacity", "Capacity", "concurrency and guards, live; e changes a settable one"], |
| 153 | 154 | ["resilience", "Resilience", "where snapshots go and the mirror; each protection green, red or untested"], |
| 154 | 155 | ["recovery-kit", "Recovery kit", "the bucket's read-only key and the file to keep off this machine"], |
new above
offline
A scoped export publishes
closes(and told_at, cost) from issues that may be sealed, though the sealed issue itself is excluded. Filter closed issues bysealed = 0whenw.scopeis set.