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

Every gate run times each test and names those over the budget (20 s a file, 2 s a test); a breach is red on the fast tier for files the pull changed #12091

Parked opened this
Closed without merging

mason/forge:mason/12087-every-gate-run-times-each-test-and-names → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +521 −189
docs/MCP.md +33 −33
@@ -56,11 +56,11 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
5656 | `app_env` | `list`, `set`, `unset` | An app's environment variables: list names, set or unset by scope; write-only | 393 |
5757 | `app_members` | — | People a private app names, who may enter it and its previews | 297 |
5858 | `app_notes` | `hide`, `ban`, `unban` | Notes from an app's forge button and banned senders; hide a note, ban or unban its sender | 306 |
59 | `apps` | — | Apps you can see: live or not, where served, how each runs, what works | 343 |
60 | `archive` | — | Archive or wake a repository (`archived`) | 380 |
61 | `asked` | — | What people asked the crew for: unmerged by default, oldest first | 372 |
62 | `asks` | `stopped`, `look`, `review`, `paused`, `parked`, `declined`, `handover`, `waiting`, `assigned`, `proposal` | What waits on you, most important first; saved filter applies; `filter` sets or clears one | 707 |
63 | `asks_act` | `dismiss`, `decline`, `mute`, `listen`, `undo`, `ship`, `close`, `replan` | Decide asks (`items`): dismiss, ship, close (`reason`), mute, replan; `listen` (`repo`) unmutes; `undo` (`operation`) | 535 |
59 | `apps` | — | Apps you can see: live or not, where served, how each runs, what works | 384 |
60 | `archive` | — | Archive or wake a repository (`archived`) | 421 |
61 | `asked` | — | What people asked the crew for: unmerged by default, oldest first | 415 |
62 | `asks` | `stopped`, `look`, `review`, `paused`, `parked`, `declined`, `handover`, `waiting`, `assigned`, `proposal` | What waits on you, most important first; saved filter applies; `filter` sets or clears one | 749 |
63 | `asks_act` | `dismiss`, `decline`, `mute`, `listen`, `undo`, `ship`, `close`, `replan` | Decide asks (`items`): dismiss, ship, close (`reason`), mute, replan; `listen` (`repo`) unmutes; `undo` (`operation`) | 577 |
6464 | `asks_decide` | — | Answer a hand-over: the decider (`parked:<id>`), or `give_back` to its builder (`handover:`/`assigned:<id>`) | 270 |
6565 | `asks_proposal` | — | Act on a wave proposal: `approve`, `redirect` (`words`), `later` (`again`) | 315 |
6666 | `asks_undecide` | — | Put a set-aside card back on your board, within a day | 208 |
@@ -77,10 +77,10 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
7777 | `board_delete` | — | Delete a board by slug (history keeps it) | 194 |
7878 | `board_pins` | — | The panels pinned to the caller's home (person admins) | 302 |
7979 | `board_write` | — | Write a whole board under a slug: {title, range, refresh, panels} | 231 |
80 | `boards` | — | The forge's boards for person admins: slug, title, range, refresh and panels | 475 |
80 | `boards` | — | The forge's boards for person admins: slug, title, range, refresh and panels | 518 |
8181 | `branches` | `create`, `delete`, `branches`, `tags` | A repo's branches; `name`, `action` create (from `from`) or delete one, not the default | 407 |
8282 | `builds` | — | A repo's build pins (`refs/builds/`): label, commit, pinned by, note | 231 |
83 | `capacity` | — | Forge capacity and guards, live | 468 |
83 | `capacity` | — | Forge capacity and guards, live | 514 |
8484 | `claim_link` | `revoke`, `undo` | A child's claim link: `reveal` a new one, or `action` revoke/undo | 304 |
8585 | `close` | — | Close or reopen (`state` open) an issue or pull | 463 |
8686 | `cloud_account` | — | Change a cloud account by `verb` (admin) | 549 |
@@ -89,7 +89,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
8989 | `confirm_wait` | — | Let an issue go ahead though its blocker closed dropped or split | 269 |
9090 | `contribute` | — | For a new agent: what this forge is, its bottleneck, help-wanted issues, how to propose | 210 |
9191 | `converge` | — | Have a fork's crew merge the parent's updates where both changed a file | 200 |
92 | `crew` | — | List a repository's crew, or add or remove an agent | 387 |
92 | `crew` | — | List a repository's crew, or add or remove an agent | 429 |
9393 | `data` | — | Read SQLite files you may see: tables, rows, read-only SQL; secrets masked | 367 |
9494 | `decisions_by` | — | Who decides parked hand-over cards: `me`, `decider`, `decider_tell` | 305 |
9595 | `detach` | — | Detach a fork from its parent | 210 |
@@ -100,10 +100,10 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
100100 | `email_verify` | — | Send yourself a new verification link | 126 |
101101 | `estimate` | — | Ask an issue's base rate, or record `event` with `p50`, `p90` (instants) and `basis` | 406 |
102102 | `events` | — | Repository events | 259 |
103 | `explore` | — | The apps, people (and, for an admin, forges) you can see, ranked | 627 |
103 | `explore` | — | The apps, people (and, for an admin, forges) you can see, ranked | 672 |
104104 | `family` | — | The forge that sent this one and, for a site admin, those it sent, with state, version | 205 |
105105 | `features` | — | Apps absorbed as forge features: list, read, absorb or un-absorb, change typed settings | 357 |
106 | `feed` | — | Your ranked home timeline; `cursor` pages; saved filter applies | 562 |
106 | `feed` | — | Your ranked home timeline; `cursor` pages; saved filter applies | 604 |
107107 | `feed_chips` | `kind`, `person` | Feed chips you switched off | 262 |
108108 | `feed_dismiss` | `dismissed`, `muted` | Dismiss a feed item or mute its app; `feed` then leaves it out | 280 |
109109 | `feed_like` | — | Like or unlike a feed item as a ledger row, or read its ledger | 308 |
@@ -111,25 +111,25 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
111111 | `flag_set` | — | Set or clear a flag (admin) | 209 |
112112 | `flag_winner` | — | An A/B flag winner becomes default | 206 |
113113 | `flags` | — | Declared flags: why, default, owner issue, live value | 171 |
114 | `flow` | `bugs`, `cpu`, `drift`, `growth` | Pipeline (admin); `q`: `/fleet` rows, `action` plans an op, `apply` does it; `kind:bugs`; `repo`: why stuck | 488 |
114 | `flow` | `bugs`, `cpu`, `drift`, `growth` | Pipeline (admin); `q`: `/fleet` rows, `action` plans an op, `apply` does it; `kind:bugs`; `repo`: why stuck | 530 |
115115 | `follow_mode` | — | How a fork follows its parent: take updates, tell me, or don't follow | 281 |
116116 | `following` | — | Where a fork stands against what it follows: in step, behind, ahead, diverged | 243 |
117117 | `forge_proposals` | — | What this forge proposed to its parent; `reachable` false if it is silent | 245 |
118 | `forge_view` | — | The forge as one picture: counts, apps, runs with stations, health | 239 |
119 | `forges` | — | Forges sent from here (admin; a stage says when to resend), or one forge's plan to read or grant | 387 |
118 | `forge_view` | — | The forge as one picture: counts, apps, runs with stations, health | 282 |
119 | `forges` | — | Forges sent from here (admin; a stage says when to resend), or one forge's plan to read or grant | 431 |
120120 | `fork` | — | Fork a repository into your account; for a guest, a copy to send changes back from | 232 |
121 | `fork_tree` | — | The fork tree around a repo: ancestors, siblings and descendants you may read | 397 |
122 | `forks` | `chain` | A repo's forks you may see, paged by limit and cursor (next_cursor), each with commits ahead and behind | 437 |
121 | `fork_tree` | — | The fork tree around a repo: ancestors, siblings and descendants you may read | 440 |
122 | `forks` | `chain` | A repo's forks you may see, paged by limit and cursor (next_cursor), each with commits ahead and behind | 480 |
123123 | `front_page` | — | The stranger's front page; admin sets `pinned`/`hidden`/`weights` | 457 |
124 | `health` | — | How this forge is: version, commit, draining or not, rollout, incidents | 241 |
125 | `held` | — | What the Later gate holds, and one proposed pass over it | 319 |
124 | `health` | — | How this forge is: version, commit, draining or not, rollout, incidents | 285 |
125 | `held` | — | What the Later gate holds, and one proposed pass over it | 361 |
126126 | `here` | — | What you may do on a forge page; given an app's link, what its /__forge/ door shows | 237 |
127127 | `hold` | — | Hold a pull (`why`) or `release` it; or `path`: hold new work on a file | 522 |
128128 | `hooks` | `list`, `add`, `remove`, `deliveries`, `ping`, `pause`, `resume`, `redeliver` | List, add (`url`, `secret`, `kinds`) or remove (`id`) webhooks; admins | 494 |
129129 | `invites` | `list`, `revoke` | Open invites; `id` revokes | 206 |
130 | `issue` | — | One issue with comments, `blockedBy`, `blocks`; non-writers' text is `untrusted` | 341 |
130 | `issue` | — | One issue with comments, `blockedBy`, `blocks`; non-writers' text is `untrusted` | 384 |
131131 | `issue_teams` | — | Name up to two crew teams to review | 267 |
132 | `issues` | — | A repository's issues by state, label and author, newest first, paged | 473 |
132 | `issues` | — | A repository's issues by state, label and author, newest first, paged | 517 |
133133 | `iterations` | — | A repo's fork family of build pins and runs, as the Iterations page draws them | 279 |
134134 | `keep_plan` | — | Keep a short plan checklist on your issue, replaced whole each time | 415 |
135135 | `knobs` | — | The crew's five knobs and what each does now | 307 |
@@ -140,20 +140,20 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
140140 | `limits` | — | Every limit the owner can hit | 1077 |
141141 | `maintenance` | `status`, `prepare`, `resume`, `pause-duty`, `resume-duty` | Prepare the forge for a power-off, check the drain, or end maintenance (admin) | 308 |
142142 | `make_it_yours` | — | Fork an app you can see: code and history, following the original | 337 |
143 | `map` | — | An app's plan: ready or waiting, critical path, crew, parkedTwice; `done` adds closed; `first: N` ranks N first | 375 |
143 | `map` | — | An app's plan: ready or waiting, critical path, crew, parkedTwice; `done` adds closed; `first: N` ranks N first | 416 |
144144 | `merge` | `land` | Land a pull, as its page's Merge button does; a person's only | 362 |
145145 | `migrate` | — | Bring a repo in by public `url` (`name`, `crew`), history and all | 269 |
146 | `milestones` | — | How far each ask is | 391 |
146 | `milestones` | — | How far each ask is | 439 |
147147 | `mint_invite` | — | Mint a one-use invite link, shown once, valid `days` (1–30, default 7) | 225 |
148148 | `mirror_now` | — | Admin: bring the snapshot mirror level now | 129 |
149149 | `mirror_set` | — | Admin: set or forget the snapshot mirror | 296 |
150150 | `model_ceiling` | — | Set an account's daily and per-run model spend ceilings in dollars | 422 |
151151 | `model_grant` | — | Give a person a monthly model grant (`usdPerMonth`, 0 takes it back) | 338 |
152 | `new_app` | — | Make an app from a sentence: a repo, production, and with `description` a first issue | 553 |
152 | `new_app` | — | Make an app from a sentence: a repo, production, and with `description` a first issue | 594 |
153153 | `next_steps` | — | On a spawned forge, its owner's first three steps, each done or not | 207 |
154154 | `next_up` | — | The ranked list the crew builds from; `issue` + `to` (top, not-now, after:N) moves one | 349 |
155155 | `notify` | — | Read, set or clear your phone notify URL | 146 |
156 | `now` | — | What the crew does across your apps: who, on what, since when, cost; what awaits review | 252 |
156 | `now` | — | What the crew does across your apps: who, on what, since when, cost; what awaits review | 294 |
157157 | `open_pull` | — | Open a pull request, from a branch or from your fork | 449 |
158158 | `org_create` | — | Make an organization | 151 |
159159 | `org_teams` | `create`, `add_member`, `members`, `metrics`, `remove_member`, `remove` | An org's teams: create, add member with a role, list members, remove | 682 |
@@ -172,29 +172,29 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
172172 | `prompts` | `list`, `add`, `run`, `remove`, `instagram` | Prompt sources: list, add (`kind`, `token`, `at`), run or remove (`id`) | 470 |
173173 | `proposal_tokens` | — | A child's propose-only token: `mint` (`child`, `origin`), `list`, `revoke` (`id`) | 396 |
174174 | `propose_to_parent_forge` | — | Offer this forge's landed change to its parent as a pull on `child/<name>/…` | 221 |
175 | `pull` | — | A pull: title, state, head, base; open: `mergeable`, `conflicts`, `checkStale`, `check` | 346 |
176 | `pulls` | — | A repository's pulls, newest first; no `repo`: all open pulls you may read, oldest first | 411 |
175 | `pull` | — | A pull: title, state, head, base; open: `mergeable`, `conflicts`, `checkStale`, `check` | 388 |
176 | `pulls` | — | A repository's pulls, newest first; no `repo`: all open pulls you may read, oldest first | 454 |
177177 | `queue_gates` | — | Recent merge-queue gates: pulls, verdicts, failing tests | 277 |
178178 | `quotas` | — | Enforced per-account quotas (never an admin): repositories, apps, storage, previews, runs, checks | 342 |
179179 | `read_file` | — | No shell? Read a file or list a directory at a ref (default branch); over 5 MB answers tooLarge | 317 |
180180 | `release_hold` | — | Hold or release the release keeper's cuts (admin) | 202 |
181181 | `release_keeper` | — | The release keeper's releases, holds and what blocks the next cut | 192 |
182182 | `release_now` | — | Cut a release now, with a reason (admin) | 176 |
183 | `releases` | — | Kept releases, newest first | 253 |
183 | `releases` | — | Kept releases, newest first | 298 |
184184 | `repo` | `open`, `add`, `remove`, `close` | One repository you can read, as GET /api/v1/repos/:owner/:name | 383 |
185185 | `repo_labels` | — | Repo labels: list (default), create, update, remove (admin token) | 351 |
186186 | `repo_settings` | — | Read, change or move (newOwner) a repo: PATCH /api/v1/repos/:owner/:name (admin); mirrorPacks mirrors the packs' upstreams | 444 |
187 | `reports` | `accept`, `dismiss` | Outsiders' reports; `id`+`action`: accept or dismiss | 310 |
188 | `restore_drill` | — | Drill-restore the newest snapshot | 173 |
187 | `reports` | `accept`, `dismiss` | Outsiders' reports; `id`+`action`: accept or dismiss | 355 |
188 | `restore_drill` | — | Drill-restore the newest snapshot | 216 |
189189 | `returns` | — | What crew tokens bought in `days` (1–90, default 7): dollars, runs, landed, cost/change | 284 |
190190 | `review` | — | Approve a pull, or request changes (`reason` required); your own pull is refused | 350 |
191191 | `rollback` | — | Plan, then apply, a rollback to a kept release (admin) | 209 |
192192 | `run_log` | — | A run's log, or its last `tail` lines, as GET /api/v1/repos/:owner/:name/runs/:id/log | 332 |
193 | `runs` | `agent`, `deploy`, `check` | A repository's runs, newest first: id, kind, state, number, start, end | 483 |
193 | `runs` | `agent`, `deploy`, `check` | A repository's runs, newest first: id, kind, state, number, start, end | 525 |
194194 | `say` | `list`, `new`, `rename`, `archive`, `restore`, `build`, `build_state`, `build_diff`, `build_restore`, `build_publish` | Say something on an issue or pull; with no repo, to the forge's own agent, and manage its conversations (action) | 585 |
195 | `scorecard` | — | Crew scorecard (forge admin): per agent, all time and 30 days | 237 |
195 | `scorecard` | — | Crew scorecard (forge admin): per agent, all time and 30 days | 284 |
196196 | `seal` | `private` | Seal or unseal an issue or pull: a sealed one is seen only by writers and crew | 297 |
197 | `search` | `all`, `issues`, `repos`, `code` | Find issues, pulls, repositories and code you can read; `kind` and `repo` narrow | 429 |
197 | `search` | `all`, `issues`, `repos`, `code` | Find issues, pulls, repositories and code you can read; `kind` and `repo` narrow | 473 |
198198 | `secrets` | — | Admin: list\|set\|remove sealed secrets | 248 |
199199 | `sessions` | `list`, `end`, `end_idle`, `signins`, `shells` | Where you are signed in: your tokens and browsers, never a secret; `username` for a person as owner; action end + id signs a browser out | 385 |
200200 | `sever` | — | Unlink a spawned forge from its parent (owner of its `forge` repo only) | 214 |
@@ -227,13 +227,13 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
227227 | `tokens` | — | Your API tokens, no secrets | 146 |
228228 | `trail` | — | A migrated repository's source and forks; `shown` shows or hides them (admin) | 258 |
229229 | `upstream` | — | Read, set (`enabled`) or `check` the upstream a repository follows | 302 |
230 | `usage` | — | Crew spend: with `repo`, `days` (1–90) by agent, issue; without, today, last24h, headroom % | 345 |
230 | `usage` | — | Crew spend: with `repo`, `days` (1–90) by agent, issue; without, today, last24h, headroom % | 388 |
231231 | `valves` | — | The week's pipes and valves; with `repo` and `level`, turns a valve (plans first) | 269 |
232232 | `variant` | — | Like or dislike a pull among its variants; a later vote replaces; dislike closes it | 349 |
233233 | `vision` | — | VISION.md: purpose, order, rules | 235 |
234234 | `wait_for` | — | An issue waits for another; `stop` ends it | 297 |
235235 | `watch` | — | Watch a milestone, or stop (`watch: false`); your phone is told once when it lands | 341 |
236 | `waves` | — | Waves; `version`: one | 260 |
236 | `waves` | — | Waves; `version`: one | 302 |
237237 | `week` | — | The week's retrospective; `take` accepts one proposal | 226 |
238238 | `whoami_can` | `role`, `passkeys` | What you can do: your role and its roles-table row, yes or no each | 231 |
239239 | `write_file` | — | No shell? Commit one file to a branch | 342 |
docs/design/attention-budget.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "home": {
33 "390": {
4 "words": 95,
4 "words": 100,
55 "blocks": 20,
66 "colours": 2
77 },
88 "1280": {
9 "words": 95,
9 "words": 100,
1010 "blocks": 20,
1111 "colours": 2
1212 }
docs/design/size-budget.json +8 −8
@@ -1,34 +1,34 @@
11 {
22 "/": {
33 "js": 21248,
4 "css": 38912
4 "css": 40192
55 },
66 "/explore": {
77 "js": 20992,
8 "css": 38912
8 "css": 40192
99 },
1010 "/map": {
1111 "js": 26624,
12 "css": 40448
12 "css": 41728
1313 },
1414 "/:owner/:name": {
1515 "js": 34816,
16 "css": 38912
16 "css": 40192
1717 },
1818 "/changelog": {
1919 "js": 25856,
20 "css": 38912
20 "css": 40192
2121 },
2222 "/pricing": {
2323 "js": 20992,
24 "css": 38912
24 "css": 40192
2525 },
2626 "/forges/new": {
2727 "js": 21248,
28 "css": 38912
28 "css": 40192
2929 },
3030 "/claim": {
3131 "js": 23552,
32 "css": 38912
32 "css": 40192
3333 }
3434 }
scripts/gate.ts +12
@@ -37,6 +37,18 @@ export type Exclusion = {
3737
3838 export const EXCLUDED: readonly Exclusion[] = [];
3939
40 /**
41 * Gated files set aside from the time budget (`scripts/test-budget.ts`:
42 * 20 s a file, 2 s a test): each still runs and is still timed, and its
43 * breaches are named "SLOW aside" rather than counted, until the issue
44 * that owns it makes it fast and deletes its entry.
45 */
46 export const SLOW: readonly Exclusion[] = [
47 { file: "test/fork-flow.test.ts", reason: "48 s alone in scripts/test-times.json", issue: 1242 },
48 { file: "test/studio.test.ts", reason: "35 s alone in scripts/test-times.json", issue: 1242 },
49 { file: "test/crew-wrapup.test.ts", reason: "24 s alone in scripts/test-times.json", issue: 1242 },
50 ];
51
4052 /**
4153 * Everything wrong with the quarantine, against the test files that exist:
4254 * one line per problem, none when every exclusion is sound.
scripts/header-width-allow.json −1
@@ -7,7 +7,6 @@
77 "src/core/runs.ts",
88 "src/crew/brief.ts",
99 "src/crew/hot_history.ts",
10 "src/crew/week_read.ts",
1110 "src/flow/hot_trend.ts",
1211 "src/flow/keeper.ts",
1312 "src/flow/kpis.ts",
scripts/test-budget.ts added +197
@@ -0,0 +1,197 @@
1 /**
2 * The time budget every gate run holds its tests to (#12087, the first
3 * step of #1242): a test file over {@link FILE_BUDGET_SECONDS}, a single
4 * test over {@link TEST_BUDGET_SECONDS}. Files `SLOW` in `scripts/gate.ts`
5 * names are set aside, each under the issue that owns making it fast.
6 *
7 * Plain data in, plain data out. `scripts/test-shards.ts` reads each
8 * test's time from Bun's JUnit report (`parseJunit`), asks `breaches`,
9 * prints `budgetLines`, and asks `budgetBinds` whether a breach is red:
10 * only on the fast tier, only for a test file the pull changed. On the
11 * full tier a breach is reported, never red.
12 */
13
14 /** A test file over this many seconds, alone in its own `bun test`, is over the budget. */
15 export const FILE_BUDGET_SECONDS = 20;
16 /** A single test over this many seconds is over the budget. */
17 export const TEST_BUDGET_SECONDS = 2;
18 /** How many of the slowest tests the summary names. */
19 export const SLOWEST_TESTS = 5;
20
21 export type FileTime = { file: string; seconds: number };
22 /** `test` is Bun's own name for it: its describe blocks and its title, joined by ` > `. */
23 export type TestTime = { file: string; test: string; seconds: number };
24 /** A file set aside: why it is slow, and the issue that owns making it fast. */
25 export type SlowEntry = { file: string; reason: string; issue: number };
26
27 export type Breach =
28 | { kind: "file"; file: string; seconds: number }
29 | { kind: "test"; file: string; test: string; seconds: number };
30
31 export type Budget = {
32 /** Every file and test over its budget, not set aside, slowest first. */
33 over: Breach[];
34 /** Every breach in a file `SLOW` names, slowest first. */
35 aside: (Breach & { issue: number })[];
36 /** The slowest tests of the run, at most {@link SLOWEST_TESTS}. */
37 slowest: TestTime[];
38 /** Seconds the slowest took between them, and the seconds of every test timed. */
39 slowestSeconds: number;
40 totalSeconds: number;
41 };
42
43 const plain = (file: string): string => file.replace(/^\.\//, "");
44
45 /** What is over the budget in one run's times, `slow` aside. */
46 export function breaches(
47 run: { files: readonly FileTime[]; tests: readonly TestTime[] },
48 slow: readonly SlowEntry[],
49 ): Budget {
50 const issueOf = new Map(slow.map((entry) => [plain(entry.file), entry.issue]));
51 const found: Breach[] = [
52 ...run.files
53 .filter((f) => f.seconds > FILE_BUDGET_SECONDS)
54 .map((f): Breach => ({ kind: "file", file: plain(f.file), seconds: f.seconds })),
55 ...run.tests
56 .filter((t) => t.seconds > TEST_BUDGET_SECONDS)
57 .map((t): Breach => ({ kind: "test", file: plain(t.file), test: t.test, seconds: t.seconds })),
58 ].sort((a, b) => b.seconds - a.seconds);
59 const over: Breach[] = [];
60 const aside: (Breach & { issue: number })[] = [];
61 for (const breach of found) {
62 const issue = issueOf.get(breach.file);
63 if (issue === undefined) over.push(breach);
64 else aside.push({ ...breach, issue });
65 }
66 const slowest = [...run.tests]
67 .sort((a, b) => b.seconds - a.seconds)
68 .slice(0, SLOWEST_TESTS)
69 .map((t) => ({ ...t, file: plain(t.file) }));
70 const sum = (list: readonly TestTime[]): number => list.reduce((total, t) => total + t.seconds, 0);
71 return { over, aside, slowest, slowestSeconds: sum(slowest), totalSeconds: sum(run.tests) };
72 }
73
74 /**
75 * Whether a breach in `file` turns the run red: on the fast tier, for a
76 * test file the pull changed. The full tier reports it and stays green.
77 */
78 export function budgetBinds(tier: string, changed: readonly string[], file: string): boolean {
79 return tier === "fast" && changed.map(plain).includes(plain(file));
80 }
81
82 /** One breach as the log names it: file, test where it is one, seconds and the budget it broke. */
83 export function breachLine(breach: Breach): string {
84 return breach.kind === "file"
85 ? `${breach.file}: ${breach.seconds.toFixed(1)}s (a file over ${FILE_BUDGET_SECONDS}s)`
86 : `${breach.file} > ${breach.test}: ${breach.seconds.toFixed(2)}s (a test over ${TEST_BUDGET_SECONDS}s)`;
87 }
88
89 /** The block a run's summary ends with: the slowest tests, then the count over and each breach. */
90 export function budgetLines(budget: Budget): string[] {
91 const share =
92 budget.totalSeconds > 0 ? `${Math.round((100 * budget.slowestSeconds) / budget.totalSeconds)}%` : "0%";
93 return [
94 `Slowest ${budget.slowest.length} tests: ${budget.slowestSeconds.toFixed(2)}s, ${share} of ${budget.totalSeconds.toFixed(1)}s in tests`,
95 ...budget.slowest.map((t) => ` ${t.seconds.toFixed(2)}s ${t.file} > ${t.test}`),
96 `over the budget: ${budget.over.length}, SLOW aside: ${budget.aside.length}`,
97 ...budget.over.map((breach) => ` ${breachLine(breach)}`),
98 ...budget.aside.map((breach) => ` aside: ${breachLine(breach)} (SLOW, #${breach.issue})`),
99 ];
100 }
101
102 const ENTITY: Record<string, string> = { lt: "<", gt: ">", quot: '"', apos: "'", amp: "&" };
103
104 function unescapeXml(text: string): string {
105 return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (whole, name: string) => {
106 if (name.startsWith("#x")) return String.fromCodePoint(Number.parseInt(name.slice(2), 16));
107 if (name.startsWith("#")) return String.fromCodePoint(Number.parseInt(name.slice(1), 10));
108 return ENTITY[name] ?? whole;
109 });
110 }
111
112 function attributes(text: string): Map<string, string> {
113 const found = new Map<string, string>();
114 for (const [, key, value] of text.matchAll(/([A-Za-z_:][\w:.-]*)="([^"]*)"/g)) found.set(key!, unescapeXml(value!));
115 return found;
116 }
117
118 /**
119 * Each test's time from Bun's JUnit report (`bun test --reporter=junit
120 * --reporter-outfile=…`): its file, its describe blocks and title joined
121 * by ` > ` as Bun's console names it, and its seconds. A testcase with no
122 * file or no finite time is skipped, never guessed.
123 */
124 export function parseJunit(xml: string): TestTime[] {
125 const tests: TestTime[] = [];
126 // Open `testsuite`s: the outermost is the file, the rest are describe blocks.
127 const suites: string[] = [];
128 for (const [, close, tag, attrs, selfClosing] of xml.matchAll(/<(\/?)(testsuite|testcase)\b([^>]*?)(\/?)>/g)) {
129 if (tag === "testsuite") {
130 if (close) suites.pop();
131 else if (!selfClosing) suites.push(attributes(attrs!).get("name") ?? "");
132 continue;
133 }
134 if (close) continue;
135 const found = attributes(attrs!);
136 const file = found.get("file");
137 const seconds = Number(found.get("time"));
138 if (!file || !Number.isFinite(seconds) || seconds < 0) continue;
139 tests.push({ file: plain(file), test: [...suites.slice(1), found.get("name") ?? ""].join(" > "), seconds });
140 }
141 return tests;
142 }
143
144 /** Each file's tests by name to seconds, as `.forge-cache/test-times-tests.json` keeps them. */
145 export type TestTable = Map<string, Map<string, number>>;
146
147 /** A table written by {@link formatTestTable}; anything else is refused. */
148 export function parseTestTable(text: string): { ok: true; value: TestTable } | { ok: false; error: string } {
149 let raw: unknown;
150 try {
151 raw = JSON.parse(text);
152 } catch {
153 return { ok: false, error: "not JSON" };
154 }
155 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { ok: false, error: "not an object" };
156 const table: TestTable = new Map();
157 for (const [file, tests] of Object.entries(raw)) {
158 if (typeof tests !== "object" || tests === null || Array.isArray(tests))
159 return { ok: false, error: `${file} is not an object` };
160 const row = new Map<string, number>();
161 for (const [test, seconds] of Object.entries(tests as Record<string, unknown>)) {
162 if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds < 0)
163 return { ok: false, error: `${file} > ${test} is not a time` };
164 row.set(test, seconds);
165 }
166 table.set(file, row);
167 }
168 return { ok: true, value: table };
169 }
170
171 /**
172 * `old` with every file this run timed replaced by its fresh tests, and
173 * every file no longer in the tree forgotten.
174 */
175 export function refreshTestTable(old: TestTable, tests: readonly TestTime[], exists: (file: string) => boolean): TestTable {
176 const fresh = new Map<string, Map<string, number>>();
177 for (const t of tests) {
178 const row = fresh.get(plain(t.file)) ?? new Map<string, number>();
179 row.set(t.test, Math.round(t.seconds * 1000) / 1000);
180 fresh.set(plain(t.file), row);
181 }
182 const table: TestTable = new Map();
183 for (const [file, row] of old) if (!fresh.has(file) && exists(file)) table.set(file, row);
184 for (const [file, row] of fresh) table.set(file, row);
185 return table;
186 }
187
188 /** Sorted by file, then by test, so the file diffs by line. */
189 export function formatTestTable(table: TestTable): string {
190 const out: Record<string, Record<string, number>> = {};
191 for (const file of [...table.keys()].sort()) {
192 const row: Record<string, number> = {};
193 for (const test of [...table.get(file)!.keys()].sort()) row[test] = table.get(file)!.get(test)!;
194 out[file] = row;
195 }
196 return `${JSON.stringify(out, null, 2)}\n`;
197 }
scripts/test-shards.ts +76 −5
@@ -38,6 +38,12 @@
3838 * waits on go first. `FORGE_CHECK_ONLY` (comma-separated test files, set
3939 * by the forge for a bisection step) keeps only those files.
4040 *
41 * Every run also writes Bun's JUnit report and reads each test's time
42 * from it; its summary ends with the slowest tests and what is over the
43 * time budget (`scripts/test-budget.ts`, #12087), red on the fast tier
44 * only for a test file the pull changed. A green run of the gate's files
45 * writes those times to `.forge-cache/test-times-tests.json`.
46 *
4147 * The whole gate, unsliced (`--gate` on the full tier, as `check.run`),
4248 * runs one file per `bun test`, heaviest first into whichever worker is
4349 * free, so every file is timed alone; when it is green it writes those
@@ -82,7 +88,19 @@ import {
8288 CRASH_RERUNS,
8389 type ShardResult,
8490 } from "./shards.ts";
85 import { gateFiles, gateRefusal, presentTests } from "./gate.ts";
91 import { gateFiles, gateRefusal, presentTests, SLOW } from "./gate.ts";
92 import {
93 breaches,
94 budgetBinds,
95 budgetLines,
96 breachLine,
97 formatTestTable,
98 parseJunit,
99 parseTestTable,
100 refreshTestTable,
101 type FileTime,
102 type TestTime,
103 } from "./test-budget.ts";
86104 import { cgroupMemory, summaryLines } from "./gate-summary.ts";
87105 import { GATE_FILE, executedFiles, formatImpact, gateListAdds, handedImpact, mergeImpact, parseImpact } from "../src/checks/impact.ts";
88106 import { importsReader, readImpact, scansIn } from "./tier-input.ts";
@@ -104,6 +122,8 @@ const IMPACT_NAME = handed ?? "scripts/test-impact.json";
104122 // What the forge keeps between checks (`src/checks/cache.ts`): the full
105123 // gate's own per-file times, fresher than the committed table.
106124 const CACHED_TIMES = `${CHECK_CACHE}/test-times.json`;
125 // Each test's own time, from the last green run (#12087).
126 const CACHED_TEST_TIMES = `${CHECK_CACHE}/test-times-tests.json`;
107127
108128 const argv = process.argv.slice(2);
109129 const record = argv.includes("--record");
@@ -477,7 +497,8 @@ let crashReruns = 0;
477497 /** What a live first run shows once it has gone red: held until its end. */
478498 const RED_SIGN = /^(\(fail\)|# Unhandled error|error:)/m;
479499
480 type Timed = ShardResult & { seconds: number };
500 /** A shard's result, its wall seconds, and each of its tests' time from Bun's JUnit report. */
501 type Timed = ShardResult & { seconds: number; tests: TestTime[] };
481502
482503 /**
483504 * One shard. `live` (shards running one at a time) writes the shard's
@@ -531,9 +552,14 @@ async function runShardIn(
531552 // Measuring: one file per process, its coverage in a directory of its own.
532553 const covDir =
533554 measure && slice.length === 1 ? mkdtempSync(join(tmpdir(), "impact-")) : undefined;
534 const cover = covDir
535 ? ["--coverage", "--coverage-reporter=lcov", `--coverage-dir=${covDir}`]
536 : [];
555 // Bun's JUnit report beside its console one, which it leaves as it was:
556 // each test's own time (#12087). The run that is the verdict writes it last.
557 const junit = join(home, "junit.xml");
558 const cover = [
559 ...(covDir ? ["--coverage", "--coverage-reporter=lcov", `--coverage-dir=${covDir}`] : []),
560 "--reporter=junit",
561 `--reporter-outfile=${junit}`,
562 ];
537563 const run = async (
538564 targets: string[],
539565 extra: string[],
@@ -659,11 +685,18 @@ async function runShardIn(
659685 }
660686 rmSync(covDir, { recursive: true, force: true });
661687 }
688 let tests: TestTime[] = [];
689 try {
690 tests = parseJunit(readFileSync(junit, "utf8"));
691 } catch {
692 // A run that died before its report times no test; its file time still stands.
693 }
662694 return {
663695 files: slice,
664696 code,
665697 output: text,
666698 seconds: (performance.now() - started) / 1000,
699 tests,
667700 };
668701 }
669702
@@ -849,4 +882,42 @@ if (code !== 0 && tier === "fast" && range !== undefined && only === undefined)
849882 if (verdict.cleared) code = 0;
850883 }
851884 }
885
886 // The time budget (#12087): every run names its slowest tests and each
887 // file or test over the budget; a breach is red only on the fast tier, in
888 // a test file the pull changed. A file alone in its shard is timed from
889 // spawn to exit; one beside others, by the sum of its tests.
890 const fileTimes: FileTime[] = results.flatMap((result) => {
891 if (result.files.length === 1) return [{ file: result.files[0]!, seconds: result.seconds }];
892 return result.files.map((file) => ({
893 file,
894 seconds: result.tests
895 .filter((t) => t.file === file.replace(/^\.\//, ""))
896 .reduce((sum, t) => sum + t.seconds, 0),
897 }));
898 });
899 const testTimes = results.flatMap((result) => result.tests);
900 const budget = breaches({ files: fileTimes, tests: testTimes }, SLOW);
901 // Only a run of the gate's own files: a hand-picked slice (a fixture, say)
902 // is not what the forge keeps between checks.
903 if (ending.code === 0 && testTimes.length > 0 && (gate || tier === "fast")) {
904 let old = new Map<string, Map<string, number>>();
905 try {
906 const parsed = parseTestTable(readFileSync(CACHED_TEST_TIMES, "utf8"));
907 if (parsed.ok) old = parsed.value;
908 else console.log(`test-shards: ${CACHED_TEST_TIMES} refused (${parsed.error}); writing a fresh table`);
909 } catch {
910 // None yet: this run writes the first.
911 }
912 mkdirSync(CHECK_CACHE, { recursive: true });
913 writeFileSync(CACHED_TEST_TIMES, formatTestTable(refreshTestTable(old, testTimes, (file) => existsSync(file))));
914 console.log(`test-shards: wrote ${testTimes.length} test times to ${CACHED_TEST_TIMES}`);
915 }
916 console.log(`\n${budgetLines(budget).join("\n")}`);
917 const binding = budget.over.filter((breach) => budgetBinds(tier, changed, breach.file));
918 if (binding.length > 0) {
919 for (const breach of binding)
920 console.log(`test-shards: over the budget in a test file this pull changed: ${breachLine(breach)}`);
921 if (code === 0) code = 1;
922 }
852923 process.exit(code);
src/crew/week_burn.ts deleted −57
@@ -1,57 +0,0 @@
1 /**
2 * The week's burn (#8910): the change in the measured share of the week over
3 * time, from stored readings of the meter. Dollars are never turned into
4 * percent here. `burnFrom` is pure; `noteReading` and `readingsSince` keep
5 * the readings in `week_reading`.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 /** One reading of the meter: the share of the week still free, 0..100. */
11 export interface Reading {
12 readonly at: number;
13 readonly freePct: number;
14 }
15
16 /** Readings closer than this are one reading. */
17 export const READING_GAP_MS = 60_000;
18 /** Readings further apart than this say nothing about the pace now. */
19 export const BURN_MIN_SPAN_MS = 15 * 60_000;
20
21 /**
22 * Percent of the week spent an hour over the `hours` before `now`, or null
23 * with too few readings. The baseline is the newest reading at or before the
24 * window's start, else the oldest inside it; the span between it and the
25 * newest reading must reach `BURN_MIN_SPAN_MS`. A rise (a reset) is no burn.
26 */
27 export function burnFrom(readings: readonly Reading[], now: number, hours: number): number | null {
28 const seen = readings.filter((r) => r.at <= now).sort((a, b) => a.at - b.at);
29 const last = seen[seen.length - 1];
30 if (last === undefined) return null;
31 const start = now - hours * 3_600_000;
32 const before = seen.filter((r) => r.at <= start);
33 const base = before[before.length - 1] ?? seen.find((r) => r.at > start);
34 if (base === undefined || last.at - base.at < BURN_MIN_SPAN_MS) return null;
35 return Math.max(0, base.freePct - last.freePct) / ((last.at - base.at) / 3_600_000);
36 }
37
38 /** Store a reading unless one was stored within `READING_GAP_MS`; forget what is older than `keepMs`. */
39 export function noteReading(db: Database, scope: string, now: number, freePct: number, keepMs: number): void {
40 const at = new Date(now).toISOString();
41 const newest = db
42 .query<{ at: string }, [string]>("SELECT MAX(at) AS at FROM week_reading WHERE scope = ?1")
43 .get(scope)?.at;
44 if (newest != null && Math.abs(now - Date.parse(newest)) < READING_GAP_MS) return;
45 db.query("INSERT OR REPLACE INTO week_reading (scope, at, free_pct) VALUES (?1, ?2, ?3)").run(scope, at, freePct);
46 db.query("DELETE FROM week_reading WHERE scope = ?1 AND at < ?2").run(scope, new Date(now - keepMs).toISOString());
47 }
48
49 /** The readings of `scope` since `since` (ms). */
50 export function readingsSince(db: Database, scope: string, since: number): Reading[] {
51 return db
52 .query<{ at: string; free_pct: number }, [string, string]>(
53 "SELECT at, free_pct FROM week_reading WHERE scope = ?1 AND at >= ?2 ORDER BY at",
54 )
55 .all(scope, new Date(since).toISOString())
56 .map((r) => ({ at: Date.parse(r.at), freePct: r.free_pct }));
57 }
src/flow/lanes_read.ts +4 −1
@@ -512,7 +512,10 @@ function askedNext(db: Database): { items: LaneItem[]; total: number } {
512512 return { items, total };
513513 }
514514
515 /** The slow part: the crew's order, the figures, the alarms and the week. `app` is the two things the week reads (a database and a data directory), nothing else. */
515 /**
516 * The slow part: the crew's order, the figures, the alarms and the week. `app` is the two things
517 * the week reads (a database and a data directory), nothing else.
518 */
516519 export function readSlow(
517520 db: Database,
518521 now: Date,
src/web/pages/home_flow.ts +10 −2
@@ -287,7 +287,11 @@ export async function forgesRegion(app: App): Promise<Html> {
287287
288288 // ---- the page ----
289289
290 /** The filter: a select whose other apps are read from `data-apps` by the page's script when it is opened, so no list of them is written out as text. Without scripts, an app's `owner/name` is typed. */
290 /**
291 * The filter: a select whose other apps are read from `data-apps` by the page's script when it is
292 * opened, so no list of them is written out as text. Without scripts, an app's `owner/name` is
293 * typed.
294 */
291295 function filterForm(repos: readonly string[], only: string | null): Html {
292296 return html`<form class="hf-filter" method="get" action="/home" id="hf-filter">
293297 <label class="hf-filter-label" for="hf-app">Show</label>
@@ -334,7 +338,11 @@ export async function homeFlowPage(ctx: Ctx): Promise<Response> {
334338 return res;
335339 }
336340
337 /** A lane's ETag: the picture's version of the lane and what else its words read, for this viewer and this filter, and the minute (its ages are in minutes). A lane that has not changed answers 304 without being drawn. */
341 /**
342 * A lane's ETag: the picture's version of the lane and what else its words read, for this viewer
343 * and this filter, and the minute (its ages are in minutes). A lane that has not changed answers
344 * 304 without being drawn.
345 */
338346 function laneTag(picture: LanePicture, key: LaneKey, viewer: string, only: string | null, now: number): string {
339347 const b = picture.builders;
340348 return Bun.hash(`${picture.versions[key]}|${picture.moved[key]}|${b.running}/${b.slots}|${viewer}|${only ?? ""}|${Math.floor(now / 60_000)}`).toString(36);
src/web/studio/cards.ts +1 −1
@@ -1213,7 +1213,7 @@ report();
12131213 `;
12141214
12151215 const pal = (t: "light" | "dark"): string => `--c-bg:${CARD_PALETTE[t].bg};--c-fg:${CARD_PALETTE[t].fg};--c-link:${CARD_PALETTE[t].link};color-scheme:${t}`;
1216 export const CARD_CSS = `:root{${pal("light")}}@media(prefers-color-scheme:dark){:root{${pal("dark")}}}:root[data-theme=light]{${pal("light")}}:root[data-theme=dark]{${pal("dark")}}:root{--c-line:color-mix(in srgb,var(--c-fg) 14%,var(--c-bg));--c-soft:color-mix(in srgb,var(--c-fg) 7%,var(--c-bg));--c-mute:color-mix(in srgb,var(--c-fg) 78%,var(--c-bg))}body{font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif);margin:0;padding:12px;background:var(--c-bg);color:var(--c-fg)}#card{border:1px solid var(--c-line);border-radius:var(--border-radius-lg,12px);padding:16px}h2{margin:0;font-size:17px;line-height:1.25}.status{margin:6px 0 0;color:var(--c-mute);font-size:13px}dl{margin:14px 0 0;border-top:1px solid var(--c-line)}h2,dt,dd{overflow-wrap:anywhere}dt{font-weight:600;padding-top:10px}dd{margin:2px 0 0;padding-bottom:10px;border-bottom:1px solid var(--c-line);color:var(--c-mute)}dd:last-child{border-bottom:0}a{color:var(--c-link);text-underline-offset:2px;display:inline-flex;align-items:center;min-height:44px}@media(pointer:fine){a{min-height:0}}button,input{font:inherit;color:var(--c-fg);border:1px solid var(--c-line);background:var(--c-soft);border-radius:var(--border-radius-sm,8px);min-height:44px;box-sizing:border-box}button{margin:8px 8px 0 0;padding:4px 14px;cursor:pointer}button.primary{background:var(--c-link);border-color:transparent;color:var(--c-bg);font-weight:600}input{padding:4px 10px;width:100%;margin-top:10px}:focus-visible{outline:2px solid var(--c-link);outline-offset:2px}`;
1216 export const CARD_CSS = `:root{${pal("light")}}@media(prefers-color-scheme:dark){:root{${pal("dark")}}}:root[data-theme=light]{${pal("light")}}:root[data-theme=dark]{${pal("dark")}}:root{--c-line:color-mix(in srgb,var(--c-fg) 14%,var(--c-bg));--c-soft:color-mix(in srgb,var(--c-fg) 7%,var(--c-bg));--c-mute:color-mix(in srgb,var(--c-fg) 78%,var(--c-bg))}body{font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif);margin:0;padding:12px;background:var(--c-bg);color:var(--c-fg)}#card{border:1px solid var(--c-line);border-radius:var(--border-radius-lg,12px);padding:16px}h2{margin:0;font-size:16px;line-height:1.25}.status{margin:6px 0 0;color:var(--c-mute);font-size:13px}dl{margin:14px 0 0;border-top:1px solid var(--c-line)}h2,dt,dd{overflow-wrap:anywhere}dt{font-weight:600;padding-top:10px}dd{margin:2px 0 0;padding-bottom:10px;border-bottom:1px solid var(--c-line);color:var(--c-mute)}dd:last-child{border-bottom:0}a{color:var(--c-link);text-underline-offset:2px;display:inline-flex;align-items:center;min-height:44px}@media(pointer:fine){a{min-height:0}}button,input{font:inherit;color:var(--c-fg);border:1px solid var(--c-line);background:var(--c-soft);border-radius:var(--border-radius-sm,8px);min-height:44px;box-sizing:border-box}button{margin:8px 8px 0 0;padding:4px 14px;cursor:pointer}button.primary{background:var(--c-link);border-color:transparent;color:var(--c-bg);font-weight:600}input{padding:4px 10px;width:100%;margin-top:10px}:focus-visible{outline:2px solid var(--c-link);outline-offset:2px}`;
12171217
12181218 export const CARD_SHELL = (kind: CardKind): string =>
12191219 html`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><meta name="color-scheme" content="light dark"><title>${CARD_TITLE[kind]}</title><style>${raw(CARD_CSS)}</style><div id="card"><h2>${CARD_TITLE[kind]}</h2><p class="status">The same answer is in the chat as text; this card fills in when the app sends it.</p></div><script>${raw(SHELL_JS)}</script>`.text;
test/app-home-batched.test.ts +6 −1
@@ -269,7 +269,12 @@ async function statementsByText(path: string): Promise<Map<string, number>> {
269269 await quiet(app.db);
270270 const seen = new Map<string, number>();
271271 door.query = (sql: string) => {
272 const key = sql.replace(/IN \((\?\d*,?)+\)/g, "IN (?…)").replace(/\s+/g, " ");
272 // A batch's placeholders, `IN (?…)` or `VALUES (?1, ?2),…`, are one statement however many
273 // rows it names.
274 const key = sql
275 .replace(/IN \((\?\d*,?)+\)/g, "IN (?…)")
276 .replace(/VALUES (\(\?\d+, \?\d+\),?)+/g, "VALUES (?…)")
277 .replace(/\s+/g, " ");
273278 seen.set(key, (seen.get(key) ?? 0) + 1);
274279 return original(sql);
275280 };
test/door-ssh-fingerprint.test.ts +3 −4
@@ -1,4 +1,4 @@
1 /** The public home shows the ssh command, the host key fingerprint, once. */
1 /** The public home offers a stranger no ssh (b3c2780db), so no host key fingerprint either. */
22 import { afterAll, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
@@ -26,11 +26,10 @@ async function home(sshPort?: number, fingerprint?: string) {
2626 }
2727 }
2828
29 test("a stranger sees the fingerprint, once", async () => {
29 test("a stranger sees no fingerprint, even with the terminal on", async () => {
3030 const fp = "SHA256:abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
3131 const { text } = await home(2222, fp);
32 expect(text).toContain(`host key ${fp}`);
33 expect(text.split(`host key ${fp}`).length).toBe(2);
32 expect(text).not.toContain(fp);
3433 expect(text).not.toContain("ssh-keyscan");
3534 });
3635
test/forge-looks.test.ts +1
@@ -34,6 +34,7 @@ const NOT_A_PAGE: Record<string, string> = {
3434 "/agents": "/llms.txt drawn as a page for an assistant; no picture: the cap of 24 looks is spent, and test/agents-page.test.ts covers it",
3535 "/packs": "no picture: the cap of 24 looks is spent; the page is covered by test/packs.test.ts",
3636 "/fleet": "no picture: the cap of 24 looks is spent; the page is covered by test/fleet-table.test.ts",
37 "/home": "no picture: the cap of 24 looks is spent; the owner's new pipeline home, covered by test/home-flow.test.ts",
3738 "/robots.txt": "plain text for crawlers",
3839 "/openapi.json": "a redirect to the contract document",
3940 "/favicon.ico": "the tab icon, an image",
test/home-kpi-row.test.ts +8
@@ -124,6 +124,8 @@ describe("the builders figure from the database", () => {
124124 const db = new Database(":memory:");
125125 db.run("CREATE TABLE repo (autonomy TEXT, autonomy_slots INTEGER, default_branch TEXT, id TEXT)");
126126 db.run("CREATE TABLE run (id TEXT, kind TEXT, state TEXT, started_at TEXT, finished_at TEXT, serving_at TEXT, env TEXT, commit_oid TEXT, cost_usd REAL, created_at TEXT)");
127 // The index readKpis names (`INDEXED BY run_agent_cost`), as the migration makes it.
128 db.run("CREATE INDEX run_agent_cost ON run(created_at, cost_usd) WHERE kind = 'agent'");
127129 db.run("CREATE TABLE pull (carried INTEGER NOT NULL DEFAULT 0, merged_at TEXT, merged_oid TEXT, base_oid TEXT, base_branch TEXT, issue_id TEXT)");
128130 db.run("CREATE TABLE issue (id TEXT, repo_id TEXT, kind TEXT, state TEXT, created_at TEXT)");
129131 bugTables(db);
@@ -189,6 +191,8 @@ describe("the spend figure from the database", () => {
189191 const db = new Database(":memory:");
190192 db.run("CREATE TABLE repo (autonomy TEXT, autonomy_slots INTEGER, default_branch TEXT, id TEXT)");
191193 db.run("CREATE TABLE run (id TEXT, kind TEXT, state TEXT, started_at TEXT, finished_at TEXT, serving_at TEXT, env TEXT, commit_oid TEXT, cost_usd REAL, created_at TEXT)");
194 // The index readKpis names (`INDEXED BY run_agent_cost`), as the migration makes it.
195 db.run("CREATE INDEX run_agent_cost ON run(created_at, cost_usd) WHERE kind = 'agent'");
192196 db.run("CREATE TABLE pull (carried INTEGER NOT NULL DEFAULT 0, merged_at TEXT, merged_oid TEXT, base_oid TEXT, base_branch TEXT, issue_id TEXT)");
193197 db.run("CREATE TABLE issue (id TEXT, repo_id TEXT, kind TEXT, state TEXT, created_at TEXT)");
194198 bugTables(db);
@@ -242,6 +246,8 @@ describe("home kpi row: the last off-box backup", () => {
242246 const db = new Database(":memory:");
243247 db.run("CREATE TABLE repo (autonomy TEXT, autonomy_slots INTEGER, default_branch TEXT, id TEXT)");
244248 db.run("CREATE TABLE run (id TEXT, kind TEXT, state TEXT, started_at TEXT, finished_at TEXT, serving_at TEXT, env TEXT, commit_oid TEXT, cost_usd REAL, created_at TEXT)");
249 // The index readKpis names (`INDEXED BY run_agent_cost`), as the migration makes it.
250 db.run("CREATE INDEX run_agent_cost ON run(created_at, cost_usd) WHERE kind = 'agent'");
245251 db.run("CREATE TABLE pull (carried INTEGER NOT NULL DEFAULT 0, merged_at TEXT, merged_oid TEXT, base_oid TEXT, base_branch TEXT, issue_id TEXT)");
246252 db.run("CREATE TABLE issue (id TEXT, repo_id TEXT, kind TEXT, state TEXT, created_at TEXT)");
247253 bugTables(db);
@@ -431,6 +437,8 @@ describe("the forge ceiling hit (#5798)", () => {
431437 const db = new Database(":memory:");
432438 db.run("CREATE TABLE repo (autonomy TEXT, autonomy_slots INTEGER, default_branch TEXT, id TEXT)");
433439 db.run("CREATE TABLE run (id TEXT, kind TEXT, state TEXT, started_at TEXT, finished_at TEXT, serving_at TEXT, env TEXT, commit_oid TEXT, cost_usd REAL, created_at TEXT)");
440 // The index readKpis names (`INDEXED BY run_agent_cost`), as the migration makes it.
441 db.run("CREATE INDEX run_agent_cost ON run(created_at, cost_usd) WHERE kind = 'agent'");
434442 db.run("CREATE TABLE pull (carried INTEGER NOT NULL DEFAULT 0, merged_at TEXT, merged_oid TEXT, base_oid TEXT, base_branch TEXT, issue_id TEXT)");
435443 db.run("CREATE TABLE issue (id TEXT, repo_id TEXT, kind TEXT, state TEXT, created_at TEXT)");
436444 bugTables(db);
test/retention-deploys.test.ts +8 −5
@@ -244,24 +244,27 @@ describe("deploy_pull retention", () => {
244244 first = tick(now);
245245 });
246246 expect(first!.more).toBe(true);
247 expect(first!.deleted).toBeGreaterThan(1_900);
247 // A slice reads 500 rows (31955846d): nearly all of the first are past the rule.
248 expect(first!.deleted).toBeGreaterThan(450);
248249 expectWork(cost, { max: 6 });
249250 // Mid-pass a slice waits its pace: the same instant runs nothing.
250251 expect(tick(now)).toBeUndefined();
251252 const at = (s: number) => new Date(now.getTime() + s * 1000);
252253 let total = first!.deleted;
253254 let slices = 1;
255 let end = 0;
254256 for (let s = 11; ; s += 11) {
255257 const r = tick(at(s))!;
256258 total += r.deleted;
257259 slices++;
260 end = s;
258261 if (!r.more) break;
259262 }
260263 expect(total).toBe(7_000);
261 expect(slices).toBe(4);
262 // The pass is over: the next one waits for the hour.
263 expect(tick(at(60))).toBeUndefined();
264 expect(tick(new Date(now.getTime() + 62 * 60_000))).toMatchObject({ deleted: 0, more: false });
264 expect(slices).toBe(15);
265 // The pass is over: the next one waits for the hour from its last slice.
266 expect(tick(at(end + 60))).toBeUndefined();
267 expect(tick(at(end + 61 * 60))).toMatchObject({ deleted: 0, more: false });
265268 });
266269
267270 test("the keep window is the setting's: deploys past it go, deploys inside it stay, each slice bounded", async () => {
test/stall-scans.test.ts +3 −1
@@ -102,7 +102,9 @@ test("build yield reads event through its index, never a scan of event or a run
102102 const plan = planOf(big, BUILD_YIELD_SQL, [ago(1440), ago(0), 0]);
103103 expect(plan.filter((d) => /SCAN /.test(d))).toEqual([]);
104104 expect(plan.some((d) => d.includes("event_repo_kind_number_at"))).toBe(true);
105 expect(plan.some((d) => /SEARCH x USING INDEX run_kind_finished/.test(d))).toBe(true);
105 // Either index that searches finished runs by kind and range keeps it a search, never a run per
106 // run.
107 expect(plan.some((d) => /SEARCH x USING (COVERING )?INDEX run_(kind_finished|finished_cov) \(kind=\? AND finished_at/.test(d))).toBe(true);
106108 });
107109
108110 test("build yield on thousands of runs answers within the bound and counts them all", () => {
test/surfaces-adversarial.test.ts +8 −4
@@ -309,7 +309,8 @@ describe("surfaces adversarial: web", () => {
309309 // ---- 5. N+1 ----
310310
311311 test("N+1: /apps does not cost more queries as private, org-visible apps grow", async () => {
312 // Invariant: a listing of private org apps costs the same statements at 30 apps as at 5. Users here are passwordless with a session row (no argon2); 2 measured runs.
312 // Invariant: a listing of private org apps costs the same statements at 30 apps as at 5. Users
313 // here are passwordless with a session row (no argon2); 2 measured runs.
313314 const org = createOrg(app.db, "acme-apps", aliceUser().id);
314315 expect(org.ok).toBe(true);
315316 if (!org.ok) return;
@@ -359,7 +360,8 @@ describe("surfaces adversarial: web", () => {
359360 });
360361
361362 test("N+1: the dashboard's Apps and On-you cards stay flat with 30 apps and 30 assigned issues", async () => {
362 // Invariant: the dashboard cards cost the same statements at 30 apps and 30 assigned issues as at 5. Users here are passwordless with a session row (no argon2); 2 measured runs.
363 // Invariant: the dashboard cards cost the same statements at 30 apps and 30 assigned issues as
364 // at 5. Users here are passwordless with a session row (no argon2); 2 measured runs.
363365 const owner = await createUser(app.db, { origin: "seed", trusted: true,
364366 username: "dashowner",
365367 email: "[email protected]",
@@ -434,7 +436,8 @@ describe("surfaces adversarial: web", () => {
434436 // `writableRepoIds` query (`REPO_WRITABLE`, the SQL twin of `canWrite`),
435437 // so the count must not move with the number of distinct repositories.
436438 test("N+1: needsYouCard does not cost more as agent pulls span more distinct repos", async () => {
437 // Invariant: needsYouCard costs the same statements at 30 distinct repos as at 5. Users here are passwordless with a session row (no argon2); 2 measured runs.
439 // Invariant: needsYouCard costs the same statements at 30 distinct repos as at 5. Users here
440 // are passwordless with a session row (no argon2); 2 measured runs.
438441 const owner = await createUser(app.db, { origin: "seed", trusted: true,
439442 username: "needsowner",
440443 email: "[email protected]",
@@ -521,7 +524,8 @@ describe("surfaces adversarial: web", () => {
521524 });
522525
523526 test("N+1: a pull's crew activity does not cost more as its agent runs grow", async () => {
524 // Invariant: a pull page costs the same statements however many agent runs it has. Users here are passwordless with a session row (no argon2); 2 measured runs.
527 // Invariant: a pull page costs the same statements however many agent runs it has. Users here
528 // are passwordless with a session row (no argon2); 2 measured runs.
525529 const agent = await createAgent(app, aliceUser(), {
526530 username: "crewn1bot",
527531 });
test/test-budget-run.test.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * The test time budget (`scripts/test-budget.ts`, #12087) from fixture
3 * times, with no real test run: what is over 20 s a file or 2 s a test,
4 * what `SLOW` sets aside, and where a breach is red.
5 */
6
7 import { describe, expect, test } from "bun:test";
8 import {
9 breaches,
10 budgetBinds,
11 budgetLines,
12 formatTestTable,
13 parseJunit,
14 parseTestTable,
15 refreshTestTable,
16 type SlowEntry,
17 } from "../scripts/test-budget.ts";
18 import { SLOW } from "../scripts/gate.ts";
19 import { existsSync } from "node:fs";
20
21 const quick = {
22 files: [
23 { file: "test/a.test.ts", seconds: 4 },
24 { file: "test/b.test.ts", seconds: 19.9 },
25 ],
26 tests: [
27 { file: "test/a.test.ts", test: "one", seconds: 0.5 },
28 { file: "test/a.test.ts", test: "two", seconds: 2 },
29 { file: "test/b.test.ts", test: "group > three", seconds: 1.5 },
30 ],
31 };
32
33 describe("breaches", () => {
34 test("a run under the budget has nothing over it", () => {
35 const budget = breaches(quick, []);
36 expect(budget.over).toEqual([]);
37 expect(budget.aside).toEqual([]);
38 expect(budgetLines(budget)).toContain("over the budget: 0, SLOW aside: 0");
39 });
40
41 test("a file over 20 s and a test over 2 s are each named", () => {
42 const budget = breaches(
43 {
44 files: [...quick.files, { file: "./test/c.test.ts", seconds: 21 }],
45 tests: [...quick.tests, { file: "test/c.test.ts", test: "slow one", seconds: 2.5 }],
46 },
47 [],
48 );
49 expect(budget.over).toEqual([
50 { kind: "file", file: "test/c.test.ts", seconds: 21 },
51 { kind: "test", file: "test/c.test.ts", test: "slow one", seconds: 2.5 },
52 ]);
53 const lines = budgetLines(budget);
54 expect(lines).toContain("over the budget: 2, SLOW aside: 0");
55 expect(lines).toContain(" test/c.test.ts: 21.0s (a file over 20s)");
56 expect(lines).toContain(" test/c.test.ts > slow one: 2.50s (a test over 2s)");
57 });
58
59 test("a file SLOW names is set aside, under its issue, not counted", () => {
60 const slow: SlowEntry[] = [{ file: "test/c.test.ts", reason: "spawns the forge", issue: 1242 }];
61 const budget = breaches(
62 {
63 files: [{ file: "test/c.test.ts", seconds: 48 }],
64 tests: [{ file: "test/c.test.ts", test: "boots", seconds: 9 }],
65 },
66 slow,
67 );
68 expect(budget.over).toEqual([]);
69 expect(budget.aside.map((b) => b.issue)).toEqual([1242, 1242]);
70 const lines = budgetLines(budget);
71 expect(lines).toContain("over the budget: 0, SLOW aside: 2");
72 expect(lines).toContain(" aside: test/c.test.ts: 48.0s (a file over 20s) (SLOW, #1242)");
73 });
74
75 test("the five slowest tests and their share of the run", () => {
76 const tests = [1, 2, 3, 4, 5, 6, 9].map((seconds) => ({ file: "test/a.test.ts", test: `t${seconds}`, seconds: seconds / 10 }));
77 const budget = breaches({ files: [], tests }, []);
78 expect(budget.slowest.map((t) => t.test)).toEqual(["t9", "t6", "t5", "t4", "t3"]);
79 expect(budget.slowestSeconds).toBeCloseTo(2.7);
80 expect(budget.totalSeconds).toBeCloseTo(3);
81 expect(budgetLines(budget)[0]).toBe("Slowest 5 tests: 2.70s, 90% of 3.0s in tests");
82 });
83 });
84
85 describe("budgetBinds", () => {
86 test("a breach is red on the fast tier only for a test file the pull changed", () => {
87 expect(budgetBinds("fast", ["test/c.test.ts", "src/x.ts"], "./test/c.test.ts")).toBe(true);
88 expect(budgetBinds("fast", ["src/x.ts"], "test/c.test.ts")).toBe(false);
89 });
90
91 test("a full-tier breach is reported, not red", () => {
92 expect(budgetBinds("full", ["test/c.test.ts"], "test/c.test.ts")).toBe(false);
93 });
94 });
95
96 describe("parseJunit", () => {
97 test("reads each test's file, describe path and seconds from Bun's report", () => {
98 const xml = `<?xml version="1.0" encoding="UTF-8"?>
99 <testsuites name="bun test" tests="3" time="0.05">
100 <testsuite name="test/x.test.ts" file="test/x.test.ts" tests="3" time="0">
101 <testsuite name="grp" file="test/x.test.ts" line="2" tests="2" time="0.03">
102 <testcase name="a &lt;b&gt; &amp; &quot;c&quot;" classname="grp" time="0.031407" file="test/x.test.ts" line="2" />
103 <testcase name="bad" classname="grp" time="2.5" file="test/x.test.ts" line="3">
104 <failure type="AssertionError" />
105 </testcase>
106 </testsuite>
107 <testcase name="top" classname="" time="0.000068" file="test/x.test.ts" line="5" />
108 <testcase name="no time" classname="" file="test/x.test.ts" line="6" />
109 </testsuite>
110 </testsuites>`;
111 expect(parseJunit(xml)).toEqual([
112 { file: "test/x.test.ts", test: 'grp > a <b> & "c"', seconds: 0.031407 },
113 { file: "test/x.test.ts", test: "grp > bad", seconds: 2.5 },
114 { file: "test/x.test.ts", test: "top", seconds: 0.000068 },
115 ]);
116 });
117 });
118
119 describe("the per-test table", () => {
120 test("a run replaces the files it timed, keeps the rest, forgets the gone", () => {
121 const old = new Map([
122 ["test/a.test.ts", new Map([["stale", 9]])],
123 ["test/b.test.ts", new Map([["kept", 1]])],
124 ["test/gone.test.ts", new Map([["x", 1]])],
125 ]);
126 const table = refreshTestTable(old, [{ file: "test/a.test.ts", test: "fresh", seconds: 0.12345 }], (f) => f !== "test/gone.test.ts");
127 const text = formatTestTable(table);
128 expect(JSON.parse(text)).toEqual({ "test/a.test.ts": { fresh: 0.123 }, "test/b.test.ts": { kept: 1 } });
129 const back = parseTestTable(text);
130 expect(back.ok && back.value.get("test/b.test.ts")?.get("kept")).toBe(1);
131 expect(parseTestTable('{"test/a.test.ts": {"t": "slow"}}').ok).toBe(false);
132 });
133 });
134
135 test("every file SLOW sets aside exists and names an issue and a reason", () => {
136 for (const entry of SLOW) {
137 expect(existsSync(entry.file)).toBe(true);
138 expect(entry.issue).toBeGreaterThan(0);
139 expect(entry.reason.trim()).not.toBe("");
140 }
141 });
test/week-burn.test.ts deleted −64
@@ -1,64 +0,0 @@
1 /** The burn is the change in the measured percent over time (#8910), replayed on the readings of 2026-11-02. */
2 import { Database } from "bun:sqlite";
3 import { describe, expect, test } from "bun:test";
4 import migration from "../src/core/migrations/20261103140000-week-readings.ts";
5 import { burnFrom, noteReading, readingsSince, type Reading } from "../src/crew/week_burn.ts";
6
7 const WEEK_MS = 7 * 86_400_000;
8 const migrationSql = (): string => migration;
9 const at = (hhmm: string): number => Date.parse(`2026-11-02T${hhmm}:00Z`);
10
11 /** What the `usage` tool read: 54% at 16:33Z, 46% at 19:25Z, then 45% from 20:05Z to 21:15Z every five minutes. */
12 const readings: Reading[] = [{ at: at("16:33"), freePct: 54 }, { at: at("19:25"), freePct: 46 }];
13 for (let t = at("20:05"); t <= at("21:15"); t += 300_000) readings.push({ at: t, freePct: 45 });
14
15 test("at 21:15Z the meter has barely moved in the hour, so the burn is nowhere near 1.4% an hour", () => {
16 const burn = burnFrom(readings, at("21:15"), 1)!;
17 expect(burn).toBeLessThan(0.2);
18 expect(burn).toBeGreaterThanOrEqual(0);
19 });
20
21 test("at 19:30Z the burn is the fall since 16:33Z, about 2.7 points an hour", () => {
22 expect(burnFrom(readings, at("19:30"), 1)!).toBeCloseTo(8 / (172 / 60), 1);
23 });
24
25 test("too few readings say so: none, one, or two a minute apart", () => {
26 expect(burnFrom([], at("21:15"), 1)).toBeNull();
27 expect(burnFrom([readings[0]!], at("21:15"), 1)).toBeNull();
28 expect(burnFrom([{ at: at("21:00"), freePct: 45 }, { at: at("21:01"), freePct: 44 }], at("21:02"), 1)).toBeNull();
29 });
30
31 test("a rise, a reset, is no burn", () => {
32 expect(burnFrom([{ at: at("20:00"), freePct: 10 }, { at: at("21:00"), freePct: 100 }], at("21:00"), 1)).toBe(0);
33 });
34
35 describe("the readings store", () => {
36 const db = new Database(":memory:");
37 db.exec(migrationSql());
38 const T = at("12:00");
39
40 test("a reading within a minute of the last is one reading; a minute on is a new one", () => {
41 noteReading(db, "s", T, 50, WEEK_MS);
42 noteReading(db, "s", T + 59_000, 49, WEEK_MS);
43 expect(readingsSince(db, "s", 0)).toEqual([{ at: T, freePct: 50 }]);
44 noteReading(db, "s", T + 60_000, 49, WEEK_MS);
45 expect(readingsSince(db, "s", 0).map((r) => r.freePct)).toEqual([50, 49]);
46 });
47
48 test("scopes are apart, and since leaves out the older", () => {
49 noteReading(db, "other", T, 10, WEEK_MS);
50 expect(readingsSince(db, "other", 0)).toEqual([{ at: T, freePct: 10 }]);
51 expect(readingsSince(db, "s", T + 30_000)).toEqual([{ at: T + 60_000, freePct: 49 }]);
52 });
53
54 test("what is older than a week is forgotten on the next reading", () => {
55 noteReading(db, "s", T + WEEK_MS + 120_000, 40, WEEK_MS);
56 expect(readingsSince(db, "s", 0)).toEqual([{ at: T + WEEK_MS + 120_000, freePct: 40 }]);
57 });
58
59 test("stored readings give the burn", () => {
60 noteReading(db, "b", T, 60, WEEK_MS);
61 noteReading(db, "b", T + 3_600_000, 57, WEEK_MS);
62 expect(burnFrom(readingsSince(db, "b", 0), T + 3_600_000, 1)).toBeCloseTo(3, 5);
63 });
64 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs