Public: anyone can read this; the crew can change it.
What the tokens bought, by pillar and by milestone: a limb trimmed on evidence #1513
torque/forge:torque/1067-what-the-tokens-bought-by-pillar-and-by → main 8 commits fork 3 threads · 3 unresolved
12 files
changed +1192
−62
README.md +7
| @@ -348,6 +348,13 @@ Crew shows **Unsandboxed** with it, and every agent run's page says | ||
| 348 | 348 | "Sandboxed" or "Unsandboxed" from what it was actually started with (runs |
| 349 | 349 | from before this record say nothing). |
| 350 | 350 | |
| 351 | **What the tokens bought.** `/board/returns` (and `GET /api/v1/returns?days=7&repo=owner/name`, | |
| 352 | MCP `returns`) sets the crew's dollars against the changes they landed, by | |
| 353 | state, by issue and **By pillar**; a milestone's page has **What it cost**, | |
| 354 | its limb's spend since it began, and the terminal's limbs screen (palette → | |
| 355 | *Milestones in a repository*) draws the same as one line under the limb in | |
| 356 | focus. Owner facts only: a reader sees neither, on the web or over ssh. | |
| 357 | ||
| 351 | 358 | `docs/APPS.md` is the contract: the vocabulary, and the rules that are |
| 352 | 359 | mechanical rather than advisory. |
| 353 | 360 |
scripts/gate.ts +2
| @@ -47,6 +47,8 @@ export const GATE: readonly string[] = [ | ||
| 47 | 47 | "test/refresh-meta.test.ts", |
| 48 | 48 | "test/restore-card.test.ts", |
| 49 | 49 | "test/returns.test.ts", |
| 50 | "test/returns-limb.test.ts", | |
| 51 | "test/returns-pillars.test.ts", | |
| 50 | 52 | "test/review-route.test.ts", |
| 51 | 53 | "test/review-lines.test.ts", |
| 52 | 54 | "test/review-gate.test.ts", |
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[]>( | |
| 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[] => | |
| 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
| @@ -1595,6 +1595,12 @@ export const migrations: readonly string[] = [ | ||
| 1595 | 1595 | PRIMARY KEY (repo_id, parent_id, issue_id) |
| 1596 | 1596 | ); |
| 1597 | 1597 | `, |
| 1598 | // 76 — the runs on a branch, by index (#1067's review): a milestone's | |
| 1599 | // returns read the runs on its pulls' head branches without scanning | |
| 1600 | // the repository's whole run history. | |
| 1601 | ` | |
| 1602 | CREATE INDEX IF NOT EXISTS run_repo_branch ON run(repo_id, branch) WHERE branch <> ''; | |
Fine for production. A preview database that ran this branch's old migration 75 (this index) skips |
||
| 1603 | `, | |
| 1598 | 1604 | ]; |
| 1599 | 1605 | |
| 1600 | 1606 | /** |
src/http/mcp.ts +2 −2
| @@ -1179,7 +1179,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1179 | 1179 | { |
| 1180 | 1180 | name: "milestones", |
| 1181 | 1181 | description: |
| 1182 | "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.", | |
| 1182 | "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.", | |
| 1183 | 1183 | inputSchema: { |
| 1184 | 1184 | type: "object", |
| 1185 | 1185 | properties: { |
| @@ -1333,7 +1333,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1333 | 1333 | { |
| 1334 | 1334 | name: "returns", |
| 1335 | 1335 | description: |
| 1336 | "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.", | |
| 1336 | "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.", | |
| 1337 | 1337 | inputSchema: { |
| 1338 | 1338 | type: "object", |
| 1339 | 1339 | properties: { |
src/tui/screens/limbs.ts +48 −6
| @@ -8,7 +8,9 @@ | ||
| 8 | 8 | * verb `place`. What the screen decides is only what to draw and which keys |
| 9 | 9 | * exist; the action decides who may. A reader sees the order and no keys to |
| 10 | 10 | * change it, an agent likewise, and a guest sees what `canRead` lets the web |
| 11 | * show — the plan is read without the owner's spend. | |
| 11 | * show — the plan is read without the owner's spend. The one owner fact is | |
| 12 | * the page's **What it cost** for the limb in focus, as one line, read by | |
| 13 | * `limbReturns` and so gated where the page is gated (#1067). | |
| 12 | 14 | * |
| 13 | 15 | * `enter` on a limb that has limbs of its own opens them, so a milestone's |
| 14 | 16 | * sub-limbs can be moved among themselves (the `under` of the action). |
| @@ -18,8 +20,10 @@ | ||
| 18 | 20 | |
| 19 | 21 | import { undoFleetOp } from "../../actions/fleet.ts"; |
| 20 | 22 | import { applyLimb, previewLimb, type LimbPreview } from "../../actions/limbs.ts"; |
| 23 | import { limbReturns } from "../../actions/returns.ts"; | |
| 21 | 24 | import { canAdmin, canRead, type Repo } from "../../core/repos.ts"; |
| 22 | import { readPlan, type Limb } from "../../core/milestones.ts"; | |
| 25 | import { readPlan, type Limb, type Plan } from "../../core/milestones.ts"; | |
| 26 | import type { Returns } from "../../core/returns.ts"; | |
| 23 | 27 | import type { Ctx, Screen } from "../app/app.ts"; |
| 24 | 28 | import { binding } from "../app/keys.ts"; |
| 25 | 29 | import { fill, len, split } from "../ui/layout.ts"; |
| @@ -44,8 +48,7 @@ const LIVE_KINDS = ["limb.moved", "issue.opened", "issue.closed", "issue.reopene | ||
| 44 | 48 | const SHOWN = 6; |
| 45 | 49 | |
| 46 | 50 | /** The limbs of `group` (`top`, or a milestone's number), in their set order. */ |
| 47 | function limbsOf(f: Session, repo: Repo, group: string): Limb[] | undefined { | |
| 48 | const plan = readPlan(f.db, repo); | |
| 51 | function limbsOf(f: Session, repo: Repo, group: string, plan = readPlan(f.db, repo)): Limb[] | undefined { | |
| 49 | 52 | if (group === "top") return [...plan.limbs]; |
| 50 | 53 | const milestone = plan.milestone(Number(group)); |
| 51 | 54 | return milestone === undefined ? undefined : [...milestone.limbs]; |
| @@ -53,6 +56,20 @@ function limbsOf(f: Session, repo: Repo, group: string): Limb[] | undefined { | ||
| 53 | 56 | |
| 54 | 57 | const line = (n: number, title: string): string => `#${n} ${title}`; |
| 55 | 58 | |
| 59 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 60 | ||
| 61 | /** The milestone page's **What it cost**, as one line. */ | |
| 62 | export function costLine(r: Returns): string { | |
| 63 | if (r.spent.runs === 0) return "What it cost: no run of the crew's has worked on it"; | |
| 64 | const nothing = r.landedNothing; | |
| 65 | return [ | |
| 66 | `What it cost: ${usd(r.spent.usd)} over ${plural(r.spent.runs, "run")}`, | |
| 67 | `${plural(r.landed, "change")} landed`, | |
| 68 | `${usd(nothing.closed.usd)} closed with nothing`, | |
| 69 | `${usd(nothing.open.usd)} still open`, | |
| 70 | ].join(" · "); | |
| 71 | } | |
| 72 | ||
| 56 | 73 | /** What a preview says before anything is written, as dialog lines. */ |
| 57 | 74 | function previewLines(p: LimbPreview): string[] { |
| 58 | 75 | const out: string[] = ["New order:"]; |
| @@ -88,6 +105,9 @@ export function limbsScreen( | ||
| 88 | 105 | ): Screen { |
| 89 | 106 | const state = new ListState(); |
| 90 | 107 | let limbs: Limb[] = []; |
| 108 | let plan: Plan | undefined; | |
| 109 | /** What each limb cost, read once per load and only for the one in focus. */ | |
| 110 | const costs = new Map<number, Returns | undefined>(); | |
| 91 | 111 | let loaded = false; |
| 92 | 112 | /** The receipt of the last move made here, which `u` reverses once. */ |
| 93 | 113 | let last: string | undefined; |
| @@ -98,11 +118,15 @@ export function limbsScreen( | ||
| 98 | 118 | const reload = (follow?: number): void => { |
| 99 | 119 | if (!canRead(f.db, repo, f.user)) { |
| 100 | 120 | limbs = []; |
| 121 | plan = undefined; | |
| 122 | costs.clear(); | |
| 101 | 123 | loaded = true; |
| 102 | 124 | ctx.invalidate(); |
| 103 | 125 | return; |
| 104 | 126 | } |
| 105 | limbs = limbsOf(f, repo, group) ?? []; | |
| 127 | plan = readPlan(f.db, repo); | |
| 128 | costs.clear(); | |
| 129 | limbs = limbsOf(f, repo, group, plan) ?? []; | |
| 106 | 130 | loaded = true; |
| 107 | 131 | if (follow !== undefined) { |
| 108 | 132 | const at = limbs.findIndex((l) => l.issue.number === follow); |
| @@ -114,6 +138,21 @@ export function limbsScreen( | ||
| 114 | 138 | |
| 115 | 139 | const current = (): Limb | undefined => limbs[state.index]; |
| 116 | 140 | |
| 141 | /** The focused limb's cost for a viewer with the owner facts; nothing for anyone else. */ | |
| 142 | const cost = (): Returns | undefined => { | |
| 143 | const limb = current(); | |
| 144 | if (limb === undefined || plan === undefined) return undefined; | |
| 145 | const number = limb.issue.number; | |
| 146 | if (!costs.has(number)) { | |
| 147 | const rows = plan.limb(number); | |
| 148 | costs.set( | |
| 149 | number, | |
| 150 | rows === undefined ? undefined : limbReturns(f.app, f.user, repo, [...rows.own, ...rows.shared]), | |
| 151 | ); | |
| 152 | } | |
| 153 | return costs.get(number); | |
| 154 | }; | |
| 155 | ||
| 117 | 156 | const move = (action: "raise" | "lower"): void => { |
| 118 | 157 | const limb = current(); |
| 119 | 158 | if (limb === undefined || !may()) return; |
| @@ -203,7 +242,8 @@ export function limbsScreen( | ||
| 203 | 242 | }, |
| 204 | 243 | render(area, s) { |
| 205 | 244 | const c = ctx.theme.c; |
| 206 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 245 | const spent = cost(); | |
| 246 | const [head, list, foot] = split(area, "v", [len(1), fill(1), len(spent === undefined ? 0 : 1)]); | |
| 207 | 247 | const note = !loaded |
| 208 | 248 | ? "Loading…" |
| 209 | 249 | : limbs.length === 0 |
| @@ -211,6 +251,8 @@ export function limbsScreen( | ||
| 211 | 251 | : `${plural(limbs.length, "limb")} in the order the crew takes ready work${may() ? "" : " · you can read this order, not change it"}`; |
| 212 | 252 | s.text(head!.x, head!.y, truncate(note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 213 | 253 | drawList(s, list!, c, state, rows()); |
| 254 | if (spent !== undefined && foot!.h > 0) | |
| 255 | s.text(foot!.x, foot!.y, truncate(costLine(spent), foot!.w), style(c.mutedFg, c.bg), foot!.x + foot!.w); | |
| 214 | 256 | hitList(ctx, list!, state, limbs.length, { open }); |
| 215 | 257 | }, |
| 216 | 258 | key(e) { |
src/web/pages/milestones.ts +94 −9
| @@ -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. |
| @@ -24,6 +26,8 @@ import { parseSeat, seating } from "../../core/limb_seats.ts"; | ||
| 24 | 26 | import type { Issue } from "../../core/issues.ts"; |
| 25 | 27 | import type { User } from "../../core/users.ts"; |
| 26 | 28 | import type { LimbAction } from "../../actions/limbs.ts"; |
| 29 | import { limbReturns } from "../../actions/returns.ts"; | |
| 30 | import type { Returns } from "../../core/returns.ts"; | |
| 27 | 31 | import { |
| 28 | 32 | type AskToLive, |
| 29 | 33 | isStructural, |
| @@ -50,6 +54,7 @@ import { field, readForm } from "../form.ts"; | ||
| 50 | 54 | import { page, redirect } from "../layout.ts"; |
| 51 | 55 | import { liveClientJs, liveMount } from "../live.ts"; |
| 52 | 56 | import { btn, time } from "../ui.ts"; |
| 57 | import { usd } from "./board.ts"; | |
| 53 | 58 | |
| 54 | 59 | /** Where a milestone is: its own page. */ |
| 55 | 60 | export const milestoneHref = (base: string, number: number): string => |
| @@ -268,11 +273,57 @@ function watchButton(base: string, m: Milestone, watching: boolean): Html { | ||
| 268 | 273 | </form>`; |
| 269 | 274 | } |
| 270 | 275 | |
| 276 | /** How many of a limb's costliest issues its page names. */ | |
| 277 | const COSTLIEST = 5; | |
| 278 | ||
| 279 | const OUTCOME_WORDS = { | |
| 280 | landed: "landed", | |
| 281 | closed: "closed with nothing merged", | |
| 282 | open: "nothing merged yet", | |
| 283 | } as const; | |
| 284 | ||
| 285 | /** What the limb has cost and landed since it began: owner facts only. */ | |
| 286 | function costSection(base: string, r: Returns): Html { | |
| 287 | const nothing = r.landedNothing; | |
| 288 | return html`<section class="ms-section" id="ms-cost"> | |
| 289 | <h2>What it cost</h2> | |
| 290 | ${r.spent.runs === 0 | |
| 291 | ? html`<p class="muted small">No run of the crew's has worked on it.</p>` | |
| 292 | : html`<p> | |
| 293 | <b>${usd(r.spent.usd)}</b> over ${r.spent.runs} | |
| 294 | ${r.spent.runs === 1 ? "run" : "runs"} · <b>${r.landed}</b> | |
| 295 | ${r.landed === 1 ? "change" : "changes"} landed${r.landed === 0 | |
| 296 | ? null | |
| 297 | : html` · ${usd(r.spent.usd / r.landed)} a landed change`} | |
| 298 | · ${usd(nothing.closed.usd)} closed with nothing · | |
| 299 | ${usd(nothing.open.usd)} still open | |
| 300 | </p> | |
| 301 | <ul class="ms-rows"> | |
| 302 | ${r.costliest.slice(0, COSTLIEST).map( | |
| 303 | (c) => | |
| 304 | html`<li> | |
| 305 | <a href="${base}/issues/${c.number}">${c.title}</a> | |
| 306 | <span class="muted small" | |
| 307 | >#${c.number} · ${usd(c.usd)} · ${OUTCOME_WORDS[c.outcome]}</span | |
| 308 | > | |
| 309 | </li>`, | |
| 310 | )} | |
| 311 | </ul> | |
| 312 | <p class="muted small"> | |
| 313 | Since the limb began: the crew's runs on anything in it, or on a | |
| 314 | change that closes it — a run on another issue whose change closes | |
| 315 | one here counts toward the issue here. A landed change's cost is | |
| 316 | all of it over the changes it landed, waste included. | |
| 317 | </p>`} | |
| 318 | </section>`; | |
| 319 | } | |
| 320 | ||
| 271 | 321 | function milestoneBody( |
| 272 | 322 | repo: Repo, |
| 273 | 323 | m: Milestone, |
| 274 | 324 | names: boolean, |
| 275 | 325 | actions: Html | null, |
| 326 | cost: Returns | undefined, | |
| 276 | 327 | move?: Mover, |
| 277 | 328 | ): Html { |
| 278 | 329 | const base = repoBase(repo); |
| @@ -392,6 +443,7 @@ function milestoneBody( | ||
| 392 | 443 | 3, |
| 393 | 444 | )} |
| 394 | 445 | </section> |
| 446 | ${cost === undefined ? null : costSection(base, cost)} | |
| 395 | 447 | ${when( |
| 396 | 448 | open.length > 0 || closed.length > 0 || stillOpen.length === 0, |
| 397 | 449 | () => |
| @@ -446,11 +498,12 @@ export function milestonePage(ctx: Ctx): Response { | ||
| 446 | 498 | if (!repo) return notFoundPage(ctx); |
| 447 | 499 | const number = Number(ctx.params.number); |
| 448 | 500 | const owner = canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user); |
| 449 | const plan = Number.isInteger(number) | |
| 450 | ? readPlan(ctx.app.db, repo, { spend: owner }) | |
| 501 | const plan = readPlan(ctx.app.db, repo, { spend: owner }); | |
| 502 | const milestone = Number.isInteger(number) | |
| 503 | ? plan.milestone(number) | |
| 451 | 504 | : undefined; |
| 452 | const milestone = plan?.milestone(number); | |
| 453 | if (plan === undefined || milestone === undefined) return notFoundPage(ctx); | |
| 505 | if (milestone === undefined) return notFoundPage(ctx); | |
| 506 | const cost = costOf(ctx, repo, plan, number); | |
| 454 | 507 | const viewer = ctx.auth.user; |
| 455 | 508 | // Watch is each person's own; acting on the whole limb is for whoever |
| 456 | 509 | // administers the repository. One row, Watch first. |
| @@ -482,13 +535,29 @@ export function milestonePage(ctx: Ctx): Response { | ||
| 482 | 535 | crumbs: crumbsFor(repo), |
| 483 | 536 | palette: repoPalette(ctx, repo), |
| 484 | 537 | body: html`${repoHeader(ctx, repo, "map")} |
| 485 | ${milestoneBody(repo, milestone, owner, actions, move)} | |
| 538 | ${milestoneBody(repo, milestone, owner, actions, cost, move)} | |
| 486 | 539 | ${liveMount({ repo: repoBase(repo) })}`, |
| 487 | 540 | styleCss: milestonesCss, |
| 488 | 541 | scriptJs: liveClientJs, |
| 489 | 542 | }); |
| 490 | 543 | } |
| 491 | 544 | |
| 545 | /** | |
| 546 | * What a limb cost and landed, for a viewer who holds the owner facts: read | |
| 547 | * by index from the limb's issues and pulls, never the whole run history. | |
| 548 | */ | |
| 549 | function costOf( | |
This is the read the terminal needs as well. The limbs screen in |
||
| 550 | ctx: Ctx, | |
| 551 | repo: Repo, | |
| 552 | plan: Plan, | |
| 553 | number: number, | |
| 554 | ): Returns | undefined { | |
| 555 | const limb = plan.limb(number); | |
| 556 | return limb === undefined | |
| 557 | ? undefined | |
| 558 | : limbReturns(ctx.app, ctx.auth.user, repo, [...limb.own, ...limb.shared]); | |
| 559 | } | |
| 560 | ||
| 492 | 561 | /** POST /:owner/:name/milestones/:number/watch — watch, or stop, and back to it. */ |
| 493 | 562 | export async function milestoneWatch(ctx: Ctx): Promise<Response> { |
| 494 | 563 | const repo = loadRepo(ctx); |
| @@ -560,15 +629,31 @@ export async function milestoneData( | ||
| 560 | 629 | number: number, |
| 561 | 630 | ): Promise<Record<string, unknown> | undefined> { |
| 562 | 631 | const owner = canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user); |
| 563 | const milestone = readPlan(ctx.app.db, repo, { spend: owner }).milestone( | |
| 564 | number, | |
| 565 | ); | |
| 632 | const plan = readPlan(ctx.app.db, repo, { spend: owner }); | |
| 633 | const milestone = plan.milestone(number); | |
| 566 | 634 | const viewer = ctx.auth.user; |
| 635 | const cost = | |
| 636 | milestone === undefined ? undefined : costOf(ctx, repo, plan, number); | |
| 567 | 637 | return milestone === undefined |
| 568 | 638 | ? undefined |
| 569 | 639 | : { |
| 570 | 640 | repo: { owner: repo.ownerName, name: repo.name }, |
| 571 | 641 | ...milestoneJson(milestone, owner), |
| 642 | // What the limb cost and landed since it began: owner facts only. | |
| 643 | ...(cost === undefined | |
| 644 | ? {} | |
| 645 | : { | |
| 646 | returns: { | |
| 647 | spent: cost.spent, | |
| 648 | landed: cost.landed, | |
| 649 | onLanded: cost.onLanded, | |
| 650 | closed: cost.landedNothing.closed, | |
| 651 | open: cost.landedNothing.open, | |
| 652 | costliest: cost.costliest | |
| 653 | .slice(0, COSTLIEST) | |
| 654 | .map(({ repoId: _, ...c }) => c), | |
| 655 | }, | |
| 656 | }), | |
| 572 | 657 | ...askOf(await askByUmbrella(ctx, repo, number), number), |
| 573 | 658 | // Whether the caller watches it; a caller who cannot has no answer. |
| 574 | 659 | ...(viewer?.kind === "user" |
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 | }); |
test/tui-limbs.test.ts +38
| @@ -19,6 +19,7 @@ import { createApp, type App as Forge } from "../src/app.ts"; | ||
| 19 | 19 | import { listEvents } from "../src/core/events.ts"; |
| 20 | 20 | import { getIssueById, type Issue } from "../src/core/issues.ts"; |
| 21 | 21 | import { readPlan } from "../src/core/milestones.ts"; |
| 22 | import { createRun } from "../src/core/runs.ts"; | |
| 22 | 23 | import { getRepoById, type Repo } from "../src/core/repos.ts"; |
| 23 | 24 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 24 | 25 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -210,6 +211,43 @@ describe("raise and lower a limb in the terminal", () => { | ||
| 210 | 211 | g.stop(); |
| 211 | 212 | }); |
| 212 | 213 | |
| 214 | test("the owner sees what the limb in focus cost; a reader and a guest do not", async () => { | |
| 215 | // Worked by hand: two runs on the Trust leaf, $1.25 and $0.50, nothing | |
| 216 | // merged and the leaf still open → $1.75 over 2 runs, 0 landed, $1.75 open. | |
| 217 | for (const usd of [1.25, 0.5]) { | |
| 218 | const leaf = readPlan(forge.db, getRepoById(forge.db, repo.id)!).limb(trust.number)!.own.find( | |
| 219 | (i) => i.title === "A trust leaf", | |
| 220 | )!; | |
| 221 | const made = createRun(forge.db, { | |
| 222 | repoId: repo.id, | |
| 223 | kind: "agent", | |
| 224 | issueId: leaf.id, | |
| 225 | branch: "", | |
| 226 | actorId: alice.id, | |
| 227 | reason: "assigned", | |
| 228 | }); | |
| 229 | forge.db.query("UPDATE run SET state = 'ok', cost_usd = ?2 WHERE id = ?1").run(made.id, usd); | |
| 230 | } | |
| 231 | const h = boot(alice); | |
| 232 | await h.toMilestones("alice/order"); | |
| 233 | expect(h.text()).toContain( | |
| 234 | "What it cost: $1.75 over 2 runs · 0 changes landed · $0.00 closed with nothing · $1.75 still open", | |
| 235 | ); | |
| 236 | // The line follows the focus: Feed has had no run. | |
| 237 | await h.press("j"); | |
| 238 | expect(h.text()).toContain("What it cost: no run of the crew's has worked on it"); | |
| 239 | h.stop(); | |
| 240 | ||
| 241 | for (const who of [bob, undefined]) { | |
| 242 | const r = boot(who); | |
| 243 | await r.toMilestones("alice/order"); | |
| 244 | expect(r.text()).toContain("Trust"); | |
| 245 | expect(r.text()).not.toContain("What it cost"); | |
| 246 | expect(r.text()).not.toContain("$1.75"); | |
| 247 | r.stop(); | |
| 248 | } | |
| 249 | }); | |
| 250 | ||
| 213 | 251 | test("the milestones page carries the live client and hears limb.moved", async () => { |
| 214 | 252 | const res = await fetch(`${servers.url}/alice/order/milestones`); |
| 215 | 253 | const body = await res.text(); |
new above
offline
Once the terminal shows it, say where it is (the limbs screen) in this paragraph, so both doors are documented.