Public: anyone can read this; the crew can change it.
What the tokens bought, by pillar and by milestone: a limb trimmed on evidence #1232
torque/forge:torque/1067-what-the-tokens-bought-by-pillar-and-by → main 4 commits fork 4 threads · 4 unresolved
README.md +5
| @@ -338,6 +338,11 @@ Crew shows **Unsandboxed** with it, and every agent run's page says | ||
| 338 | 338 | "Sandboxed" or "Unsandboxed" from what it was actually started with (runs |
| 339 | 339 | from before this record say nothing). |
| 340 | 340 | |
| 341 | **What the tokens bought.** `/board/returns` (and `GET /api/v1/returns?days=7&repo=owner/name`, | |
| 342 | MCP `returns`) sets the crew's dollars against the changes they landed, by | |
| 343 | state, by issue and **By pillar**; a milestone's page has **What it cost**, | |
| 344 | its limb's spend since it began. Owner facts only: a reader sees neither. | |
| 345 | ||
| 341 | 346 | `docs/APPS.md` is the contract: the vocabulary, and the rules that are |
| 342 | 347 | mechanical rather than advisory. |
| 343 | 348 |
scripts/gate.ts +3 −6
| @@ -45,6 +45,9 @@ export const GATE: readonly string[] = [ | ||
| 45 | 45 | "test/refresh-meta.test.ts", |
| 46 | 46 | "test/restore-card.test.ts", |
| 47 | 47 | "test/returns.test.ts", |
| 48 | "test/returns-limb.test.ts", | |
| 49 | "test/returns-pillars.test.ts", | |
| 50 | "test/attach-look.test.ts", | |
| 48 | 51 | "test/review-route.test.ts", |
| 49 | 52 | "test/review-lines.test.ts", |
| 50 | 53 | "test/review-gate.test.ts", |
| @@ -256,12 +259,6 @@ export const EXCLUDED: readonly Exclusion[] = [ | ||
| 256 | 259 | reason: "not yet admitted", |
| 257 | 260 | issue: 261, |
| 258 | 261 | }, |
| 259 | { | |
| 260 | file: "test/plan-route.test.ts", | |
| 261 | reason: | |
| 262 | "waits up to 30 s on a fake planner run under the crew sandbox, over the 1 s budget; red where the sandbox cannot nest", | |
| 263 | issue: 261, | |
| 264 | }, | |
| 265 | 262 | { file: "test/parity.test.ts", reason: "not yet admitted", issue: 261 }, |
| 266 | 263 | { file: "test/policy.test.ts", reason: "not yet admitted", issue: 261 }, |
| 267 | 264 | { file: "test/probe.test.ts", reason: "not yet admitted", issue: 261 }, |
src/actions/returns.ts +51 −3
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | import type { App } from "../app.ts"; |
| 9 | 9 | import { isCrew } from "../core/agents.ts"; |
| 10 | import { getIssue } from "../core/issues.ts"; | |
| 10 | import { getIssue, type Issue } from "../core/issues.ts"; | |
| 11 | 11 | import { |
| 12 | 12 | outsideSpendIn, |
| 13 | 13 | recordOutsideSpend, |
| @@ -15,13 +15,24 @@ import { | ||
| 15 | 15 | type OutsideTotal, |
| 16 | 16 | } from "../core/outside_spend.ts"; |
| 17 | 17 | import { |
| 18 | pillarNames, | |
| 19 | pillarsOf, | |
| 20 | reposWithUmbrellas, | |
| 21 | servedBy, | |
| 22 | } from "../core/pillars.ts"; | |
| 23 | import { | |
| 24 | canSeeOwnerFacts, | |
| 18 | 25 | canWrite, |
| 19 | 26 | getRepo, |
| 20 | 27 | listReposVisibleTo, |
| 21 | 28 | ownerFactRepoIds, |
| 22 | 29 | type Repo, |
| 23 | 30 | } from "../core/repos.ts"; |
| 24 | import { tokenReturns, type Returns } from "../core/returns.ts"; | |
| 31 | import { | |
| 32 | tokenReturns, | |
| 33 | type PillarMap, | |
| 34 | type Returns, | |
| 35 | } from "../core/returns.ts"; | |
| 25 | 36 | import type { User } from "../core/users.ts"; |
| 26 | 37 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 27 | 38 | |
| @@ -37,6 +48,43 @@ export function returnsRepos(app: App, viewer: User): Repo[] { | ||
| 37 | 48 | return visible.filter((r) => facts.has(r.id)); |
| 38 | 49 | } |
| 39 | 50 | |
| 51 | /** Each repository's pillars, as `tokenReturns` groups by them; one with none is absent. */ | |
| 52 | function pillarMaps(app: App, repos: readonly Repo[]): Map<string, PillarMap> { | |
| 53 | const out = new Map<string, PillarMap>(); | |
| 54 | const some = reposWithUmbrellas( | |
| 55 | app.db, | |
| 56 | repos.map((r) => r.id), | |
| 57 | ); | |
| 58 | for (const repo of repos) { | |
| 59 | if (!some.has(repo.id)) continue; | |
| 60 | const set = pillarsOf(app.db, repo); | |
| 61 | if (set.pillars.length === 0) continue; | |
| 62 | out.set(repo.id, { names: pillarNames(set), of: servedBy(app.db, set) }); | |
| 63 | } | |
| 64 | return out; | |
| 65 | } | |
| 66 | ||
| 67 | /** | |
| 68 | * What a limb has cost and landed since it began — the runs whose work was | |
| 69 | * for an issue in it — for a viewer who holds the repository's owner facts; | |
| 70 | * nothing for anyone else. `issues` is the limb (`Plan.limb`). | |
| 71 | */ | |
| 72 | export function limbReturns( | |
| 73 | app: App, | |
| 74 | viewer: User | undefined, | |
| 75 | repo: Repo, | |
| 76 | issues: readonly Issue[], | |
| 77 | now = new Date(), | |
| 78 | ): Returns | undefined { | |
| 79 | if (!canSeeOwnerFacts(app.db, repo, viewer)) return undefined; | |
| 80 | return tokenReturns( | |
| 81 | app.db, | |
| 82 | [repo.id], | |
| 83 | { since: new Date(0).toISOString(), until: now.toISOString() }, | |
| 84 | { within: new Set(issues.map((i) => i.id)) }, | |
| 85 | ); | |
| 86 | } | |
| 87 | ||
| 40 | 88 | export function readReturns( |
| 41 | 89 | app: App, |
| 42 | 90 | viewer: User | undefined, |
| @@ -63,7 +111,7 @@ export function readReturns( | ||
| 63 | 111 | }; |
| 64 | 112 | const ids = repos.map((r) => r.id); |
| 65 | 113 | return ok({ |
| 66 | ...tokenReturns(app.db, ids, window), | |
| 114 | ...tokenReturns(app.db, ids, window, { pillars: pillarMaps(app, repos) }), | |
| 67 | 115 | repos: repos.map((r) => `${r.ownerName}/${r.name}`), |
| 68 | 116 | // Apart, never added in: a claim from a session the forge did not run. |
| 69 | 117 | outside: outsideSpendIn(app.db, ids, window.since, window.until), |
src/core/returns.ts +392 −37
| @@ -10,6 +10,18 @@ | ||
| 10 | 10 | * close reason, which most closed issues do not carry. Dollars are the |
| 11 | 11 | * provider's list price as each run reported it (`run.cost_usd`). |
| 12 | 12 | * |
| 13 | * By pillar (#1067): a run serves the pillar of the issue it worked for — | |
| 14 | * its own issue, else the first issue its change closes that serves one | |
| 15 | * (`core/pillars.ts`, read by the caller and handed in as plain data). Every | |
| 16 | * run falls in exactly one row, so the rows add up to the whole. | |
| 17 | * | |
| 18 | * Narrowed to a limb (`within`): only the runs whose work was for one of | |
| 19 | * those issues, so a milestone can say what its limb cost and landed. Those | |
| 20 | * are read by index — the limb's issues, the pulls that close them, the runs | |
| 21 | * on either or on their branches — never by scanning the history; and each | |
| 22 | * run counts toward the limb issue it was for, so the costliest are the | |
| 23 | * limb's own. | |
| 24 | * | |
| 13 | 25 | * Pure data over the run, issue and pull tables: who may read it is the |
| 14 | 26 | * caller's to decide (owner facts only; `actions/returns.ts`). |
| 15 | 27 | */ |
| @@ -42,13 +54,50 @@ export interface CostlyIssue extends Money { | ||
| 42 | 54 | readonly outcome: Outcome; |
| 43 | 55 | } |
| 44 | 56 | |
| 57 | /** One repository's pillars as `tokenReturns` groups by them (`pillars.ts`). */ | |
| 58 | export interface PillarMap { | |
| 59 | /** Every name an issue can be filed under, in order (`pillarNames`). */ | |
| 60 | readonly names: readonly string[]; | |
| 61 | /** What each issue serves, by issue id (`servedBy`). */ | |
| 62 | readonly of: ReadonlyMap<string, string>; | |
| 63 | } | |
| 64 | ||
| 65 | /** What one pillar of one repository spent and landed in the window. */ | |
| 66 | export interface PillarReturns { | |
| 67 | readonly repoId: string; | |
| 68 | /** The pillar's name; null for work that serves none. */ | |
| 69 | readonly pillar: string | null; | |
| 70 | readonly spent: Money; | |
| 71 | /** Runs whose change merged. */ | |
| 72 | readonly onLanded: Money; | |
| 73 | /** Distinct changes those runs merged. */ | |
| 74 | readonly landed: number; | |
| 75 | /** | |
| 76 | * All the pillar's dollars over the changes it landed — waste included, | |
| 77 | * so it is what one landed change of this pillar really cost; null when | |
| 78 | * it landed none. | |
| 79 | */ | |
| 80 | readonly perLanded: number | null; | |
| 81 | /** Work closed without a merge. */ | |
| 82 | readonly closed: Money; | |
| 83 | /** Work with nothing merged yet. */ | |
| 84 | readonly open: Money; | |
| 85 | } | |
| 86 | ||
| 87 | export interface ReturnsOptions { | |
| 88 | /** Group by pillar: each repository's pillars, by repository id. A repository absent has none. */ | |
| 89 | readonly pillars?: ReadonlyMap<string, PillarMap>; | |
| 90 | /** Only the runs whose work was for one of these issue ids: a limb. */ | |
| 91 | readonly within?: ReadonlySet<string>; | |
| 92 | } | |
| 93 | ||
| 45 | 94 | export interface Returns { |
| 46 | 95 | readonly window: ReturnsWindow; |
| 47 | 96 | /** Every agent run in the window. */ |
| 48 | 97 | readonly spent: Money; |
| 49 | 98 | /** The same, by the run's own state. */ |
| 50 | 99 | readonly byState: Readonly<Record<string, Money>>; |
| 51 | /** Pulls merged in the window. */ | |
| 100 | /** Pulls merged in the window; narrowed to a limb, the changes its runs merged. */ | |
| 52 | 101 | readonly landed: number; |
| 53 | 102 | /** Runs whose change merged, and what a landed change cost: total and median over the changes. */ |
| 54 | 103 | readonly onLanded: Money & { |
| @@ -74,6 +123,12 @@ export interface Returns { | ||
| 74 | 123 | }; |
| 75 | 124 | /** The issues that cost the most, with what came of each. */ |
| 76 | 125 | readonly costliest: readonly CostlyIssue[]; |
| 126 | /** | |
| 127 | * The same split by pillar, repository by repository: every pillar in | |
| 128 | * order, cost or not, then the work that serves none where there was | |
| 129 | * any. Empty unless pillars were asked for. | |
| 130 | */ | |
| 131 | readonly byPillar: readonly PillarReturns[]; | |
| 77 | 132 | } |
| 78 | 133 | |
| 79 | 134 | interface RunRow { |
| @@ -151,60 +206,239 @@ const money = (m: { runs: number; usd: number } | undefined): Money => ({ | ||
| 151 | 206 | const marks = (n: number, from = 1): string => |
| 152 | 207 | Array.from({ length: n }, (_, i) => `?${i + from}`).join(","); |
| 153 | 208 | |
| 209 | const RUN_COLUMNS = | |
| 210 | "id, repo_id, issue_id, branch, state, summary, cost_usd, started_at, finished_at"; | |
| 211 | ||
| 212 | /** A list in pieces SQLite takes as one statement's placeholders. */ | |
| 213 | const batches = <T>(list: readonly T[], size = 400): T[][] => | |
| 214 | Array.from({ length: Math.ceil(list.length / size) }, (_, i) => | |
| 215 | list.slice(i * size, (i + 1) * size), | |
| 216 | ); | |
| 217 | ||
| 218 | /** | |
| 219 | * The runs in the window that can have worked for a limb, read by index and | |
| 220 | * never by scanning the history: a run on a limb issue; a run on a pull that | |
| 221 | * says it closes one, or on that pull's head branch; a run on any other issue | |
| 222 | * such a pull closes (its change is the limb's). A superset — `tokenReturns` | |
| 223 | * still keeps only the runs whose work was for the limb. | |
| 224 | */ | |
| 225 | function limbRuns( | |
| 226 | db: Database, | |
| 227 | repoIds: readonly string[], | |
| 228 | window: ReturnsWindow, | |
| 229 | limb: readonly IssueRow[], | |
| 230 | theirs: readonly PullRow[], | |
| 231 | closesOf: ReadonlyMap<string, readonly number[]>, | |
| 232 | idsByNumber: (wanted: Map<string, Set<number>>) => Map<string, string>, | |
| 233 | ): RunRow[] { | |
| 234 | if (limb.length === 0) return []; | |
| 235 | const keys = new Set(limb.map((i) => `${i.repo_id}#${i.number}`)); | |
| 236 | const alsoClosed = new Map<string, Set<number>>(); | |
| 237 | for (const p of theirs) | |
| 238 | for (const k of closesOf.get(p.id)!) | |
| 239 | if (!keys.has(`${p.repo_id}#${k}`)) | |
| 240 | alsoClosed.set(p.repo_id, (alsoClosed.get(p.repo_id) ?? new Set()).add(k)); | |
| 241 | const issueIds = [ | |
| 242 | ...new Set([ | |
| 243 | ...limb.map((i) => i.id), | |
| 244 | ...theirs.map((p) => p.id), | |
| 245 | ...idsByNumber(alsoClosed).values(), | |
| 246 | ]), | |
| 247 | ]; | |
| 248 | const repos = new Set(repoIds); | |
| 249 | const out = new Map<string, RunRow>(); | |
| 250 | // By issue alone, so SQLite takes `run_issue` and not the repository's | |
| 251 | // whole history through `run_repo`; the repository is checked here. | |
| 252 | for (const batch of batches(issueIds)) | |
| 253 | for (const r of db | |
| 254 | .query<RunRow, string[]>( | |
| 255 | `SELECT ${RUN_COLUMNS} FROM run WHERE issue_id IN (${marks(batch.length)}) | |
| 256 | AND kind = 'agent' AND created_at >= ?${batch.length + 1} AND created_at < ?${batch.length + 2}`, | |
| 257 | ) | |
| 258 | .all(...batch, window.since, window.until)) | |
| 259 | if (repos.has(r.repo_id)) out.set(r.id, r); | |
| 260 | const branches = new Map<string, Set<string>>(); | |
| 261 | for (const p of theirs) | |
| 262 | if (p.head_branch !== "") | |
| 263 | branches.set(p.repo_id, (branches.get(p.repo_id) ?? new Set()).add(p.head_branch)); | |
| 264 | for (const [repoId, names] of branches) | |
| 265 | for (const batch of batches([...names])) | |
| 266 | for (const r of db | |
| 267 | .query<RunRow, string[]>( | |
| 268 | `SELECT ${RUN_COLUMNS} FROM run WHERE repo_id = ?1 AND branch <> '' AND kind = 'agent' | |
| 269 | AND branch IN (${marks(batch.length, 2)}) | |
| 270 | AND created_at >= ?${batch.length + 2} AND created_at < ?${batch.length + 3}`, | |
| 271 | ) | |
| 272 | .all(repoId, ...batch, window.since, window.until)) | |
| 273 | out.set(r.id, r); | |
| 274 | return [...out.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); | |
| 275 | } | |
| 276 | ||
| 154 | 277 | /** What the tokens bought in these repositories over the window. */ |
| 155 | 278 | export function tokenReturns( |
| 156 | 279 | db: Database, |
| 157 | 280 | repoIds: readonly string[], |
| 158 | 281 | window: ReturnsWindow, |
| 282 | options: ReturnsOptions = {}, | |
| 159 | 283 | ): Returns { |
| 160 | 284 | const n = repoIds.length; |
| 161 | const runs = | |
| 285 | const within = options.within; | |
| 286 | const repoSet = new Set(repoIds); | |
| 287 | const issueRows = (ids: readonly string[]): IssueRow[] => | |
| 288 | batches(ids).flatMap((batch) => | |
| 289 | db | |
| 290 | .query<IssueRow, string[]>( | |
| 291 | `SELECT id, repo_id, number, title, kind, state FROM issue WHERE id IN (${marks(batch.length)})`, | |
| 292 | ) | |
| 293 | .all(...batch), | |
| 294 | ); | |
| 295 | /** Issue ids by `repo#number`, for these numbers in each repository. */ | |
| 296 | const idsByNumber = (wanted: Map<string, Set<number>>): Map<string, string> => { | |
| 297 | const out = new Map<string, string>(); | |
| 298 | for (const [repoId, numbers] of wanted) | |
| 299 | for (const batch of batches([...numbers])) | |
| 300 | for (const row of db | |
| 301 | .query<{ id: string; number: number }, (string | number)[]>( | |
| 302 | `SELECT id, number FROM issue WHERE repo_id = ?1 AND kind = 'issue' | |
| 303 | AND number IN (${marks(batch.length, 2)})`, | |
| 304 | ) | |
| 305 | .all(repoId, ...batch)) | |
| 306 | out.set(`${repoId}#${row.number}`, row.id); | |
| 307 | return out; | |
| 308 | }; | |
| 309 | // The issue numbers each pull says it closes, read from its body once. | |
| 310 | const closesOf = new Map<string, number[]>(); | |
| 311 | const readPulls = (where: string, params: readonly string[]): PullRow[] => { | |
| 312 | const rows = db | |
| 313 | .query<PullRow, string[]>( | |
outdated
This re-parses every candidate pull's body once per run (and once more in |
||
| 314 | `SELECT issue.id, issue.repo_id, issue.number, issue.body, issue.state, | |
| 315 | pull.head_branch, pull.merged_at | |
| 316 | FROM issue JOIN pull ON pull.issue_id = issue.id WHERE ${where}`, | |
| 317 | ) | |
| 318 | .all(...params); | |
| 319 | for (const p of rows) | |
| 320 | if (!closesOf.has(p.id)) closesOf.set(p.id, closesFromBody(p.body)); | |
| 321 | return rows; | |
| 322 | }; | |
| 323 | /** | |
| 324 | * The pulls that may close one of these issue numbers: every pull whose | |
| 325 | * body says `#N`, or `#0…` for one written with leading zeros (a | |
| 326 | * superset; `closesOf` says which do close it). | |
| 327 | */ | |
| 328 | const pullsNaming = (wanted: Map<string, Set<number>>): PullRow[] => | |
outdated
A run on an issue outside the limb counts when its change closes a limb issue. That is fine for the totals, but the run's own issue then gets into |
||
| 329 | [...wanted].flatMap(([repoId, numbers]) => | |
| 330 | batches([...numbers].map((k) => `#${k}`)).flatMap((batch) => | |
| 331 | readPulls( | |
| 332 | `issue.repo_id = ?1 AND (instr(issue.body, '#0') > 0 | |
| 333 | OR ${batch.map((_, i) => `instr(issue.body, ?${i + 2}) > 0`).join(" OR ")})`, | |
| 334 | [repoId, ...batch], | |
| 335 | ), | |
| 336 | ), | |
| 337 | ); | |
| 338 | const numbersOf = (rows: readonly { repo_id: string; number: number }[]) => { | |
| 339 | const out = new Map<string, Set<number>>(); | |
| 340 | for (const r of rows) | |
| 341 | out.set(r.repo_id, (out.get(r.repo_id) ?? new Set()).add(r.number)); | |
| 342 | return out; | |
| 343 | }; | |
| 344 | ||
| 345 | // Narrowed to a limb, read only what can be its work: its pulls (those | |
| 346 | // that say they close one of its issues), the runs those and its issues | |
| 347 | // could have, and the pulls those runs' work could have become. | |
| 348 | const limb = | |
| 349 | within === undefined | |
| 350 | ? [] | |
| 351 | : issueRows([...within]).filter( | |
| 352 | (i) => i.kind === "issue" && repoSet.has(i.repo_id), | |
| 353 | ); | |
| 354 | const limbKeys = new Set(limb.map((i) => `${i.repo_id}#${i.number}`)); | |
| 355 | const theirs = pullsNaming(numbersOf(limb)).filter((p) => | |
| 356 | closesOf.get(p.id)!.some((k) => limbKeys.has(`${p.repo_id}#${k}`)), | |
| 357 | ); | |
| 358 | const all = | |
| 162 | 359 | n === 0 |
| 163 | 360 | ? [] |
| 164 | : db | |
| 165 | .query<RunRow, string[]>( | |
| 166 | `SELECT id, repo_id, issue_id, branch, state, summary, cost_usd, started_at, finished_at | |
| 167 | FROM run WHERE kind = 'agent' AND repo_id IN (${marks(n)}) | |
| 168 | AND created_at >= ?${n + 1} AND created_at < ?${n + 2}`, | |
| 169 | ) | |
| 170 | .all(...repoIds, window.since, window.until); | |
| 361 | : within === undefined | |
| 362 | ? db | |
| 363 | .query<RunRow, string[]>( | |
| 364 | `SELECT ${RUN_COLUMNS} FROM run WHERE kind = 'agent' AND repo_id IN (${marks(n)}) | |
| 365 | AND created_at >= ?${n + 1} AND created_at < ?${n + 2}`, | |
| 366 | ) | |
| 367 | .all(...repoIds, window.since, window.until) | |
| 368 | : limbRuns(db, repoIds, window, limb, theirs, closesOf, idsByNumber); | |
| 369 | ||
| 370 | const issues = new Map<string, IssueRow>(); | |
| 371 | for (const row of issueRows([ | |
| 372 | ...new Set(all.flatMap((r) => (r.issue_id === null ? [] : [r.issue_id]))), | |
| 373 | ])) | |
| 374 | issues.set(row.id, row); | |
| 375 | for (const row of limb) issues.set(row.id, row); | |
| 376 | ||
| 171 | 377 | // Every pull in these repositories, once: what a run's work became. |
| 378 | // Narrowed to a limb, the pulls its runs' work could have become: those | |
| 379 | // runs are on, are on the head branch of, or say they close the issue of. | |
| 380 | const onBranches = (): PullRow[] => { | |
| 381 | const wanted = new Map<string, Set<string>>(); | |
| 382 | for (const r of all) | |
| 383 | if (r.branch !== "") | |
| 384 | wanted.set(r.repo_id, (wanted.get(r.repo_id) ?? new Set()).add(r.branch)); | |
| 385 | return [...wanted].flatMap(([repoId, names]) => | |
| 386 | batches([...names]).flatMap((batch) => | |
| 387 | readPulls( | |
| 388 | // `+`: walk the pull table, not every issue the repository has. | |
| 389 | `+issue.repo_id = ?1 AND pull.head_branch IN (${marks(batch.length, 2)})`, | |
| 390 | [repoId, ...batch], | |
| 391 | ), | |
| 392 | ), | |
| 393 | ); | |
| 394 | }; | |
| 395 | const ranOn = [...issues.values()]; | |
| 172 | 396 | const pulls = |
| 173 | 397 | n === 0 |
| 174 | 398 | ? [] |
| 175 | : db | |
| 176 | .query<PullRow, string[]>( | |
| 177 | `SELECT issue.id, issue.repo_id, issue.number, issue.body, issue.state, | |
| 178 | pull.head_branch, pull.merged_at | |
| 179 | FROM issue JOIN pull ON pull.issue_id = issue.id | |
| 180 | WHERE issue.repo_id IN (${marks(n)})`, | |
| 181 | ) | |
| 182 | .all(...repoIds); | |
| 399 | : within === undefined | |
| 400 | ? readPulls(`issue.repo_id IN (${marks(n)})`, repoIds) | |
| 401 | : [ | |
| 402 | ...new Map( | |
| 403 | [ | |
| 404 | ...theirs, | |
| 405 | ...batches(ranOn.filter((i) => i.kind === "pull").map((i) => i.id)).flatMap( | |
| 406 | (batch) => readPulls(`issue.id IN (${marks(batch.length)})`, batch), | |
| 407 | ), | |
| 408 | ...onBranches(), | |
| 409 | ...pullsNaming( | |
| 410 | numbersOf( | |
| 411 | ranOn.filter( | |
| 412 | (i) => i.kind === "issue" && !limbKeys.has(`${i.repo_id}#${i.number}`), | |
| 413 | ), | |
| 414 | ), | |
| 415 | ), | |
| 416 | ].map((p) => [p.id, p]), | |
| 417 | ).values(), | |
| 418 | ]; | |
| 183 | 419 | const pullById = new Map(pulls.map((p) => [p.id, p])); |
| 184 | 420 | const byBranch = new Map<string, PullRow[]>(); |
| 185 | 421 | const closing = new Map<string, PullRow[]>(); |
| 186 | 422 | for (const p of pulls) { |
| 187 | 423 | const b = `${p.repo_id}\u0000${p.head_branch}`; |
| 188 | 424 | byBranch.set(b, [...(byBranch.get(b) ?? []), p]); |
| 189 | for (const k of closesFromBody(p.body)) { | |
| 425 | for (const k of closesOf.get(p.id)!) { | |
| 190 | 426 | const c = `${p.repo_id}#${k}`; |
| 191 | 427 | closing.set(c, [...(closing.get(c) ?? []), p]); |
| 192 | 428 | } |
| 193 | 429 | } |
| 194 | const issueIds = [ | |
| 195 | ...new Set(runs.flatMap((r) => (r.issue_id === null ? [] : [r.issue_id]))), | |
| 196 | ]; | |
| 197 | const issues = new Map<string, IssueRow>(); | |
| 198 | for (let i = 0; i < issueIds.length; i += 400) { | |
| 199 | const batch = issueIds.slice(i, i + 400); | |
| 200 | for (const row of db | |
| 201 | .query< | |
| 202 | IssueRow, | |
| 203 | string[] | |
| 204 | >(`SELECT id, repo_id, number, title, kind, state FROM issue WHERE id IN (${marks(batch.length)})`) | |
| 205 | .all(...batch)) | |
| 206 | issues.set(row.id, row); | |
| 430 | ||
| 431 | // The issues a pull says it closes, by number: what a pull's run was for. | |
| 432 | // Grouping by pillar needs every one; a limb only its own. | |
| 433 | const closedIds = new Map<string, string>(); | |
| 434 | if (options.pillars !== undefined) { | |
| 435 | const wanted = new Map<string, Set<number>>(); | |
| 436 | for (const p of pulls) | |
| 437 | for (const k of closesOf.get(p.id)!) | |
| 438 | wanted.set(p.repo_id, (wanted.get(p.repo_id) ?? new Set()).add(k)); | |
| 439 | for (const [k, id] of idsByNumber(wanted)) closedIds.set(k, id); | |
| 207 | 440 | } |
| 441 | for (const i of limb) closedIds.set(`${i.repo_id}#${i.number}`, i.id); | |
| 208 | 442 | |
| 209 | 443 | /** The change a run worked toward: the merged pull if any of its candidates merged, else what is left. */ |
| 210 | 444 | const changeOf = (r: RunRow): { merged?: PullRow; candidates: PullRow[] } => { |
| @@ -223,6 +457,72 @@ export function tokenReturns( | ||
| 223 | 457 | return merged === undefined ? { candidates } : { merged, candidates }; |
| 224 | 458 | }; |
| 225 | 459 | |
| 460 | /** The issues a run's work was for, its own first: never a pull. */ | |
| 461 | const workedFor = ( | |
| 462 | r: RunRow, | |
| 463 | change: { merged?: PullRow; candidates: PullRow[] }, | |
| 464 | ): string[] => { | |
| 465 | const issue = r.issue_id === null ? undefined : issues.get(r.issue_id); | |
| 466 | const own = issue !== undefined && issue.kind !== "pull" ? [issue.id] : []; | |
| 467 | const pulls = [ | |
| 468 | ...(change.merged === undefined ? [] : [change.merged]), | |
| 469 | ...change.candidates, | |
| 470 | ]; | |
| 471 | return [ | |
| 472 | ...own, | |
| 473 | ...pulls.flatMap((p) => | |
| 474 | (closesOf.get(p.id) ?? []).flatMap((k) => { | |
| 475 | const id = closedIds.get(`${p.repo_id}#${k}`); | |
| 476 | return id === undefined ? [] : [id]; | |
| 477 | }), | |
| 478 | ), | |
| 479 | ]; | |
| 480 | }; | |
| 481 | const runs = | |
| 482 | within === undefined | |
| 483 | ? all.map((r) => ({ r, change: changeOf(r) })) | |
| 484 | : all.flatMap((r) => { | |
| 485 | const change = changeOf(r); | |
| 486 | const mine = | |
| 487 | (r.issue_id !== null && within.has(r.issue_id)) || | |
| 488 | workedFor(r, change).some((id) => within.has(id)); | |
| 489 | return mine ? [{ r, change }] : []; | |
| 490 | }); | |
| 491 | ||
| 492 | interface Row { | |
| 493 | runs: number; | |
| 494 | usd: number; | |
| 495 | landedRuns: number; | |
| 496 | landedUsd: number; | |
| 497 | changes: Set<string>; | |
| 498 | closed: { runs: number; usd: number }; | |
| 499 | open: { runs: number; usd: number }; | |
| 500 | } | |
| 501 | const rowOf = (): Row => ({ | |
| 502 | runs: 0, | |
| 503 | usd: 0, | |
| 504 | landedRuns: 0, | |
| 505 | landedUsd: 0, | |
| 506 | changes: new Set(), | |
| 507 | closed: { runs: 0, usd: 0 }, | |
| 508 | open: { runs: 0, usd: 0 }, | |
| 509 | }); | |
| 510 | const pillarRows = new Map<string, Row>(); | |
| 511 | const pillarKey = (repoId: string, pillar: string | null): string => | |
| 512 | `${repoId}\u0000${pillar ?? ""}`; | |
| 513 | const pillarOf = ( | |
| 514 | r: RunRow, | |
| 515 | change: { merged?: PullRow; candidates: PullRow[] }, | |
| 516 | ): string | null => { | |
| 517 | const map = options.pillars?.get(r.repo_id); | |
| 518 | if (map === undefined) return null; | |
| 519 | for (const id of workedFor(r, change)) { | |
| 520 | const name = map.of.get(id); | |
| 521 | if (name !== undefined) return name; | |
| 522 | } | |
| 523 | return null; | |
| 524 | }; | |
| 525 | ||
| 226 | 526 | const byState = new Map<string, { runs: number; usd: number }>(); |
| 227 | 527 | const perChange = new Map<string, number>(); |
| 228 | 528 | const nothing = new Map<string, { runs: number; usd: number }>(); |
| @@ -236,7 +536,7 @@ export function tokenReturns( | ||
| 236 | 536 | let landedUsd = 0; |
| 237 | 537 | const okUsd: number[] = []; |
| 238 | 538 | const okMinutes: number[] = []; |
| 239 | for (const r of runs) { | |
| 539 | for (const { r, change } of runs) { | |
| 240 | 540 | const usd = r.cost_usd ?? 0; |
| 241 | 541 | spentUsd += usd; |
| 242 | 542 | add(byState, r.state, usd); |
| @@ -247,7 +547,6 @@ export function tokenReturns( | ||
| 247 | 547 | (Date.parse(r.finished_at) - Date.parse(r.started_at)) / 60_000, |
| 248 | 548 | ); |
| 249 | 549 | } |
| 250 | const change = changeOf(r); | |
| 251 | 550 | const issue = r.issue_id === null ? undefined : issues.get(r.issue_id); |
| 252 | 551 | let outcome: Outcome; |
| 253 | 552 | if (change.merged !== undefined) { |
| @@ -273,18 +572,73 @@ export function tokenReturns( | ||
| 273 | 572 | add(failures, reasonOf(r.summary), usd); |
| 274 | 573 | } else if (r.state === "cancelled") add(nothing, "cancelled", usd); |
| 275 | 574 | } |
| 276 | if (issue !== undefined) { | |
| 277 | const m = perIssue.get(issue.id) ?? { runs: 0, usd: 0, outcome }; | |
| 575 | // Narrowed to a limb, a run counts toward the limb issue its work was | |
| 576 | // for, so the costliest are the limb's own and never a pull or an issue | |
| 577 | // outside it whose change closed one. | |
| 578 | const counted = | |
| 579 | within === undefined | |
| 580 | ? issue | |
| 581 | : issues.get(workedFor(r, change).find((id) => within.has(id)) ?? ""); | |
| 582 | if (counted !== undefined) { | |
| 583 | const m = perIssue.get(counted.id) ?? { runs: 0, usd: 0, outcome }; | |
| 278 | 584 | m.runs++; |
| 279 | 585 | m.usd += usd; |
| 280 | 586 | // An issue is landed once any of its runs' work landed. |
| 281 | 587 | if (outcome === "landed") m.outcome = "landed"; |
| 282 | perIssue.set(issue.id, m); | |
| 588 | perIssue.set(counted.id, m); | |
| 589 | } | |
| 590 | if (options.pillars !== undefined) { | |
| 591 | const key = pillarKey(r.repo_id, pillarOf(r, change)); | |
| 592 | const row = pillarRows.get(key) ?? rowOf(); | |
| 593 | row.runs++; | |
| 594 | row.usd += usd; | |
| 595 | if (change.merged !== undefined) { | |
| 596 | row.landedRuns++; | |
| 597 | row.landedUsd += usd; | |
| 598 | row.changes.add(change.merged.id); | |
| 599 | } else { | |
| 600 | const m = outcome === "closed" ? row.closed : row.open; | |
| 601 | m.runs++; | |
| 602 | m.usd += usd; | |
| 603 | } | |
| 604 | pillarRows.set(key, row); | |
| 283 | 605 | } |
| 284 | 606 | } |
| 285 | 607 | |
| 608 | const pillarRow = (repoId: string, pillar: string | null): PillarReturns => { | |
| 609 | const row = pillarRows.get(pillarKey(repoId, pillar)) ?? rowOf(); | |
| 610 | return { | |
| 611 | repoId, | |
| 612 | pillar, | |
| 613 | spent: money(row), | |
| 614 | onLanded: { runs: row.landedRuns, usd: cents(row.landedUsd) }, | |
| 615 | landed: row.changes.size, | |
| 616 | perLanded: | |
| 617 | row.changes.size === 0 ? null : cents(row.usd / row.changes.size), | |
| 618 | closed: money(row.closed), | |
| 619 | open: money(row.open), | |
| 620 | }; | |
| 621 | }; | |
| 622 | const byPillar = | |
| 623 | options.pillars === undefined | |
| 624 | ? [] | |
| 625 | : repoIds.flatMap((repoId) => { | |
| 626 | const names = options.pillars!.get(repoId)?.names ?? []; | |
| 627 | // A name the map serves but does not list still has its row, so the rows add up. | |
| 628 | const spentOn = [...pillarRows.keys()] | |
| 629 | .filter((k) => k.startsWith(`${repoId}\u0000`)) | |
| 630 | .map((k) => k.slice(repoId.length + 1)); | |
| 631 | const others = spentOn.filter((p) => p !== "" && !names.includes(p)); | |
| 632 | return [ | |
| 633 | ...[...names, ...others].map((name) => pillarRow(repoId, name)), | |
| 634 | ...(spentOn.includes("") ? [pillarRow(repoId, null)] : []), | |
| 635 | ]; | |
| 636 | }); | |
| 637 | ||
| 286 | 638 | const landed = |
| 287 | n === 0 | |
| 639 | within !== undefined | |
| 640 | ? perChange.size | |
| 641 | : n === 0 | |
| 288 | 642 | ? 0 |
| 289 | 643 | : (db |
| 290 | 644 | .query<{ n: number }, string[]>( |
| @@ -367,5 +721,6 @@ export function tokenReturns( | ||
| 367 | 721 | ...money(m), |
| 368 | 722 | }; |
| 369 | 723 | }), |
| 724 | byPillar, | |
| 370 | 725 | }; |
| 371 | 726 | } |
src/core/schema.ts +6
| @@ -1584,6 +1584,12 @@ export const migrations: readonly string[] = [ | ||
| 1584 | 1584 | ALTER TABLE look ADD COLUMN attached_by TEXT; |
| 1585 | 1585 | ALTER TABLE look ADD COLUMN note TEXT; |
| 1586 | 1586 | `, |
| 1587 | // 75 — the runs on a branch, by index (#1067's review): a milestone's | |
| 1588 | // returns read the runs on its pulls' head branches without scanning | |
| 1589 | // the repository's whole run history. | |
| 1590 | ` | |
| 1591 | CREATE INDEX IF NOT EXISTS run_repo_branch ON run(repo_id, branch) WHERE branch <> ''; | |
| 1592 | `, | |
| 1587 | 1593 | ]; |
| 1588 | 1594 | |
| 1589 | 1595 | /** |
src/http/mcp.ts +2 −2
| @@ -1175,7 +1175,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1175 | 1175 | { |
| 1176 | 1176 | name: "milestones", |
| 1177 | 1177 | description: |
| 1178 | "How far each thing asked for is, read from the dependency tree. With `app` alone: the plan's top-level limbs (the pillars and Later, or the plan's roots), each with done and total, open issues beneath it, how many are building, pulls merged in the last 7 days, its last movement, spend when you may see it, and `trim` when it is a candidate to trim. With `issue`: that milestone opened — who is building what, what is blocked and on what, what merged, an estimate from this week's pace, its own limbs and its leaves. The same numbers as the milestones pages.", | |
| 1178 | "How far each thing asked for is, read from the dependency tree. With `app` alone: the plan's top-level limbs (the pillars and Later, or the plan's roots), each with done and total, open issues beneath it, how many are building, pulls merged in the last 7 days, its last movement, spend when you may see it, and `trim` when it is a candidate to trim. With `issue`: that milestone opened — who is building what, what is blocked and on what, what merged, an estimate from this week's pace, its own limbs and its leaves, and, when you may see spend, `returns`: what the limb has cost and landed since it began, with its costliest issues. The same numbers as the milestones pages.", | |
| 1179 | 1179 | inputSchema: { |
| 1180 | 1180 | type: "object", |
| 1181 | 1181 | properties: { |
| @@ -1320,7 +1320,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1320 | 1320 | { |
| 1321 | 1321 | name: "returns", |
| 1322 | 1322 | description: |
| 1323 | "What the crew's tokens bought over the last days (1–90, default 7), so you can ask before you plan: dollars and runs by state; changes landed; dollars on work that landed and the median per landed change; dollars that landed nothing (closed without a merge, or still open), with failed and cancelled runs and the costliest failure reasons; what a good run costs and takes; and the costliest issues with what came of each. Over every app whose owner facts you hold, or `repo` (owner/name). Read-only; an app you cannot write is not found.", | |
| 1323 | "What the crew's tokens bought over the last days (1–90, default 7), so you can ask before you plan: dollars and runs by state; changes landed; dollars on work that landed and the median per landed change; dollars that landed nothing (closed without a merge, or still open), with failed and cancelled runs and the costliest failure reasons; what a good run costs and takes; the costliest issues with what came of each; and `byPillar`, the same by each app's pillar (dollars, changes landed, dollars per landed change with waste included, closed with nothing, still open). Over every app whose owner facts you hold, or `repo` (owner/name). Read-only; an app you cannot write is not found.", | |
| 1324 | 1324 | inputSchema: { |
| 1325 | 1325 | type: "object", |
| 1326 | 1326 | properties: { |
src/web/pages/milestones.ts +93 −6
| @@ -4,7 +4,9 @@ | ||
| 4 | 4 | * its weight — so the whole plan fits a phone; a line opens that milestone: |
| 5 | 5 | * how far it is, who is building, what is stuck and on what, what merged |
| 6 | 6 | * this week, when it lands at this week's pace, and its own limbs as lines. |
| 7 | * Leaves show only on the limb they are under. | |
| 7 | * Leaves show only on the limb they are under. Whoever holds the owner | |
| 8 | * facts also sees what the limb has cost and landed, with its costliest | |
| 9 | * issues (#1067), so a limb can be trimmed on evidence. | |
| 8 | 10 | * |
| 9 | 11 | * Everything here is read from the dependency tree by `core/milestones.ts`. |
| 10 | 12 | * Read-only: the page, the API and the MCP tool give the same numbers. |
| @@ -17,8 +19,11 @@ import { | ||
| 17 | 19 | type LeafState, |
| 18 | 20 | type Limb, |
| 19 | 21 | type Milestone, |
| 22 | type Plan, | |
| 20 | 23 | } from "../../core/milestones.ts"; |
| 21 | 24 | import type { LimbAction } from "../../actions/limbs.ts"; |
| 25 | import { limbReturns } from "../../actions/returns.ts"; | |
| 26 | import type { Returns } from "../../core/returns.ts"; | |
| 22 | 27 | import { isStructural, PILLAR_DAYS, pillarsOf } from "../../core/pillars.ts"; |
| 23 | 28 | import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts"; |
| 24 | 29 | import { isWatching } from "../../core/watches.ts"; |
| @@ -37,6 +42,7 @@ import { html, when, type Html } from "../html.ts"; | ||
| 37 | 42 | import { field, readForm } from "../form.ts"; |
| 38 | 43 | import { page, redirect } from "../layout.ts"; |
| 39 | 44 | import { btn, time } from "../ui.ts"; |
| 45 | import { usd } from "./board.ts"; | |
| 40 | 46 | |
| 41 | 47 | /** Where a milestone is: its own page. */ |
| 42 | 48 | export const milestoneHref = (base: string, number: number): string => |
| @@ -203,11 +209,57 @@ function watchButton(base: string, m: Milestone, watching: boolean): Html { | ||
| 203 | 209 | </form>`; |
| 204 | 210 | } |
| 205 | 211 | |
| 212 | /** How many of a limb's costliest issues its page names. */ | |
| 213 | const COSTLIEST = 5; | |
| 214 | ||
| 215 | const OUTCOME_WORDS = { | |
| 216 | landed: "landed", | |
| 217 | closed: "closed with nothing merged", | |
| 218 | open: "nothing merged yet", | |
| 219 | } as const; | |
| 220 | ||
| 221 | /** What the limb has cost and landed since it began: owner facts only. */ | |
| 222 | function costSection(base: string, r: Returns): Html { | |
| 223 | const nothing = r.landedNothing; | |
| 224 | return html`<section class="ms-section" id="ms-cost"> | |
| 225 | <h2>What it cost</h2> | |
| 226 | ${r.spent.runs === 0 | |
| 227 | ? html`<p class="muted small">No run of the crew's has worked on it.</p>` | |
| 228 | : html`<p> | |
| 229 | <b>${usd(r.spent.usd)}</b> over ${r.spent.runs} | |
| 230 | ${r.spent.runs === 1 ? "run" : "runs"} · <b>${r.landed}</b> | |
| 231 | ${r.landed === 1 ? "change" : "changes"} landed${r.landed === 0 | |
| 232 | ? null | |
| 233 | : html` · ${usd(r.spent.usd / r.landed)} a landed change`} | |
| 234 | · ${usd(nothing.closed.usd)} closed with nothing · | |
| 235 | ${usd(nothing.open.usd)} still open | |
| 236 | </p> | |
| 237 | <ul class="ms-rows"> | |
| 238 | ${r.costliest.slice(0, COSTLIEST).map( | |
| 239 | (c) => | |
| 240 | html`<li> | |
| 241 | <a href="${base}/issues/${c.number}">${c.title}</a> | |
| 242 | <span class="muted small" | |
| 243 | >#${c.number} · ${usd(c.usd)} · ${OUTCOME_WORDS[c.outcome]}</span | |
| 244 | > | |
| 245 | </li>`, | |
| 246 | )} | |
| 247 | </ul> | |
| 248 | <p class="muted small"> | |
| 249 | Since the limb began: the crew's runs on anything in it, or on a | |
| 250 | change that closes it — a run on another issue whose change closes | |
| 251 | one here counts toward the issue here. A landed change's cost is | |
| 252 | all of it over the changes it landed, waste included. | |
| 253 | </p>`} | |
| 254 | </section>`; | |
| 255 | } | |
| 256 | ||
| 206 | 257 | function milestoneBody( |
| 207 | 258 | repo: Repo, |
| 208 | 259 | m: Milestone, |
| 209 | 260 | names: boolean, |
| 210 | 261 | actions: Html | null, |
| 262 | cost: Returns | undefined, | |
| 211 | 263 | ): Html { |
| 212 | 264 | const base = repoBase(repo); |
| 213 | 265 | const issue = (number: number, title: string): Html => |
| @@ -324,6 +376,7 @@ function milestoneBody( | ||
| 324 | 376 | 3, |
| 325 | 377 | )} |
| 326 | 378 | </section> |
| 379 | ${cost === undefined ? null : costSection(base, cost)} | |
| 327 | 380 | ${when( |
| 328 | 381 | open.length > 0 || closed.length > 0 || stillOpen.length === 0, |
| 329 | 382 | () => |
| @@ -378,10 +431,12 @@ export function milestonePage(ctx: Ctx): Response { | ||
| 378 | 431 | if (!repo) return notFoundPage(ctx); |
| 379 | 432 | const number = Number(ctx.params.number); |
| 380 | 433 | const owner = canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user); |
| 434 | const plan = readPlan(ctx.app.db, repo, { spend: owner }); | |
| 381 | 435 | const milestone = Number.isInteger(number) |
| 382 | ? readPlan(ctx.app.db, repo, { spend: owner }).milestone(number) | |
| 436 | ? plan.milestone(number) | |
| 383 | 437 | : undefined; |
| 384 | 438 | if (milestone === undefined) return notFoundPage(ctx); |
outdated
This runs on every owner view of every milestone, uncached, and it costs a full-history scan (see the comment on |
||
| 439 | const cost = costOf(ctx, repo, plan, number); | |
| 385 | 440 | const viewer = ctx.auth.user; |
| 386 | 441 | // Watch is each person's own; acting on the whole limb is for whoever |
| 387 | 442 | // administers the repository. One row, Watch first. |
| @@ -409,11 +464,27 @@ export function milestonePage(ctx: Ctx): Response { | ||
| 409 | 464 | crumbs: crumbsFor(repo), |
| 410 | 465 | palette: repoPalette(ctx, repo), |
| 411 | 466 | body: html`${repoHeader(ctx, repo, "map")} |
| 412 | ${milestoneBody(repo, milestone, owner, actions)}`, | |
| 467 | ${milestoneBody(repo, milestone, owner, actions, cost)}`, | |
| 413 | 468 | styleCss: milestonesCss, |
| 414 | 469 | }); |
| 415 | 470 | } |
| 416 | 471 | |
| 472 | /** | |
| 473 | * What a limb cost and landed, for a viewer who holds the owner facts: read | |
| 474 | * by index from the limb's issues and pulls, never the whole run history. | |
| 475 | */ | |
| 476 | function costOf( | |
| 477 | ctx: Ctx, | |
| 478 | repo: Repo, | |
| 479 | plan: Plan, | |
| 480 | number: number, | |
| 481 | ): Returns | undefined { | |
| 482 | const limb = plan.limb(number); | |
| 483 | return limb === undefined | |
| 484 | ? undefined | |
| 485 | : limbReturns(ctx.app, ctx.auth.user, repo, [...limb.own, ...limb.shared]); | |
| 486 | } | |
| 487 | ||
| 417 | 488 | /** POST /:owner/:name/milestones/:number/watch — watch, or stop, and back to it. */ |
| 418 | 489 | export async function milestoneWatch(ctx: Ctx): Promise<Response> { |
| 419 | 490 | const repo = loadRepo(ctx); |
| @@ -457,15 +528,31 @@ export function milestoneData( | ||
| 457 | 528 | number: number, |
| 458 | 529 | ): Record<string, unknown> | undefined { |
| 459 | 530 | const owner = canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user); |
| 460 | const milestone = readPlan(ctx.app.db, repo, { spend: owner }).milestone( | |
| 461 | number, | |
| 462 | ); | |
| 531 | const plan = readPlan(ctx.app.db, repo, { spend: owner }); | |
| 532 | const milestone = plan.milestone(number); | |
| 463 | 533 | const viewer = ctx.auth.user; |
| 534 | const cost = | |
| 535 | milestone === undefined ? undefined : costOf(ctx, repo, plan, number); | |
| 464 | 536 | return milestone === undefined |
| 465 | 537 | ? undefined |
| 466 | 538 | : { |
| 467 | 539 | repo: { owner: repo.ownerName, name: repo.name }, |
| 468 | 540 | ...milestoneJson(milestone, owner), |
| 541 | // What the limb cost and landed since it began: owner facts only. | |
| 542 | ...(cost === undefined | |
| 543 | ? {} | |
| 544 | : { | |
| 545 | returns: { | |
| 546 | spent: cost.spent, | |
| 547 | landed: cost.landed, | |
| 548 | onLanded: cost.onLanded, | |
| 549 | closed: cost.landedNothing.closed, | |
| 550 | open: cost.landedNothing.open, | |
| 551 | costliest: cost.costliest | |
| 552 | .slice(0, COSTLIEST) | |
| 553 | .map(({ repoId: _, ...c }) => c), | |
| 554 | }, | |
| 555 | }), | |
| 469 | 556 | // Whether the caller watches it; a caller who cannot has no answer. |
| 470 | 557 | ...(viewer?.kind === "user" |
| 471 | 558 | ? { |
src/web/pages/returns.ts +41 −5
| @@ -1,13 +1,14 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * `/board/returns`: the board's tokens line, opened — what the window's |
| 3 | 3 | * dollars bought. Spent and landed first, then what did not land and why, |
| 4 | * then the same by pillar, so a limb of the map can be trimmed on evidence, | |
| 4 | 5 | * then the issues that cost the most with what came of each. Owner facts |
| 5 | 6 | * only (`actions/returns.ts`); `?apps=` narrows as on the board, `?days=` |
| 6 | 7 | * widens the window. |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | 10 | import { readReturns, returnsRepos } from "../../actions/returns.ts"; |
| 10 | import type { Money } from "../../core/returns.ts"; | |
| 11 | import type { Money, PillarReturns } from "../../core/returns.ts"; | |
| 11 | 12 | import { getReposByIds } from "../../core/repos.ts"; |
| 12 | 13 | import type { Ctx } from "../../http/context.ts"; |
| 13 | 14 | import { notFoundPage, signInFirst } from "../chrome.ts"; |
| @@ -25,6 +26,21 @@ const line = (title: string, m: Money, note?: string): Html => | ||
| 25 | 26 | trail: html`<b>${usd(m.usd)}</b>`, |
| 26 | 27 | }); |
| 27 | 28 | |
| 29 | /** One pillar's line: what it spent, and what that bought. */ | |
| 30 | const pillarLine = (p: PillarReturns, slug: string | null): Html => | |
| 31 | row({ | |
| 32 | title: html`${p.pillar ?? "No pillar"}${slug === null | |
| 33 | ? null | |
| 34 | : html` <span class="muted small">${slug}</span>`}`, | |
| 35 | meta: html`${runs(p.spent)} · ${p.landed} | |
| 36 | ${p.landed === 1 ? "change" : "changes"} landed${p.perLanded === null | |
| 37 | ? null | |
| 38 | : html` · ${usd(p.perLanded)} a landed change`} | |
| 39 | · ${usd(p.closed.usd)} closed with nothing · ${usd(p.open.usd)} still | |
| 40 | open`, | |
| 41 | trail: html`<b>${usd(p.spent.usd)}</b>`, | |
| 42 | }); | |
| 43 | ||
| 28 | 44 | /** GET /board/returns */ |
| 29 | 45 | export function returnsPage(ctx: Ctx): Response { |
| 30 | 46 | const user = ctx.auth.user; |
| @@ -56,10 +72,18 @@ export function returnsPage(ctx: Ctx): Response { | ||
| 56 | 72 | if (!read.ok) return notFoundPage(ctx); |
| 57 | 73 | const r = read.value; |
| 58 | 74 | const span = days ?? 7; |
| 59 | const repos = getReposByIds( | |
| 60 | ctx.app.db, | |
| 61 | r.costliest.map((c) => c.repoId), | |
| 62 | ); | |
| 75 | const repos = getReposByIds(ctx.app.db, [ | |
| 76 | ...r.costliest.map((c) => c.repoId), | |
| 77 | ...r.byPillar.map((p) => p.repoId), | |
| 78 | ]); | |
| 79 | // Name the app on a pillar's line only when more than one has pillars. | |
| 80 | const pillarRepos = new Set(r.byPillar.map((p) => p.repoId)); | |
| 81 | const slugOf = (id: string): string | null => { | |
| 82 | const repo = repos.get(id); | |
| 83 | return pillarRepos.size < 2 || repo === undefined | |
| 84 | ? null | |
| 85 | : `${repo.ownerName}/${repo.name}`; | |
| 86 | }; | |
| 63 | 87 | const nothing = r.landedNothing; |
| 64 | 88 | const body = html`<h1 id="returns-title"> |
| 65 | 89 | What the tokens bought, ${span} days |
| @@ -94,6 +118,18 @@ export function returnsPage(ctx: Ctx): Response { | ||
| 94 | 118 | ], |
| 95 | 119 | { head: html`<h2>What did not land, and why</h2>` }, |
| 96 | 120 | )} |
| 121 | ${r.byPillar.length === 0 | |
| 122 | ? null | |
| 123 | : listCard( | |
| 124 | r.byPillar.map((p) => pillarLine(p, slugOf(p.repoId))), | |
| 125 | { | |
| 126 | head: html`<h2 id="returns-by-pillar">By pillar</h2> | |
| 127 | <span class="muted small" | |
| 128 | >a landed change's cost here is all the pillar's dollars | |
| 129 | over the changes it landed, waste included</span | |
| 130 | >`, | |
| 131 | }, | |
| 132 | )} | |
| 97 | 133 | ${listCard( |
| 98 | 134 | r.costliest.map((c) => { |
| 99 | 135 | const repo = repos.get(c.repoId); |
test/returns-limb.test.ts added +182
| @@ -0,0 +1,182 @@ | ||
| 1 | /** | |
| 2 | * A limb's returns read only the runs that can be the limb's (#1067's | |
| 3 | * review): never the repository's whole history. Worked by hand — | |
| 4 | * | |
| 5 | * limb Engine: ok $1.00 on its own issue | |
| 6 | * its change "Closes #engine, closes #wheel", on bot/engine: ok $0.40 on | |
| 7 | * the branch, merged; Wheel (outside the limb) ok $0.25, since | |
| 8 | * its change is that same pull; Spare (outside, closed by | |
| 9 | * nothing) ok $0.15 on bot/engine, the same change again | |
| 10 | * a retry "Fixes #0engine", zero-padded, on bot/engine-2: ok $0.05 on | |
| 11 | * the pull itself, never merged | |
| 12 | * → $1.85 over 5 runs, 1 change landed | |
| 13 | * elsewhere 200 runs on 200 other issues, $1.00 each: never read | |
| 14 | * | |
| 15 | * Costliest lists Engine alone, with all $1.85: the runs on Wheel and Spare | |
| 16 | * were for Engine's change, and neither is in the limb. | |
| 17 | */ | |
| 18 | ||
| 19 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 20 | import type { Database } from "bun:sqlite"; | |
| 21 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 22 | import { tmpdir } from "node:os"; | |
| 23 | import { join } from "node:path"; | |
| 24 | import { createApp, type App } from "../src/app.ts"; | |
| 25 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 26 | import { openIssue } from "../src/actions/issues.ts"; | |
| 27 | import { openPull } from "../src/actions/pulls.ts"; | |
| 28 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 29 | import { getIssueById, type Issue } from "../src/core/issues.ts"; | |
| 30 | import type { Repo } from "../src/core/repos.ts"; | |
| 31 | import { tokenReturns } from "../src/core/returns.ts"; | |
| 32 | import { createRun } from "../src/core/runs.ts"; | |
| 33 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 34 | import { quietLogs } from "./helpers/globals.ts"; | |
| 35 | ||
| 36 | quietLogs(); | |
| 37 | ||
| 38 | describe("a limb's returns", () => { | |
| 39 | let dataDir = ""; | |
| 40 | let app: App; | |
| 41 | let alice: User; | |
| 42 | let repo: Repo; | |
| 43 | let engine: Issue; | |
| 44 | let wheel: Issue; | |
| 45 | const elsewhere = new Set<string>(); | |
| 46 | ||
| 47 | const run = (issue: Issue, usd: number, branch = ""): string => { | |
| 48 | const made = createRun(app.db, { | |
| 49 | repoId: repo.id, | |
| 50 | kind: "agent", | |
| 51 | issueId: issue.id, | |
| 52 | branch, | |
| 53 | actorId: getUserByName(app.db, "bot")!.id, | |
| 54 | reason: "assigned", | |
| 55 | }); | |
| 56 | app.db | |
| 57 | .query("UPDATE run SET state = 'ok', cost_usd = ?2 WHERE id = ?1") | |
| 58 | .run(made.id, usd); | |
| 59 | return made.id; | |
| 60 | }; | |
| 61 | ||
| 62 | beforeAll(async () => { | |
| 63 | dataDir = await mkdtemp(join(tmpdir(), "forge-limb-returns-")); | |
| 64 | app = createApp({ dataDir, port: 0 }); | |
| 65 | const a = await createUser(app.db, { | |
| 66 | username: "alice", | |
| 67 | email: "[email protected]", | |
| 68 | password: "a-long-limb-returns-passphrase", | |
| 69 | adminIfFirst: true, | |
| 70 | trusted: true, | |
| 71 | }); | |
| 72 | if (!a.ok) throw new Error("user"); | |
| 73 | alice = a.value; | |
| 74 | const made = await createRepo(app, alice, { name: "mill", visibility: "private" }); | |
| 75 | if (!made.ok) throw new Error(String(made.error)); | |
| 76 | repo = made.value; | |
| 77 | await commitToBranch(app, alice, repo, { | |
| 78 | message: "seed", | |
| 79 | files: [{ path: "README.md", content: "# mill\n" }], | |
| 80 | }); | |
| 81 | await createAgent(app, alice, { username: "bot" }); | |
| 82 | addToCrew(app, alice, repo, "bot"); | |
| 83 | const issue = (title: string): Issue => { | |
| 84 | const opened = openIssue(app, alice, repo, { title }); | |
| 85 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 86 | return opened.value; | |
| 87 | }; | |
| 88 | ||
| 89 | engine = issue("Engine"); | |
| 90 | wheel = issue("Wheel"); | |
| 91 | run(engine, 1); | |
| 92 | run(wheel, 0.25); | |
| 93 | run(engine, 0.4, "bot/engine"); | |
| 94 | run(issue("Spare"), 0.15, "bot/engine"); | |
| 95 | await commitToBranch(app, alice, repo, { | |
| 96 | branch: "bot/engine", | |
| 97 | base: "main", | |
| 98 | message: "engine", | |
| 99 | files: [{ path: "engine.md", content: "work\n" }], | |
| 100 | }); | |
| 101 | const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, { | |
| 102 | title: "Engine and wheel", | |
| 103 | body: `Closes #${engine.number}, closes #${wheel.number}`, | |
| 104 | baseBranch: "main", | |
| 105 | headBranch: "bot/engine", | |
| 106 | }); | |
| 107 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 108 | app.db | |
| 109 | .query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1") | |
| 110 | .run(getIssueById(app.db, opened.value.id)!.id, new Date().toISOString()); | |
| 111 | await commitToBranch(app, alice, repo, { | |
| 112 | branch: "bot/engine-2", | |
| 113 | base: "main", | |
| 114 | message: "retry", | |
| 115 | files: [{ path: "retry.md", content: "work\n" }], | |
| 116 | }); | |
| 117 | const retry = await openPull(app, getUserByName(app.db, "bot")!, repo, { | |
| 118 | title: "Engine, again", | |
| 119 | body: `Fixes #0${engine.number}`, | |
| 120 | baseBranch: "main", | |
| 121 | headBranch: "bot/engine-2", | |
| 122 | }); | |
| 123 | if (!retry.ok) throw new Error(String(retry.error)); | |
| 124 | run(getIssueById(app.db, retry.value.id)!, 0.05); | |
| 125 | for (let i = 0; i < 200; i++) elsewhere.add(run(issue(`Other ${i}`), 1)); | |
| 126 | }, 60_000); | |
| 127 | ||
| 128 | afterAll(async () => { | |
| 129 | app.close(); | |
| 130 | await rm(dataDir, { recursive: true, force: true }); | |
| 131 | }); | |
| 132 | ||
| 133 | /** The database, with every run row any query hands back written down. */ | |
| 134 | const watched = (read: Set<string>): Database => | |
| 135 | new Proxy(app.db, { | |
| 136 | get(db, key) { | |
| 137 | if (key !== "query") return Reflect.get(db, key, db); | |
| 138 | return (sql: string) => { | |
| 139 | const q = db.query(sql); | |
| 140 | if (!/\bFROM run\b/.test(sql)) return q; | |
| 141 | return { | |
| 142 | all: (...args: never[]) => { | |
| 143 | const rows = q.all(...args) as { id: string }[]; | |
| 144 | for (const r of rows) read.add(r.id); | |
| 145 | return rows; | |
| 146 | }, | |
| 147 | }; | |
| 148 | }; | |
| 149 | }, | |
| 150 | }) as Database; | |
| 151 | ||
| 152 | const window = () => ({ | |
| 153 | since: new Date(0).toISOString(), | |
| 154 | until: new Date(Date.now() + 1000).toISOString(), | |
| 155 | }); | |
| 156 | ||
| 157 | test("reads only the runs that can be the limb's, and counts them right", () => { | |
| 158 | const read = new Set<string>(); | |
| 159 | const r = tokenReturns(watched(read), [repo.id], window(), { | |
| 160 | within: new Set([engine.id]), | |
| 161 | }); | |
| 162 | expect(r.spent).toEqual({ runs: 5, usd: 1.85 }); | |
| 163 | expect(r.landed).toBe(1); | |
| 164 | expect(r.landedNothing.open).toEqual({ runs: 1, usd: 0.05 }); | |
| 165 | expect(read.size).toBe(5); | |
| 166 | for (const id of elsewhere) expect(read.has(id)).toBe(false); | |
| 167 | // Unnarrowed, the same database reads every run. | |
| 168 | const everything = new Set<string>(); | |
| 169 | tokenReturns(watched(everything), [repo.id], window()); | |
| 170 | expect(everything.size).toBe(205); | |
| 171 | }); | |
| 172 | ||
| 173 | test("its costliest are its own issues, never one outside it", () => { | |
| 174 | const r = tokenReturns(app.db, [repo.id], window(), { | |
| 175 | within: new Set([engine.id]), | |
| 176 | }); | |
| 177 | expect(r.costliest.map((c) => [c.title, c.usd, c.runs, c.outcome])).toEqual([ | |
| 178 | ["Engine", 1.85, 5, "landed"], | |
| 179 | ]); | |
| 180 | expect(r.costliest.some((c) => c.number === wheel.number)).toBe(false); | |
| 181 | }); | |
| 182 | }); |
test/returns-pillars.test.ts added +329
| @@ -0,0 +1,329 @@ | ||
| 1 | /** | |
| 2 | * What the tokens bought, by pillar and by milestone (#1067): a fixture | |
| 3 | * across two pillars and some work that serves none, worked by hand — | |
| 4 | * | |
| 5 | * P0 Trust landed: failed $0.50 + ok $1.00, merged · declined: failed $2.00, closed | |
| 6 | * → $3.50 over 3 runs, 1 change landed, $3.50 a landed change, | |
| 7 | * $2.00 closed with nothing, $0 still open | |
| 8 | * P1 Speed dropped: ok $0.40, pull closed · waiting: cancelled $0.10 | |
| 9 | * shipped: ok $0.60 on its branch + $0.20 on its pull, merged | |
| 10 | * → $1.30 over 4 runs, 1 landed, $1.30 a landed change, | |
| 11 | * $0.40 closed with nothing, $0.10 still open | |
| 12 | * no pillar stray: ok $0.30, open → $0.30 over 1 run | |
| 13 | * | |
| 14 | * The rows add up to the $5.10 over 8 runs spent. A reader and an anonymous | |
| 15 | * visitor get none of it. Requests go through the handler, not a listener. | |
| 16 | */ | |
| 17 | ||
| 18 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 19 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 20 | import { tmpdir } from "node:os"; | |
| 21 | import { join } from "node:path"; | |
| 22 | import { createApp, type App } from "../src/app.ts"; | |
| 23 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 24 | import { linkIssue } from "../src/actions/dependencies.ts"; | |
| 25 | import { openIssue, setIssueState } from "../src/actions/issues.ts"; | |
| 26 | import { openPull } from "../src/actions/pulls.ts"; | |
| 27 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 28 | import { getIssueById, type Issue } from "../src/core/issues.ts"; | |
| 29 | import type { Repo } from "../src/core/repos.ts"; | |
| 30 | import { createRun } from "../src/core/runs.ts"; | |
| 31 | import { createSession } from "../src/core/sessions.ts"; | |
| 32 | import { createToken } from "../src/core/tokens.ts"; | |
| 33 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 34 | import { readReturns } from "../src/actions/returns.ts"; | |
| 35 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 36 | import { quietLogs } from "./helpers/globals.ts"; | |
| 37 | ||
| 38 | quietLogs(); | |
| 39 | ||
| 40 | const PASSWORD = "a-long-pillar-returns-passphrase"; | |
| 41 | const ORIGIN = "http://localhost:3000"; | |
| 42 | ||
| 43 | describe("what the tokens bought, by pillar and by milestone", () => { | |
| 44 | let dataDir = ""; | |
| 45 | let app: App; | |
| 46 | let http: ForgeHttp; | |
| 47 | let alice: User; | |
| 48 | let bob: User; | |
| 49 | let repo: Repo; | |
| 50 | let trust: Issue; | |
| 51 | let aliceCookie = ""; | |
| 52 | let bobCookie = ""; | |
| 53 | let aliceRw = ""; | |
| 54 | let bobRw = ""; | |
| 55 | ||
| 56 | const get = (path: string, auth: { cookie?: string; token?: string } = {}) => | |
| 57 | http.handle( | |
| 58 | new Request(`${ORIGIN}${path}`, { | |
| 59 | headers: { | |
| 60 | ...(auth.cookie ? { cookie: auth.cookie } : {}), | |
| 61 | ...(auth.token ? { authorization: `Bearer ${auth.token}` } : {}), | |
| 62 | }, | |
| 63 | redirect: "manual", | |
| 64 | }), | |
| 65 | ); | |
| 66 | ||
| 67 | const mcp = async (token: string, name: string, args: unknown) => { | |
| 68 | const res = await http.handle( | |
| 69 | new Request(`${ORIGIN}/mcp`, { | |
| 70 | method: "POST", | |
| 71 | headers: { | |
| 72 | "content-type": "application/json", | |
| 73 | accept: "application/json, text/event-stream", | |
| 74 | authorization: `Bearer ${token}`, | |
| 75 | }, | |
| 76 | body: JSON.stringify({ | |
| 77 | jsonrpc: "2.0", | |
| 78 | id: 1, | |
| 79 | method: "tools/call", | |
| 80 | params: { name, arguments: args }, | |
| 81 | }), | |
| 82 | }), | |
| 83 | ); | |
| 84 | return ( | |
| 85 | (await res.json()) as { | |
| 86 | result: { isError?: boolean; content: { text: string }[] }; | |
| 87 | } | |
| 88 | ).result; | |
| 89 | }; | |
| 90 | ||
| 91 | const run = ( | |
| 92 | issue: Issue, | |
| 93 | state: "ok" | "failed" | "cancelled", | |
| 94 | usd: number, | |
| 95 | branch = "", | |
| 96 | ): void => { | |
| 97 | const made = createRun(app.db, { | |
| 98 | repoId: repo.id, | |
| 99 | kind: "agent", | |
| 100 | issueId: issue.id, | |
| 101 | branch, | |
| 102 | actorId: getUserByName(app.db, "bot")!.id, | |
| 103 | reason: "assigned", | |
| 104 | }); | |
| 105 | app.db | |
| 106 | .query( | |
| 107 | "UPDATE run SET state = ?2, cost_usd = ?3, summary = ?2, started_at = ?4, finished_at = ?4 WHERE id = ?1", | |
| 108 | ) | |
| 109 | .run(made.id, state, usd, new Date().toISOString()); | |
| 110 | }; | |
| 111 | ||
| 112 | const pullFrom = async (issue: Issue, branch: string): Promise<Issue> => { | |
| 113 | await commitToBranch(app, alice, repo, { | |
| 114 | branch, | |
| 115 | base: "main", | |
| 116 | message: branch, | |
| 117 | files: [{ path: `${branch.replace(/\W/g, "-")}.md`, content: "work\n" }], | |
| 118 | }); | |
| 119 | const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, { | |
| 120 | title: `Work on #${issue.number}`, | |
| 121 | body: `Closes #${issue.number}`, | |
| 122 | baseBranch: "main", | |
| 123 | headBranch: branch, | |
| 124 | }); | |
| 125 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 126 | return getIssueById(app.db, opened.value.id)!; | |
| 127 | }; | |
| 128 | ||
| 129 | const merge = (pull: Issue): void => { | |
| 130 | app.db | |
| 131 | .query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1") | |
| 132 | .run(pull.id, new Date().toISOString()); | |
| 133 | }; | |
| 134 | ||
| 135 | const close = (issue: Issue): void => { | |
| 136 | setIssueState(app, alice, repo, getIssueById(app.db, issue.id)!, "closed"); | |
| 137 | }; | |
| 138 | ||
| 139 | beforeAll(async () => { | |
| 140 | dataDir = await mkdtemp(join(tmpdir(), "forge-pillar-returns-")); | |
| 141 | app = createApp({ dataDir, port: 0 }); | |
| 142 | http = forgeHttp(app); | |
| 143 | const a = await createUser(app.db, { | |
| 144 | username: "alice", | |
| 145 | email: "[email protected]", | |
| 146 | password: PASSWORD, | |
| 147 | adminIfFirst: true, | |
| 148 | trusted: true, | |
| 149 | }); | |
| 150 | const b = await createUser(app.db, { | |
| 151 | username: "bob", | |
| 152 | email: "[email protected]", | |
| 153 | password: PASSWORD, | |
| 154 | trusted: true, | |
| 155 | }); | |
| 156 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 157 | alice = a.value; | |
| 158 | bob = b.value; | |
| 159 | aliceCookie = `forge_session=${createSession(app.db, alice.id).token}; forge_mode=studio`; | |
| 160 | bobCookie = `forge_session=${createSession(app.db, bob.id).token}; forge_mode=studio`; | |
| 161 | aliceRw = createToken(app.db, alice.id, "rw", "rw").token; | |
| 162 | bobRw = createToken(app.db, bob.id, "rw", "rw").token; | |
| 163 | // Public: bob reads it, and must still learn nothing of its spend. | |
| 164 | const made = await createRepo(app, alice, { name: "mill", visibility: "public" }); | |
| 165 | if (!made.ok) throw new Error(String(made.error)); | |
| 166 | repo = made.value; | |
| 167 | await commitToBranch(app, alice, repo, { | |
| 168 | message: "seed", | |
| 169 | files: [{ path: "README.md", content: "# mill\n" }], | |
| 170 | }); | |
| 171 | await createAgent(app, alice, { username: "bot" }); | |
| 172 | addToCrew(app, alice, repo, "bot"); | |
| 173 | ||
| 174 | const issue = (title: string): Issue => { | |
| 175 | const opened = openIssue(app, alice, repo, { title }); | |
| 176 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 177 | return opened.value; | |
| 178 | }; | |
| 179 | trust = issue("P0 Trust: the crew is contained"); | |
| 180 | const speed = issue("P1 Speed: every page answers fast"); | |
| 181 | const serve = (umbrella: Issue, title: string): Issue => { | |
| 182 | const made = issue(title); | |
| 183 | const linked = linkIssue(app, alice, repo, umbrella, made); | |
| 184 | if (!linked.ok) throw new Error(String(linked.error)); | |
| 185 | return made; | |
| 186 | }; | |
| 187 | ||
| 188 | const landed = serve(trust, "Landed work"); | |
| 189 | run(landed, "failed", 0.5); | |
| 190 | run(landed, "ok", 1, "bot/landed"); | |
| 191 | merge(await pullFrom(landed, "bot/landed")); | |
| 192 | const declined = serve(trust, "Declined work"); | |
| 193 | run(declined, "failed", 2); | |
| 194 | close(declined); | |
| 195 | ||
| 196 | const dropped = serve(speed, "Dropped work"); | |
| 197 | run(dropped, "ok", 0.4, "bot/dropped"); | |
| 198 | close(await pullFrom(dropped, "bot/dropped")); | |
| 199 | close(dropped); | |
| 200 | run(serve(speed, "Waiting work"), "cancelled", 0.1); | |
| 201 | const shipped = serve(speed, "Shipped work"); | |
| 202 | run(shipped, "ok", 0.6, "bot/shipped"); | |
| 203 | const shippedPull = await pullFrom(shipped, "bot/shipped"); | |
| 204 | // A run on the pull itself serves the pillar of the issue it closes. | |
| 205 | run(shippedPull, "ok", 0.2); | |
| 206 | merge(shippedPull); | |
| 207 | ||
| 208 | run(issue("Stray work"), "ok", 0.3); | |
| 209 | }, 30_000); | |
| 210 | ||
| 211 | afterAll(async () => { | |
| 212 | http.close(); | |
| 213 | app.close(); | |
| 214 | await rm(dataDir, { recursive: true, force: true }); | |
| 215 | }); | |
| 216 | ||
| 217 | test("a fixture across two pillars adds up", () => { | |
| 218 | const read = readReturns(app, alice, { now: new Date(Date.now() + 1000) }); | |
| 219 | if (!read.ok) throw new Error(read.error); | |
| 220 | const r = read.value; | |
| 221 | expect(r.spent).toEqual({ runs: 8, usd: 5.1 }); | |
| 222 | expect(r.byPillar.map((p) => ({ ...p, repoId: undefined }))).toEqual([ | |
| 223 | { | |
| 224 | repoId: undefined, | |
| 225 | pillar: "P0 Trust", | |
| 226 | spent: { runs: 3, usd: 3.5 }, | |
| 227 | onLanded: { runs: 2, usd: 1.5 }, | |
| 228 | landed: 1, | |
| 229 | perLanded: 3.5, | |
| 230 | closed: { runs: 1, usd: 2 }, | |
| 231 | open: { runs: 0, usd: 0 }, | |
| 232 | }, | |
| 233 | { | |
| 234 | repoId: undefined, | |
| 235 | pillar: "P1 Speed", | |
| 236 | spent: { runs: 4, usd: 1.3 }, | |
| 237 | onLanded: { runs: 2, usd: 0.8 }, | |
| 238 | landed: 1, | |
| 239 | perLanded: 1.3, | |
| 240 | closed: { runs: 1, usd: 0.4 }, | |
| 241 | open: { runs: 1, usd: 0.1 }, | |
| 242 | }, | |
| 243 | { | |
| 244 | repoId: undefined, | |
| 245 | pillar: null, | |
| 246 | spent: { runs: 1, usd: 0.3 }, | |
| 247 | onLanded: { runs: 0, usd: 0 }, | |
| 248 | landed: 0, | |
| 249 | perLanded: null, | |
| 250 | closed: { runs: 0, usd: 0 }, | |
| 251 | open: { runs: 1, usd: 0.3 }, | |
| 252 | }, | |
| 253 | ]); | |
| 254 | // Every run in exactly one row: the rows are the whole. | |
| 255 | const sum = (f: (p: (typeof r.byPillar)[number]) => number): number => | |
| 256 | Math.round(r.byPillar.reduce((s, p) => s + f(p), 0) * 100) / 100; | |
| 257 | expect(sum((p) => p.spent.usd)).toBe(r.spent.usd); | |
| 258 | expect(sum((p) => p.spent.runs)).toBe(r.spent.runs); | |
| 259 | expect(sum((p) => p.onLanded.usd)).toBe(r.onLanded.usd); | |
| 260 | expect(sum((p) => p.closed.usd)).toBe(r.landedNothing.closed.usd); | |
| 261 | expect(sum((p) => p.open.usd)).toBe(r.landedNothing.open.usd); | |
| 262 | expect(sum((p) => p.landed)).toBe(r.onLanded.perChange.changes); | |
| 263 | }); | |
| 264 | ||
| 265 | test("the owner sees a By pillar card, the same over the API and MCP", async () => { | |
| 266 | const page = ( | |
| 267 | await (await get("/board/returns", { cookie: aliceCookie })).text() | |
| 268 | ).replace(/\s+/g, " "); | |
| 269 | expect(page).toContain('id="returns-by-pillar"'); | |
| 270 | expect(page).toContain("P0 Trust"); | |
| 271 | expect(page).toContain("$3.50 a landed change"); | |
| 272 | expect(page).toContain("No pillar"); | |
| 273 | const api = (await ( | |
| 274 | await get("/api/v1/returns?repo=alice/mill", { token: aliceRw }) | |
| 275 | ).json()) as { byPillar: { pillar: string | null; perLanded: number | null }[] }; | |
| 276 | expect(api.byPillar.map((p) => [p.pillar, p.perLanded])).toEqual([ | |
| 277 | ["P0 Trust", 3.5], | |
| 278 | ["P1 Speed", 1.3], | |
| 279 | [null, null], | |
| 280 | ]); | |
| 281 | const tool = await mcp(aliceRw, "returns", {}); | |
| 282 | expect(JSON.parse(tool.content[0]!.text).byPillar).toHaveLength(3); | |
| 283 | }); | |
| 284 | ||
| 285 | test("a milestone's page says what its limb cost and landed, with its costliest issues", async () => { | |
| 286 | const page = ( | |
| 287 | await ( | |
| 288 | await get(`/alice/mill/milestones/${trust.number}`, { cookie: aliceCookie }) | |
| 289 | ).text() | |
| 290 | ).replace(/\s+/g, " "); | |
| 291 | expect(page).toContain('id="ms-cost"'); | |
| 292 | expect(page).toContain("<b>$3.50</b> over 3 runs · <b>1</b> change landed · $3.50 a landed change · $2.00 closed with nothing · $0.00 still open"); | |
| 293 | // Costliest first: the declined issue, then the landed one. | |
| 294 | const declined = page.indexOf("Declined work</a>"); | |
| 295 | const landed = page.indexOf("Landed work</a>"); | |
| 296 | expect(declined).toBeGreaterThan(page.indexOf('id="ms-cost"')); | |
| 297 | expect(landed).toBeGreaterThan(declined); | |
| 298 | expect(page).toContain("closed with nothing merged"); | |
| 299 | const api = (await ( | |
| 300 | await get(`/api/v1/repos/alice/mill/milestones/${trust.number}`, { token: aliceRw }) | |
| 301 | ).json()) as { returns: { spent: { usd: number }; landed: number; costliest: { title: string }[] } }; | |
| 302 | expect(api.returns.spent.usd).toBe(3.5); | |
| 303 | expect(api.returns.landed).toBe(1); | |
| 304 | expect(api.returns.costliest.map((c) => c.title)).toEqual(["Declined work", "Landed work"]); | |
| 305 | }); | |
| 306 | ||
| 307 | test("a reader and an anonymous visitor get none of it", async () => { | |
| 308 | expect((await get("/api/v1/returns")).status).toBe(401); | |
| 309 | const bobs = (await ( | |
| 310 | await get("/api/v1/returns", { token: bobRw }) | |
| 311 | ).json()) as { byPillar: unknown[]; repos: string[] }; | |
| 312 | expect(bobs.repos).toEqual([]); | |
| 313 | expect(bobs.byPillar).toEqual([]); | |
| 314 | expect((await mcp(bobRw, "returns", { repo: "alice/mill" })).isError).toBe(true); | |
| 315 | expect((await get("/board/returns?apps=alice/mill", { cookie: bobCookie })).status).toBe(404); | |
| 316 | for (const auth of [{ cookie: bobCookie }, {}]) { | |
| 317 | const res = await get(`/alice/mill/milestones/${trust.number}`, auth); | |
| 318 | expect(res.status).toBe(200); | |
| 319 | const page = await res.text(); | |
| 320 | expect(page).not.toContain('id="ms-cost"'); | |
| 321 | expect(page).not.toContain("$3.50"); | |
| 322 | } | |
| 323 | for (const auth of [{ token: bobRw }, {}]) { | |
| 324 | const res = await get(`/api/v1/repos/alice/mill/milestones/${trust.number}`, auth); | |
| 325 | expect(res.status).toBe(200); | |
| 326 | expect(await res.json()).not.toHaveProperty("returns"); | |
| 327 | } | |
| 328 | }); | |
| 329 | }); |
Starting at the epoch means each owner page view reads the repository's whole run history (~190 ms at 4k runs, ~1.1 s at 20k in my timing). Narrow the SQL to the limb's issues and the pulls that close them instead of scanning everything and filtering afterwards.