Public: anyone can read this; the crew can change it.
Model review moves a crew member up only on that model's own better outcomes; scorecard by kind; rework and no-account lines on /crew #16817
Check · Review · Land · Live done — Landed and live in production.
crew/model-scorecard → main 0 commits
16 files
changed +521
−32
- docs/features/crew-spend-by-kind.md
- docs/features/model-review.md
- src/actions/model_review.ts
- src/actions/scorecard.ts
- src/contract/openapi/routes/getApiV1CrewScorecard.ts
- src/contract/openapi/routes/getApiV1CrewWeek.ts
- src/core/model_review.ts
- src/crew/week_card.ts
- src/http/api.ts
- src/http/mcp/tools/crew.ts
- src/tui/screens/weekcard.ts
- src/web/pages/crew.ts
- test/crew-week-card.test.ts
- test/mcp-scorecard-decide.test.ts
- test/model-review.test.ts
- test/tui-model-review.test.ts
docs/features/crew-spend-by-kind.md added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | --- | |
| 2 | topic: Bring your own AI | |
| 3 | row: Where the crew's money goes, by kind of work, and the runs that found no account | |
| 4 | --- | |
| 5 | # Crew spend by kind of work | |
| 6 | ||
| 7 | Every agent run has a reason, and the reason says what kind of work it was: **build** (an assigned issue), **rework** (review feedback, a red check, a conflict), **review**, **plan** (any run by an agent seated as planner on that repository), or **other**. The forge reads the last 14 days of runs by kind, model and account, and what became of the pulls they worked on: merged, green on their first check, reverted. Cost per merged pull is shown only for a row with 20 merged pulls or more, so no decision rests on a handful. | |
| 8 | ||
| 9 | - **Settings → Crew** (`src/web/pages/crew.ts`): under "This week", two facts: "Spent in 14 days" ($2,380: 46% rework, 41% build, 13% review) and "Runs with no account" (agent runs that failed before they reached an account), with the reason given most and a link to add or allow an account. Below the model review, "By kind of work · 14 days" lists each kind × model × account: runs, spent, merged of pulls, green first, per merged. | |
| 10 | - **The terminal** (`src/tui/screens/weekcard.ts`): "Crew this week" lists the same two facts and the same rows after the members. | |
| 11 | - **API and MCP**: `GET /api/v1/crew/week` and MCP `crew` { kind: "week" } carry `spend` ({ days, totalUsd, byKind, reworkShare, noAccount }); `GET /api/v1/crew/scorecard` and MCP `scorecard` carry `byKind`. A forge admin's. | |
| 12 | ||
| 13 | What to do with it: a high rework share points at review feedback and red checks, not at the model; runs with no account point at Settings → Subscriptions. The weekly model review (model-review.md) reads the same ledger and asks for a dearer model only when that model's own pulls did clearly better. | |
| 14 | ||
| 15 | Proof: `test/model-review.test.ts`, `test/crew-week-card.test.ts`. The reads are `kindStats` and `KIND_SQL` (`src/core/model_review.ts`) and `weekSpend`, `spendFacts` (`src/crew/week_card.ts`). |
docs/features/model-review.md +2 −2
| @@ -4,9 +4,9 @@ row: The weekly model review | ||
| 4 | 4 | --- |
| 5 | 5 | # The weekly model review |
| 6 | 6 | |
| 7 | Once a week (`runModelReview`, ticked hourly from `src/main.ts`, runs at most once in seven days) the forge reads its ledger and, per crew member, compares the models it ran on over the last 28 days: cost per landed pull (every agent run on a pull counts), red first-check rate, change-request rounds per landed pull, reverts, and how hard the work was (share of pulls that escalated by need: `p0`, `label:opus`). The figures are on Settings → Crew ("Model review"), in `GET /api/v1/crew/scorecard` and the `scorecard` MCP tool (`modelReview`). | |
| 7 | Once a week (`runModelReview`, ticked hourly from `src/main.ts`, runs at most once in seven days) the forge reads its ledger and, per crew member, compares the models it ran on over the last 28 days: cost per landed pull (every agent run on a pull counts), pulls green on their first check, red check rate, change-request rounds per landed pull, reverts, and how hard the work was (share of pulls that escalated by need: `p0`, `label:opus`). The figures are on Settings → Crew ("Model review"), in `GET /api/v1/crew/scorecard` and the `scorecard` MCP tool (`modelReview`). | |
| 8 | 8 | |
| 9 | - **Plain code** (`src/core/model_review.ts`): the ladder is fable → opus → sonnet → haiku. A model with reverts, a rework round per landed pull, or half its checks red is asked a step *up*. A healthy one is proposed a step *down*, unless over half its work was hard, or the cheaper model has its own numbers and they are no better. | |
| 9 | - **Plain code** (`src/core/model_review.ts`): the ladder is fable → opus → sonnet → haiku. A model with reverts, a rework round per landed pull, or half its checks red is asked a step *up* only when the dearer model's own pulls by that member did clearly better: more green on their first check, or fewer reverted, with the 95% Wilson intervals apart, and no worse on the rest. Otherwise it holds and says both models' numbers. An ask the review would no longer make is held at the next tick, with the numbers (`crew.model_declined`, `held`). A healthy one is proposed a step *down*, unless over half its work was hard, or the cheaper model has its own numbers and they are no better. | |
| 10 | 10 | - **At most one change per agent per week** (a change just settled counts), and none while one waits for a person or for its result. A change, its trail row and its event are written in one transaction. |
| 11 | 11 | - **Small samples change nothing**: under `model_review.min_landed` landed pulls (default 8) the page says so. |
| 12 | 12 | - **Applies itself or asks**: a step down applies on its own when the owner sets the limit `model_review.auto` to 1 (default 0); a step up always asks. Asking is one button on the page ("Move to …" / "Leave it") and, in the terminal's "Crew scorecard per agent", `m` / `n` on a `waiting` row, then `y` (both call `decideChange`, a forge admin's only). An ask nobody answers lapses after two weeks as declined, and frees the agent. |
src/actions/model_review.ts +30 −8
| @@ -23,6 +23,7 @@ import { | ||
| 23 | 23 | type Limits, |
| 24 | 24 | type ModelChange, |
| 25 | 25 | type ModelStats, |
| 26 | statsLine, | |
| 26 | 27 | type Verdict, |
| 27 | 28 | } from "../core/model_review.ts"; |
| 28 | 29 | import type { User } from "../core/users.ts"; |
| @@ -37,13 +38,8 @@ export function reviewLimits(app: App): Limits & { auto: boolean } { | ||
| 37 | 38 | }; |
| 38 | 39 | } |
| 39 | 40 | |
| 40 | const pctOf = (n: number | null) => (n === null ? "no checks" : `${Math.round(100 * n)}% red`); | |
| 41 | const usd = (n: number | null) => (n === null ? "—" : `$${n.toFixed(2)}`); | |
| 42 | const figures = (s: ModelStats) => | |
| 43 | `${s.landed} landed at ${usd(s.costPerLanded)} each, ${pctOf(s.redRate)}, ${(s.reworkRounds ?? 0).toFixed(1)} rework rounds, ${s.reverts} reverted`; | |
| 44 | ||
| 45 | 41 | const empty = (model: string): ModelStats => ({ |
| 46 | model, opened: 0, landed: 0, costPerLanded: null, redRate: null, reworkRounds: null, reverts: 0, hardShare: null, | |
| 42 | model, opened: 0, landed: 0, costPerLanded: null, redRate: null, reworkRounds: null, reverts: 0, hardShare: null, checked: 0, firstGreen: 0, | |
| 47 | 43 | }); |
| 48 | 44 | |
| 49 | 45 | /** What the review says now for each member, without changing anything. */ |
| @@ -105,8 +101,31 @@ export function decideChange( | ||
| 105 | 101 | /** A week on, say how a change went and undo it if quality fell. */ |
| 106 | 102 | export function settleChanges(app: App, now = new Date()): void { |
| 107 | 103 | const limits = reviewLimits(app); |
| 104 | let stats: Map<string, ModelStats[]> | undefined; | |
| 105 | /** What the review says of a member now; read once a tick, and only when an ask is waiting. */ | |
| 106 | const verdictNow = (agentId: string): Verdict | undefined => { | |
| 107 | const agent = getAgent(app.db, agentId); | |
| 108 | if (agent === undefined) return undefined; | |
| 109 | stats ??= modelStats(app.db, new Date(now.getTime() - REVIEW_DAYS * 86_400_000)); | |
| 110 | return review(agent.model, stats.get(agentId) ?? [], limits); | |
| 111 | }; | |
| 108 | 112 | for (const change of listChanges(app.db, undefined, 500)) { |
| 109 | 113 | if (change.state === "asked") { |
| 114 | // An ask the review would no longer make is held, with today's numbers, so nobody takes it | |
| 115 | // on the reason it was asked for: the numbers moved, or a step up asked on poor numbers | |
| 116 | // alone that the dearer model's own pulls do not bear out. | |
| 117 | const verdict = verdictNow(change.agentId); | |
| 118 | if (verdict !== undefined && !(verdict.kind === "propose" && verdict.to.toLowerCase() === change.toModel.toLowerCase())) { | |
| 119 | const held = `held: ${verdict.kind === "hold" ? verdict.note : `the review would now ask for ${verdict.to} instead`}`; | |
| 120 | app.db.transaction(() => { | |
| 121 | setState(app.db, change.id, { state: "declined", settledAt: now, result: held }); | |
| 122 | app.bus.append({ | |
| 123 | kind: "crew.model_declined", | |
| 124 | payload: { agent: nameOf(app, change.agentId), from: change.fromModel, to: change.toModel, held }, | |
| 125 | }); | |
| 126 | })(); | |
| 127 | continue; | |
| 128 | } | |
| 110 | 129 | // One ignored ask must not block the agent for ever: after two weeks it lapses as declined. |
| 111 | 130 | if (now.getTime() - new Date(change.createdAt).getTime() < GIVE_UP_MS) continue; |
| 112 | 131 | app.db.transaction(() => { |
| @@ -143,9 +162,12 @@ export function settleChanges(app: App, now = new Date()): void { | ||
| 143 | 162 | } else if (after.landed < limits.minLanded) { |
| 144 | 163 | if (age >= GIVE_UP_MS) finish("kept", `only ${after.landed} landed on ${change.toModel} in two weeks, too few to judge; kept`); |
| 145 | 164 | } else if (fellShort(change.before, after, limits)) { |
| 146 | finish("undone", `quality fell on ${change.toModel} (${figures(after)}; before ${figures(change.before)}); back to ${change.fromModel}`); | |
| 165 | finish( | |
| 166 | "undone", | |
| 167 | `quality fell on ${change.toModel} (${statsLine(after)}; before ${statsLine(change.before)}); back to ${change.fromModel}`, | |
| 168 | ); | |
| 147 | 169 | } else { |
| 148 | finish("kept", `held on ${change.toModel} (${figures(after)}; before ${figures(change.before)})`); | |
| 170 | finish("kept", `held on ${change.toModel} (${statsLine(after)}; before ${statsLine(change.before)})`); | |
| 149 | 171 | } |
| 150 | 172 | } |
| 151 | 173 | } |
src/actions/scorecard.ts +4
| @@ -12,6 +12,7 @@ import { | ||
| 12 | 12 | type SplitScorecard, |
| 13 | 13 | } from "../core/scorecard.ts"; |
| 14 | 14 | import { modelDays, type ModelDay } from "../core/model_days.ts"; |
| 15 | import { kindStats, type KindStats } from "../core/model_review.ts"; | |
| 15 | 16 | import { readReview } from "./model_review.ts"; |
| 16 | 17 | import { wastedDays, type WastedDay } from "../core/wasted_days.ts"; |
| 17 | 18 | import { listAgents } from "../core/agents.ts"; |
| @@ -53,6 +54,8 @@ export function readScorecards( | ||
| 53 | 54 | wastedDays: WastedDay[]; |
| 54 | 55 | keeperDays: KeeperDay[]; |
| 55 | 56 | modelReview: ReturnType<typeof readReview>; |
| 57 | /** The last `KIND_DAYS` by kind of work × model × account (`core/model_review.ts`). */ | |
| 58 | byKind: KindStats[]; | |
| 56 | 59 | } | undefined { |
| 57 | 60 | if (actor?.isAdmin !== true) return undefined; |
| 58 | 61 | const window = recentWindow(); |
| @@ -67,6 +70,7 @@ export function readScorecards( | ||
| 67 | 70 | // Hours the forge ran and pulls landed, per UTC day of the last week (#7645). |
| 68 | 71 | keeperDays: keeperDays(app.db, new Date()), |
| 69 | 72 | modelReview: readReview(app), |
| 73 | byKind: kindStats(app.db), | |
| 70 | 74 | wastedDays: wastedDays(app.db), |
| 71 | 75 | agents: listAgents(app.db).map((agent) => { |
| 72 | 76 | const id = agent.user.id; |
src/contract/openapi/routes/getApiV1CrewScorecard.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "get", |
| 5 | 5 | path: "/api/v1/crew/scorecard", |
| 6 | 6 | summary: "Read the crew's scorecard", |
| 7 | detail: "Read the crew's scorecard (a forge admin's, any token scope): { agents: [{ username, all, recent, splits }] }, where all and recent are { opened, landed, reviewRounds, redCheckRate, reverts, meanLandMs } or null, and each split adds model, prompt and its own recent; also modelDays (runs, landed and spend per model per day) and wastedDays: [{ day, wasted, runs, spentUsd }], the runs that ended on work not theirs to do", | |
| 7 | detail: "Read the crew's scorecard (a forge admin's, any token scope): { agents: [{ username, all, recent, splits }] }, where all and recent are { opened, landed, reviewRounds, redCheckRate, reverts, meanLandMs } or null, and each split adds model, prompt and its own recent; also modelDays (runs, landed and spend per model per day) and wastedDays: [{ day, wasted, runs, spentUsd }], the runs that ended on work not theirs to do; and byKind: the last 14 days of agent runs by kind of work (build, rework, review, plan, other) × model × account: [{ kind, model, account, runs, spentUsd, pulls, merged, checked, firstGreen, reverted, perMergedUsd }], perMergedUsd null under 20 merged", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "admin", |
| 10 | 10 | refusals: { unauthorized: "no valid credentials were sent", forbidden: "the caller is not a forge admin" }, |
src/contract/openapi/routes/getApiV1CrewWeek.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "get", |
| 5 | 5 | path: "/api/v1/crew/week", |
| 6 | 6 | summary: "Read the crew's last 7 days", |
| 7 | detail: "Read the crew's last 7 days (a forge admin's, any token scope): { days, members: [{ username, merged, returned, spentUsd, idle }] }, merged pulls, pulls returned by review and ledger spend per agent; idle is true when all three are nothing", | |
| 7 | detail: "Read the crew's last 7 days (a forge admin's, any token scope): { days, members: [{ username, merged, returned, spentUsd, idle }] }, merged pulls, pulls returned by review and ledger spend per agent; idle is true when all three are nothing; and spend: { days, totalUsd, byKind: { build, rework, review, plan, other }, reworkShare, noAccount: { runs, most } } over the last 14 days, noAccount being the agent runs that failed before reaching an account and the reason given most", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "admin", |
| 10 | 10 | refusals: { unauthorized: "no valid credentials were sent", forbidden: "the caller is not a forge admin" }, |
src/core/model_review.ts +190 −4
| @@ -9,6 +9,12 @@ | ||
| 9 | 9 | * took three tries costs three. A pull is hard when a run on it escalated by |
| 10 | 10 | * need (`p0`, `label:opus`), so a model is not judged on work it was not given. |
| 11 | 11 | * |
| 12 | * Outcomes, not thresholds, move a model up: a dearer model is asked for only | |
| 13 | * when its own pulls by the same member did clearly better — beyond the 95% | |
| 14 | * Wilson interval of each — and never on the current model's poor numbers | |
| 15 | * alone (`clearlyBetter`). `kindStats` reads the same ledger by kind of work | |
| 16 | * (build, rework, review, plan), model and account. | |
| 17 | * | |
| 12 | 18 | * Pure data and SQL: no authz, no events (`actions/model_review.ts` has them). |
| 13 | 19 | */ |
| 14 | 20 | import type { Database } from "bun:sqlite"; |
| @@ -40,6 +46,10 @@ export interface ModelStats { | ||
| 40 | 46 | readonly reverts: number; |
| 41 | 47 | /** Share of opened pulls that were hard; null with none opened. */ |
| 42 | 48 | readonly hardShare: number | null; |
| 49 | /** Opened pulls with a finished check. */ | |
| 50 | readonly checked: number; | |
| 51 | /** Of those, the pulls whose first finished check passed: one per pull, never per retry. */ | |
| 52 | readonly firstGreen: number; | |
| 43 | 53 | } |
| 44 | 54 | |
| 45 | 55 | export interface Limits { |
| @@ -56,6 +66,7 @@ interface PullRow { | ||
| 56 | 66 | rounds: number; |
| 57 | 67 | ok: number; |
| 58 | 68 | failed: number; |
| 69 | first_green: number; | |
| 59 | 70 | reverted: number; |
| 60 | 71 | cost: number; |
| 61 | 72 | hard: number; |
| @@ -80,6 +91,9 @@ export function modelStats( | ||
| 80 | 91 | AND run.kind = 'check' AND run.state = 'ok') AS ok, |
| 81 | 92 | (SELECT COUNT(*) FROM run WHERE run.issue_id = issue.id |
| 82 | 93 | AND run.kind = 'check' AND run.state = 'failed') AS failed, |
| 94 | COALESCE((SELECT run.state FROM run WHERE run.issue_id = issue.id | |
| 95 | AND run.kind = 'check' AND run.state IN ('ok', 'failed') | |
| 96 | ORDER BY run.id LIMIT 1) = 'ok', 0) AS first_green, | |
| 83 | 97 | (pull.merged_at IS NOT NULL AND EXISTS (SELECT 1 FROM pull AS back |
| 84 | 98 | WHERE back.reverts_issue_id = issue.id AND back.merged_at IS NOT NULL)) AS reverted, |
| 85 | 99 | COALESCE((SELECT SUM(run.cost_usd) FROM run WHERE run.issue_id = issue.id |
| @@ -116,6 +130,8 @@ export function modelStats( | ||
| 116 | 130 | landed === 0 ? null : sum((r) => (r.landed === 1 ? r.rounds : 0)) / landed, |
| 117 | 131 | reverts: sum((r) => r.reverted), |
| 118 | 132 | hardShare: sum((r) => r.hard) / list.length, |
| 133 | checked: sum((r) => (r.ok + r.failed > 0 ? 1 : 0)), | |
| 134 | firstGreen: sum((r) => r.first_green), | |
| 119 | 135 | }; |
| 120 | 136 | const mine = out.get(first.author_id) ?? []; |
| 121 | 137 | mine.push(stats); |
| @@ -136,6 +152,47 @@ export type Verdict = | ||
| 136 | 152 | |
| 137 | 153 | const pct = (n: number | null) => (n === null ? "no checks" : `${Math.round(100 * n)}% red`); |
| 138 | 154 | const usd = (n: number | null) => (n === null ? "—" : `$${n.toFixed(2)}`); |
| 155 | const green = (s: ModelStats) => | |
| 156 | s.checked === 0 ? "no first checks" : `${Math.round((100 * s.firstGreen) / s.checked)}% green first time`; | |
| 157 | ||
| 158 | /** | |
| 159 | * A model's numbers in one line: the verdict, the ask, its result and the page say the same words. | |
| 160 | */ | |
| 161 | export function statsLine(s: ModelStats): string { | |
| 162 | const rework = (s.reworkRounds ?? 0).toFixed(1); | |
| 163 | return ( | |
| 164 | `${s.landed} landed at ${usd(s.costPerLanded)} each, ${green(s)}, ${pct(s.redRate)}, ` + | |
| 165 | `${rework} rework rounds, ${s.reverts} reverted` | |
| 166 | ); | |
| 167 | } | |
| 168 | ||
| 169 | /** | |
| 170 | * The Wilson score interval of k in n at 95%: where the true rate lies; all of [0, 1] with none. | |
| 171 | */ | |
| 172 | export function wilson(k: number, n: number, z = 1.96): { readonly lo: number; readonly hi: number } { | |
| 173 | if (n <= 0) return { lo: 0, hi: 1 }; | |
| 174 | const p = k / n; | |
| 175 | const z2 = z * z; | |
| 176 | const d = 1 + z2 / n; | |
| 177 | const mid = (p + z2 / (2 * n)) / d; | |
| 178 | const half = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / d; | |
| 179 | return { lo: Math.max(0, mid - half), hi: Math.min(1, mid + half) }; | |
| 180 | } | |
| 181 | ||
| 182 | /** | |
| 183 | * Whether `there`'s own pulls did clearly better than `mine`: more green on their first check, or | |
| 184 | * fewer of the landed reverted, with the two intervals apart — and no worse on the rest by the | |
| 185 | * slack `fellShort` allows. A gap inside the intervals is noise and moves nothing. | |
| 186 | */ | |
| 187 | export function clearlyBetter(there: ModelStats, mine: ModelStats, limits: Limits): boolean { | |
| 188 | if (fellShort(mine, there, limits)) return false; | |
| 189 | const greener = | |
| 190 | there.checked >= limits.minLanded && | |
| 191 | mine.checked >= limits.minLanded && | |
| 192 | wilson(there.firstGreen, there.checked).lo > wilson(mine.firstGreen, mine.checked).hi; | |
| 193 | const steadier = wilson(there.reverts, there.landed).hi < wilson(mine.reverts, mine.landed).lo; | |
| 194 | return greener || steadier; | |
| 195 | } | |
| 139 | 196 | |
| 140 | 197 | /** Whether a model's own numbers are poor enough that a dearer one is worth asking for. */ |
| 141 | 198 | export function unhealthy(s: ModelStats): boolean { |
| @@ -152,11 +209,30 @@ export function review(current: string, stats: readonly ModelStats[], limits: Li | ||
| 152 | 209 | kind: "hold", |
| 153 | 210 | note: `${mine?.landed ?? 0} landed on ${current} in ${REVIEW_DAYS} days; ${limits.minLanded} are needed to judge, so nothing changes`, |
| 154 | 211 | }; |
| 155 | const line = `${mine.landed} landed at ${usd(mine.costPerLanded)} each, ${pct(mine.redRate)}, ${(mine.reworkRounds ?? 0).toFixed(1)} rework rounds, ${mine.reverts} reverted`; | |
| 212 | const line = statsLine(mine); | |
| 156 | 213 | if (unhealthy(mine)) { |
| 157 | 214 | const to = LADDER[at - 1]; |
| 158 | 215 | if (to === undefined) return { kind: "hold", note: `${line}: poor, and already on the top model` }; |
| 159 | return { kind: "propose", to, direction: "up", why: `${current} is not holding its quality (${line})` }; | |
| 216 | // Poor numbers alone never buy a dearer model: its own pulls must show it does better. | |
| 217 | const there = stats.find((s) => s.model.toLowerCase() === to); | |
| 218 | if (there === undefined || there.landed < limits.minLanded) | |
| 219 | return { | |
| 220 | kind: "hold", | |
| 221 | note: | |
| 222 | `${current}: ${line}; ${there?.landed ?? 0} landed on ${to} in ${REVIEW_DAYS} days, ` + | |
| 223 | "too few to show it does better, so it stays", | |
| 224 | }; | |
| 225 | if (!clearlyBetter(there, mine, limits)) | |
| 226 | return { | |
| 227 | kind: "hold", | |
| 228 | note: `${current}: ${line}; ${to}: ${statsLine(there)}: not clearly better on its own pulls, so it stays`, | |
| 229 | }; | |
| 230 | return { | |
| 231 | kind: "propose", | |
| 232 | to, | |
| 233 | direction: "up", | |
| 234 | why: `${to} did clearly better on its own pulls (${statsLine(there)}) than ${current} (${line})`, | |
| 235 | }; | |
| 160 | 236 | } |
| 161 | 237 | const to = LADDER[at + 1]; |
| 162 | 238 | if (to === undefined) return { kind: "hold", note: `${line}: already on the cheapest model` }; |
| @@ -221,6 +297,10 @@ interface ChangeRow { | ||
| 221 | 297 | settled_at: string | null; |
| 222 | 298 | } |
| 223 | 299 | |
| 300 | /** Numbers kept on a change; one written before the first-check counts reads them as none. */ | |
| 301 | const stored = (json: string): ModelStats => | |
| 302 | ({ checked: 0, firstGreen: 0, ...(JSON.parse(json) as Partial<ModelStats>) }) as ModelStats; | |
| 303 | ||
| 224 | 304 | const toChange = (r: ChangeRow): ModelChange => ({ |
| 225 | 305 | id: r.id, |
| 226 | 306 | agentId: r.agent_id, |
| @@ -228,8 +308,8 @@ const toChange = (r: ChangeRow): ModelChange => ({ | ||
| 228 | 308 | toModel: r.to_model, |
| 229 | 309 | state: r.state, |
| 230 | 310 | why: r.why, |
| 231 | before: JSON.parse(r.before_json) as ModelStats, | |
| 232 | after: r.after_json === null ? null : (JSON.parse(r.after_json) as ModelStats), | |
| 311 | before: stored(r.before_json), | |
| 312 | after: r.after_json === null ? null : stored(r.after_json), | |
| 233 | 313 | result: r.result, |
| 234 | 314 | createdAt: r.created_at, |
| 235 | 315 | decidedBy: r.decided_by, |
| @@ -318,3 +398,109 @@ export function lastRun(db: Database): Date | undefined { | ||
| 318 | 398 | export function markRun(db: Database, at: Date): void { |
| 319 | 399 | db.query("INSERT INTO model_review_run (at) VALUES (?1)").run(at.toISOString()); |
| 320 | 400 | } |
| 401 | ||
| 402 | // ---- by kind of work ---- | |
| 403 | ||
| 404 | /** The window the by-kind read covers, in days. */ | |
| 405 | export const KIND_DAYS = 14; | |
| 406 | /** Merged pulls a row needs before its cost per merge is said: no verdict rests on a handful. */ | |
| 407 | export const KIND_MIN_MERGED = 20; | |
| 408 | ||
| 409 | /** | |
| 410 | * What a run was for: its reason, or the planner's seat (`repo_crew.role`), whatever the reason. | |
| 411 | */ | |
| 412 | export type WorkKind = "build" | "rework" | "review" | "plan" | "other"; | |
| 413 | export const WORK_KINDS: readonly WorkKind[] = ["build", "rework", "review", "plan", "other"]; | |
| 414 | /** | |
| 415 | * A run's kind as SQL over `run` joined to its seat as `rc` (`repo_crew`): the one mapping every | |
| 416 | * read uses. | |
| 417 | */ | |
| 418 | export const KIND_SQL = `CASE WHEN rc.role = 'planner' THEN 'plan' | |
| 419 | WHEN run.reason = 'assigned' THEN 'build' | |
| 420 | WHEN run.reason IN ('feedback', 'check_failed', 'conflict') THEN 'rework' | |
| 421 | WHEN run.reason = 'review' THEN 'review' | |
| 422 | ELSE 'other' END`; | |
| 423 | ||
| 424 | export interface KindStats { | |
| 425 | readonly kind: WorkKind; | |
| 426 | /** The model the run itself ran on; empty when unrecorded. */ | |
| 427 | readonly model: string; | |
| 428 | /** The account the run spent; empty when it never reached one. */ | |
| 429 | readonly account: string; | |
| 430 | readonly runs: number; | |
| 431 | readonly spentUsd: number; | |
| 432 | /** | |
| 433 | * Distinct pulls the runs worked on, and of those the merged, the checked, the green on their | |
| 434 | * first check, the reverted. | |
| 435 | */ | |
| 436 | readonly pulls: number; | |
| 437 | readonly merged: number; | |
| 438 | readonly checked: number; | |
| 439 | readonly firstGreen: number; | |
| 440 | readonly reverted: number; | |
| 441 | /** spentUsd ÷ merged once merged reaches `KIND_MIN_MERGED`; null before. */ | |
| 442 | readonly perMergedUsd: number | null; | |
| 443 | } | |
| 444 | ||
| 445 | /** | |
| 446 | * Agent runs created in the `KIND_DAYS` before `now`, by kind of work × model × account, with | |
| 447 | * what became of the pulls they worked on. A run's spend is its own; a pull counts once per row | |
| 448 | * however many of the row's runs touched it. Dearest row first. One query. | |
| 449 | */ | |
| 450 | interface KindRow { | |
| 451 | kind: WorkKind; | |
| 452 | model: string; | |
| 453 | account: string; | |
| 454 | runs: number; | |
| 455 | spent: number; | |
| 456 | pulls: number; | |
| 457 | merged: number; | |
| 458 | checked: number; | |
| 459 | first_green: number; | |
| 460 | reverted: number; | |
| 461 | } | |
| 462 | ||
| 463 | export function kindStats(db: Database, now: Date = new Date()): KindStats[] { | |
| 464 | const since = new Date(now.getTime() - KIND_DAYS * 86_400_000).toISOString(); | |
| 465 | return db | |
| 466 | .query<KindRow, [string]>( | |
| 467 | `WITH r AS ( | |
| 468 | SELECT run.issue_id, run.model, run.cost_usd, COALESCE(s.name, '') AS account, | |
| 469 | ${KIND_SQL} AS kind | |
| 470 | FROM run | |
| 471 | LEFT JOIN subscription s ON s.id = run.subscription_id | |
| 472 | LEFT JOIN repo_crew rc ON rc.repo_id = run.repo_id AND rc.user_id = run.actor_id | |
| 473 | WHERE run.kind = 'agent' AND run.created_at >= ?1 | |
| 474 | ), p AS ( | |
| 475 | SELECT pull.issue_id, pull.merged_at IS NOT NULL AS merged, | |
| 476 | (SELECT c.state FROM run c WHERE c.issue_id = pull.issue_id AND c.kind = 'check' | |
| 477 | AND c.state IN ('ok', 'failed') ORDER BY c.id LIMIT 1) AS first_check, | |
| 478 | EXISTS (SELECT 1 FROM pull b WHERE b.reverts_issue_id = pull.issue_id | |
| 479 | AND b.merged_at IS NOT NULL) AS reverted | |
| 480 | FROM pull WHERE pull.issue_id IN (SELECT issue_id FROM r WHERE issue_id IS NOT NULL) | |
| 481 | ) | |
| 482 | SELECT r.kind, r.model, r.account, COUNT(*) AS runs, COALESCE(SUM(r.cost_usd), 0) AS spent, | |
| 483 | COUNT(DISTINCT p.issue_id) AS pulls, | |
| 484 | COUNT(DISTINCT CASE WHEN p.merged THEN p.issue_id END) AS merged, | |
| 485 | COUNT(DISTINCT CASE WHEN p.first_check IS NOT NULL THEN p.issue_id END) AS checked, | |
| 486 | COUNT(DISTINCT CASE WHEN p.first_check = 'ok' THEN p.issue_id END) AS first_green, | |
| 487 | COUNT(DISTINCT CASE WHEN p.reverted THEN p.issue_id END) AS reverted | |
| 488 | FROM r LEFT JOIN p ON p.issue_id = r.issue_id | |
| 489 | GROUP BY r.kind, r.model, r.account | |
| 490 | ORDER BY spent DESC, r.kind, r.model, r.account`, | |
| 491 | ) | |
| 492 | .all(since) | |
| 493 | .map((r) => ({ | |
| 494 | kind: r.kind, | |
| 495 | model: r.model, | |
| 496 | account: r.account, | |
| 497 | runs: r.runs, | |
| 498 | spentUsd: Math.round(r.spent * 10_000) / 10_000, | |
| 499 | pulls: r.pulls, | |
| 500 | merged: r.merged, | |
| 501 | checked: r.checked, | |
| 502 | firstGreen: r.first_green, | |
| 503 | reverted: r.reverted, | |
| 504 | perMergedUsd: r.merged >= KIND_MIN_MERGED ? Math.round((r.spent / r.merged) * 100) / 100 : null, | |
| 505 | })); | |
| 506 | } |
src/crew/week_card.ts +81
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import type { Database } from "bun:sqlite"; |
| 14 | import { KIND_DAYS, KIND_SQL, WORK_KINDS, type WorkKind } from "../core/model_review.ts"; | |
| 14 | 15 | |
| 15 | 16 | export const WEEK_DAYS = 7; |
| 16 | 17 | |
| @@ -60,6 +61,86 @@ export function weekCard(db: Database, now: Date = new Date()): WeekLine[] { | ||
| 60 | 61 | }); |
| 61 | 62 | } |
| 62 | 63 | |
| 64 | export interface WeekSpend { | |
| 65 | readonly days: number; | |
| 66 | readonly totalUsd: number; | |
| 67 | readonly byKind: Readonly<Record<WorkKind, number>>; | |
| 68 | /** Rework's share (0–1) of the total; null with nothing spent. */ | |
| 69 | readonly reworkShare: number | null; | |
| 70 | /** | |
| 71 | * Agent runs that failed before they reached an account (none allowed, no credit, a cap), and | |
| 72 | * the reason they gave most, clipped; empty with none. | |
| 73 | */ | |
| 74 | readonly noAccount: { readonly runs: number; readonly most: string }; | |
| 75 | } | |
| 76 | ||
| 77 | /** | |
| 78 | * Where the crew's money went over the last `KIND_DAYS`, by kind of work (`KIND_SQL`), and the | |
| 79 | * runs that never reached an account: the lines under the week's table on /crew, and | |
| 80 | * /api/v1/crew/week's `spend`. Two grouped reads. | |
| 81 | */ | |
| 82 | export function weekSpend(db: Database, now: Date = new Date()): WeekSpend { | |
| 83 | const since = new Date(now.getTime() - KIND_DAYS * 86_400_000).toISOString(); | |
| 84 | const byKind = Object.fromEntries(WORK_KINDS.map((k) => [k, 0])) as Record<WorkKind, number>; | |
| 85 | for (const r of db | |
| 86 | .query<{ work: WorkKind; spent: number }, [string]>( | |
| 87 | // Named `work`, not `kind`: GROUP BY would take `run.kind` ('agent') over an alias. | |
| 88 | `SELECT ${KIND_SQL} AS work, COALESCE(SUM(run.cost_usd), 0) AS spent FROM run | |
| 89 | LEFT JOIN repo_crew rc ON rc.repo_id = run.repo_id AND rc.user_id = run.actor_id | |
| 90 | WHERE run.kind = 'agent' AND run.created_at >= ?1 GROUP BY work`, | |
| 91 | ) | |
| 92 | .all(since)) | |
| 93 | byKind[r.work] = money(r.spent); | |
| 94 | const totalUsd = money(WORK_KINDS.reduce((n, k) => n + byKind[k], 0)); | |
| 95 | const failed = db | |
| 96 | .query<{ summary: string; n: number }, [string]>( | |
| 97 | `SELECT summary, COUNT(*) AS n FROM run | |
| 98 | WHERE kind = 'agent' AND state = 'failed' AND subscription_id IS NULL AND created_at >= ?1 | |
| 99 | GROUP BY summary ORDER BY n DESC`, | |
| 100 | ) | |
| 101 | .all(since); | |
| 102 | const first = (failed[0]?.summary ?? "").split("\n")[0]!.trim(); | |
| 103 | return { | |
| 104 | days: KIND_DAYS, | |
| 105 | totalUsd, | |
| 106 | byKind, | |
| 107 | reworkShare: totalUsd > 0 ? byKind.rework / totalUsd : null, | |
| 108 | noAccount: { | |
| 109 | runs: failed.reduce((n, r) => n + r.n, 0), | |
| 110 | most: first.length > 120 ? `${first.slice(0, 119)}…` : first, | |
| 111 | }, | |
| 112 | }; | |
| 113 | } | |
| 114 | ||
| 115 | const dollars = (n: number) => `$${Math.round(n).toLocaleString("en-US")}`; | |
| 116 | ||
| 117 | /** Where a run with no account is fixed: the accounts, and where each may be used. */ | |
| 118 | export const NO_ACCOUNT_FIX = { href: "/settings/subscriptions", words: "Add or allow an account" } as const; | |
| 119 | ||
| 120 | export interface SpendFact { | |
| 121 | readonly label: string; | |
| 122 | readonly value: string; | |
| 123 | /** The control that fixes it, when there is something to do. */ | |
| 124 | readonly fix?: { readonly href: string; readonly words: string }; | |
| 125 | } | |
| 126 | ||
| 127 | /** The spend as two short facts: /crew's list under the week's table and the terminal's rows. */ | |
| 128 | export function spendFacts(s: WeekSpend): readonly [SpendFact, SpendFact] { | |
| 129 | const share = (k: WorkKind) => `${Math.round((100 * s.byKind[k]) / s.totalUsd)}% ${k}`; | |
| 130 | const parts = WORK_KINDS.filter((k) => k === "rework" || s.byKind[k] > 0) | |
| 131 | .sort((a, b) => (a === "rework" ? -1 : b === "rework" ? 1 : s.byKind[b] - s.byKind[a])) | |
| 132 | .map(share); | |
| 133 | const spent = { | |
| 134 | label: `Spent in ${s.days} days`, | |
| 135 | value: s.totalUsd === 0 ? "Nothing" : `${dollars(s.totalUsd)}: ${parts.join(", ")}`, | |
| 136 | }; | |
| 137 | const n = s.noAccount.runs; | |
| 138 | const label = "Runs with no account"; | |
| 139 | if (n === 0) return [spent, { label, value: "None" }]; | |
| 140 | const most = s.noAccount.most === "" ? "" : `; most often “${s.noAccount.most.replace(/[.!?]$/, "")}”`; | |
| 141 | return [spent, { label, value: `${n.toLocaleString("en-US")}${most}`, fix: NO_ACCOUNT_FIX }]; | |
| 142 | } | |
| 143 | ||
| 63 | 144 | export interface ReturnedPull { |
| 64 | 145 | readonly repo: string; |
| 65 | 146 | readonly number: number; |
src/http/api.ts +3 −2
| @@ -80,7 +80,7 @@ import { readHours, routeHours } from "../perf/history.ts"; | ||
| 80 | 80 | import { planProbes } from "../perf/probe.ts"; |
| 81 | 81 | import { countRead } from "../system/telemetry_reads.ts"; |
| 82 | 82 | import { historyFor, sourcesOut, systemWithReaders, welcome } from "../system/telemetry.ts"; |
| 83 | import { weekCard, WEEK_DAYS } from "../crew/week_card.ts"; | |
| 83 | import { weekCard, weekSpend, WEEK_DAYS } from "../crew/week_card.ts"; | |
| 84 | 84 | import { markReaders } from "../crew/direct.ts"; |
| 85 | 85 | import { |
| 86 | 86 | reattachMirror, |
| @@ -1382,7 +1382,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1382 | 1382 | if (denied) return denied; |
| 1383 | 1383 | if (ctx.auth.user?.isAdmin !== true) return apiError("forbidden", 403, ADMIN_WORDS.scorecard); |
| 1384 | 1384 | const members = timePhase(ctx.request, "week", () => weekCard(ctx.app.db)); |
| 1385 | return timePhase(ctx.request, "render", () => json({ days: WEEK_DAYS, members })); | |
| 1385 | const spend = timePhase(ctx.request, "spend", () => weekSpend(ctx.app.db)); | |
| 1386 | return timePhase(ctx.request, "render", () => json({ days: WEEK_DAYS, members, spend })); | |
| 1386 | 1387 | }); |
| 1387 | 1388 | |
| 1388 | 1389 | // What the crew is doing right now, as MCP `now` answers it: a read, so |
src/http/mcp/tools/crew.ts +2 −2
| @@ -11,7 +11,7 @@ import { crewOffInPreview } from "../../../crew/preview.ts"; | ||
| 11 | 11 | import { setSeatSlots, seatSlotsSaid } from "../../../actions/seat_slots.ts"; |
| 12 | 12 | import { checkSeatSlots, seatSlotsOf } from "../../../crew/seat_slots.ts"; |
| 13 | 13 | import { seatsOf } from "../../../crew/seats.ts"; |
| 14 | import { weekCard, WEEK_DAYS } from "../../../crew/week_card.ts"; | |
| 14 | import { weekCard, weekSpend, WEEK_DAYS } from "../../../crew/week_card.ts"; | |
| 15 | 15 | import { ADMIN_WORDS } from "../../../actions/admin_words.ts"; |
| 16 | 16 | import { emptyCrewLine, seatEmptyCrew, SEAT_CREW_WORDS } from "../../../actions/seat_crew.ts"; |
| 17 | 17 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| @@ -50,7 +50,7 @@ export const tool: Tool = { | ||
| 50 | 50 | if (args["kind"] !== undefined) { |
| 51 | 51 | if (args["kind"] !== "week") return bad("invalid", "`kind` is `week` or `seat`"); |
| 52 | 52 | if (user.isAdmin !== true) return bad("forbidden", ADMIN_WORDS.scorecard); |
| 53 | return good({ days: WEEK_DAYS, members: weekCard(ctx.app.db) }); | |
| 53 | return good({ days: WEEK_DAYS, members: weekCard(ctx.app.db), spend: weekSpend(ctx.app.db) }); | |
| 54 | 54 | } |
| 55 | 55 | const repo = repoArg(ctx, user, args); |
| 56 | 56 | if (isAnswer(repo)) return repo; |
src/tui/screens/weekcard.ts +34 −2
| @@ -5,7 +5,17 @@ | ||
| 5 | 5 | * admin; anyone else sees one sentence and no figures. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { weekCard, weekReturns, WEEK_DAYS, type ReturnedPull, type WeekLine } from "../../crew/week_card.ts"; | |
| 8 | import { | |
| 9 | spendFacts, | |
| 10 | weekCard, | |
| 11 | weekReturns, | |
| 12 | weekSpend, | |
| 13 | WEEK_DAYS, | |
| 14 | type ReturnedPull, | |
| 15 | type WeekLine, | |
| 16 | type WeekSpend, | |
| 17 | } from "../../crew/week_card.ts"; | |
| 18 | import { kindStats, type KindStats } from "../../core/model_review.ts"; | |
| 9 | 19 | import type { Ctx, Screen } from "../app/app.ts"; |
| 10 | 20 | import { binding } from "../app/keys.ts"; |
| 11 | 21 | import { style } from "../term/style.ts"; |
| @@ -33,10 +43,32 @@ export function weekRows( | ||
| 33 | 43 | }); |
| 34 | 44 | } |
| 35 | 45 | |
| 46 | /** | |
| 47 | * Under the members, what /crew says under its week table and in "By kind of work": the spend | |
| 48 | * and the runs with no account (with where to fix it), then one row per kind × model × account. | |
| 49 | */ | |
| 50 | export function spendRows(spend: WeekSpend, kinds: readonly KindStats[]): ListRow[] { | |
| 51 | const pct = (k: number, n: number) => (n === 0 ? "no checks" : `${Math.round((100 * k) / n)}% green first`); | |
| 52 | return [ | |
| 53 | ...spendFacts(spend).map((f) => ({ | |
| 54 | title: f.label, | |
| 55 | secondary: f.fix === undefined ? f.value : `${f.value} · ${f.fix.words}: ${f.fix.href}`, | |
| 56 | })), | |
| 57 | ...kinds.map((k) => ({ | |
| 58 | title: `${k.kind} · ${k.model === "" ? "unrecorded" : k.model} · ${k.account === "" ? "no account" : k.account}`, | |
| 59 | secondary: | |
| 60 | `${k.runs} runs · $${k.spentUsd.toFixed(2)} · merged ${k.merged} of ${k.pulls} · ${pct(k.firstGreen, k.checked)}` + | |
| 61 | (k.perMergedUsd === null ? "" : ` · $${k.perMergedUsd.toFixed(2)} per merged`), | |
| 62 | })), | |
| 63 | ]; | |
| 64 | } | |
| 65 | ||
| 36 | 66 | export function weekCardScreen(f: Session, ctx: Ctx): Screen { |
| 37 | 67 | const state = new ListState(); |
| 38 | 68 | const allowed = f.user?.isAdmin === true; |
| 39 | const rows = allowed ? weekRows(weekCard(f.db), weekReturns(f.db)) : []; | |
| 69 | const rows = allowed | |
| 70 | ? [...weekRows(weekCard(f.db), weekReturns(f.db)), ...spendRows(weekSpend(f.db), kindStats(f.db))] | |
| 71 | : []; | |
| 40 | 72 | return { |
| 41 | 73 | title: "Crew this week", |
| 42 | 74 | keys: [binding(["j", "k"], "move cursor")], |
src/web/pages/crew.ts +56 −3
| @@ -47,7 +47,17 @@ import { | ||
| 47 | 47 | } from "../../core/scorecard.ts"; |
| 48 | 48 | import { keeperDays, type KeeperDay } from "../../flow/keeper_rate.ts"; |
| 49 | 49 | import { weekCardRows } from "../../crew/week.ts"; |
| 50 | import { weekCard, weekReturns, WEEK_DAYS, type ReturnedPull, type WeekLine } from "../../crew/week_card.ts"; | |
| 50 | import { | |
| 51 | spendFacts, | |
| 52 | weekCard, | |
| 53 | weekReturns, | |
| 54 | weekSpend, | |
| 55 | WEEK_DAYS, | |
| 56 | type ReturnedPull, | |
| 57 | type WeekLine, | |
| 58 | type WeekSpend, | |
| 59 | } from "../../crew/week_card.ts"; | |
| 60 | import { KIND_DAYS, kindStats } from "../../core/model_review.ts"; | |
| 51 | 61 | import { knobsCard } from "./knobs.ts"; |
| 52 | 62 | import { CHANGE_WORDS, decideChange, readReview } from "../../actions/model_review.ts"; |
| 53 | 63 | import { wastedDays, type WastedDay } from "../../core/wasted_days.ts"; |
| @@ -432,7 +442,9 @@ function weekCardPanel( | ||
| 432 | 442 | lines: readonly WeekLine[], |
| 433 | 443 | returns: ReadonlyMap<string, readonly ReturnedPull[]>, |
| 434 | 444 | records: ReadonlyMap<string, MemberRecord>, |
| 445 | spend: WeekSpend, | |
| 435 | 446 | ): Html { |
| 447 | const facts = spendFacts(spend); | |
| 436 | 448 | return panel( |
| 437 | 449 | html`<div class="table-scroll"> |
| 438 | 450 | <table class="table" id="crew-week" data-sticky-lead> |
| @@ -459,7 +471,12 @@ function weekCardPanel( | ||
| 459 | 471 | })} |
| 460 | 472 | </tbody> |
| 461 | 473 | </table> |
| 462 | </div>`, | |
| 474 | </div> | |
| 475 | <dl class="status-rows" id="crew-week-spend">${facts.map( | |
| 476 | (f) => html`<div class="status-row"><dt>${f.label}</dt><dd>${f.value}${f.fix === undefined | |
| 477 | ? null | |
| 478 | : html`. <a href="${f.fix.href}">${f.fix.words}</a>`}</dd></div>`, | |
| 479 | )}</dl>`, | |
| 463 | 480 | { title: `This week · ${WEEK_DAYS} days`, id: "crew-week-card" }, |
| 464 | 481 | ); |
| 465 | 482 | } |
| @@ -549,6 +566,41 @@ function loadSpending(ctx: Ctx) { | ||
| 549 | 566 | })); |
| 550 | 567 | } |
| 551 | 568 | |
| 569 | /** | |
| 570 | * The crew's runs by kind of work × model × account over `KIND_DAYS` (`kindStats`): what each | |
| 571 | * spent and what became of its pulls, dearest first. Cost per merge only from `KIND_MIN_MERGED`. | |
| 572 | */ | |
| 573 | function kindCard(ctx: Ctx): Html | null { | |
| 574 | const rows = kindStats(ctx.app.db); | |
| 575 | if (rows.length === 0) return null; | |
| 576 | const pct = (k: number, n: number) => | |
| 577 | n === 0 ? html`<td class="num muted">—</td>` : html`<td class="num">${Math.round((100 * k) / n)}%</td>`; | |
| 578 | return panel( | |
| 579 | html`<div class="table-scroll"> | |
| 580 | <table class="table" id="crew-kinds" data-sticky-lead> | |
| 581 | <thead> | |
| 582 | <tr><th>Kind</th><th>Model</th><th>Account</th><th class="num">Runs</th><th class="num">Spent</th><th class="num">Merged</th><th class="num">Green first</th><th class="num">Per merged</th></tr> | |
| 583 | </thead> | |
| 584 | <tbody> | |
| 585 | ${rows.map( | |
| 586 | (r) => html`<tr data-kind="${r.kind}"> | |
| 587 | <td>${r.kind}</td> | |
| 588 | <td class="mono">${r.model === "" ? "unrecorded" : r.model}</td> | |
| 589 | <td>${r.account === "" ? "none" : r.account}</td> | |
| 590 | <td class="num">${r.runs}</td> | |
| 591 | <td class="num">$${r.spentUsd.toFixed(2)}</td> | |
| 592 | <td class="num">${r.merged} <span class="muted small">of ${r.pulls}</span></td> | |
| 593 | ${pct(r.firstGreen, r.checked)} | |
| 594 | ${r.perMergedUsd === null ? html`<td class="num muted">—</td>` : html`<td class="num">$${r.perMergedUsd.toFixed(2)}</td>`} | |
| 595 | </tr>`, | |
| 596 | )} | |
| 597 | </tbody> | |
| 598 | </table> | |
| 599 | </div>`, | |
| 600 | { title: `By kind of work · ${KIND_DAYS} days`, id: "crew-kinds-card" }, | |
| 601 | ); | |
| 602 | } | |
| 603 | ||
| 552 | 604 | /** |
| 553 | 605 | * The weekly model review (#7815): each member's models side by side, the verdict, the button, the |
| 554 | 606 | * trail. |
| @@ -658,7 +710,7 @@ function weekPanel(ctx: Ctx): Html { | ||
| 658 | 710 | const db = ctx.app.db; |
| 659 | 711 | const card = weekCard(db); |
| 660 | 712 | const records = new Map(memberRecords(db, new Date(), card).map((m) => [m.username, m])); |
| 661 | return weekCardPanel(card, weekReturns(db), records); | |
| 713 | return weekCardPanel(card, weekReturns(db), records, weekSpend(db)); | |
| 662 | 714 | } |
| 663 | 715 | |
| 664 | 716 | function crewView( |
| @@ -797,6 +849,7 @@ function crewView( | ||
| 797 | 849 | ), |
| 798 | 850 | )} |
| 799 | 851 | ${when(agents.length > 0, () => modelReviewCard(ctx))} |
| 852 | ${agents.length > 0 ? kindCard(ctx) : null} | |
| 800 | 853 | ${splitsCard( |
| 801 | 854 | "Per model", |
| 802 | 855 | "Model", |
test/crew-week-card.test.ts +19 −1
| @@ -15,7 +15,7 @@ import { createRepo } from "../src/actions/repos.ts"; | ||
| 15 | 15 | import { createSession } from "../src/core/sessions.ts"; |
| 16 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 17 | 17 | import { createUser, type User } from "../src/core/users.ts"; |
| 18 | import { weekCard, weekReturns, RETURNED_CAP } from "../src/crew/week_card.ts"; | |
| 18 | import { weekCard, weekReturns, weekSpend, RETURNED_CAP } from "../src/crew/week_card.ts"; | |
| 19 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 20 | 20 | import { seedAdmin } from "./helpers/admin.ts"; |
| 21 | 21 | import { statements } from "./helpers/statements.ts"; |
| @@ -124,6 +124,14 @@ test("the crew page: a dense row for the busy one, the word idle for the rest", | ||
| 124 | 124 | expect(rows[2]).toContain("idle"); |
| 125 | 125 | expect(rows[2]).not.toContain("$0"); |
| 126 | 126 | expect(rows[1]).toContain("idle"); |
| 127 | // Under the table, two facts: where the money went by kind of work, and the runs that reached no | |
| 128 | // account. | |
| 129 | expect(page).toContain('id="crew-week-spend"'); | |
| 130 | expect(page).toContain("<dt>Runs with no account</dt><dd>None</dd>"); | |
| 131 | // And the rows behind them: each kind × model × account, as a table. | |
| 132 | const kinds = page.slice(page.indexOf('id="crew-kinds"'), page.indexOf("</table>", page.indexOf('id="crew-kinds"'))); | |
| 133 | expect(kinds).toContain('data-kind="other"'); | |
| 134 | expect(kinds).toContain("unrecorded"); | |
| 127 | 135 | }); |
| 128 | 136 | |
| 129 | 137 | test("a Returned count opens onto the pulls and why; zero stays a bare 0", async () => { |
| @@ -194,6 +202,7 @@ test("the API and the MCP crew tool answer the same numbers", async () => { | ||
| 194 | 202 | const body = (await api.json()) as { days: number; members: any[] }; |
| 195 | 203 | expect(body.days).toBe(7); |
| 196 | 204 | expect(body.members).toEqual(weekCard(app.db)); |
| 205 | expect((body as { spend?: unknown }).spend).toEqual(JSON.parse(JSON.stringify(weekSpend(app.db)))); | |
| 197 | 206 | const rpc = await fetch(`${servers.url}/mcp`, { |
| 198 | 207 | method: "POST", |
| 199 | 208 | headers: { |
| @@ -249,6 +258,15 @@ test("the terminal rows say idle, and show the figures for the busy", async () = | ||
| 249 | 258 | expect(rows.find((r) => r.title === "smith")!.secondary).toContain("spent $1.25"); |
| 250 | 259 | }); |
| 251 | 260 | |
| 261 | test("the terminal shows the spend facts and the rows by kind, with where to fix runs that reached no account", async () => { | |
| 262 | const { spendRows } = await import("../src/tui/screens/weekcard.ts"); | |
| 263 | const { kindStats } = await import("../src/core/model_review.ts"); | |
| 264 | const rows = spendRows(weekSpend(app.db), kindStats(app.db)); | |
| 265 | expect(rows.map((r) => r.title)).toEqual(expect.arrayContaining(["Spent in 14 days", "Runs with no account", "other · unrecorded · no account"])); | |
| 266 | const none = spendRows({ ...weekSpend(app.db), noAccount: { runs: 3, most: "No account may be used here." } }, []); | |
| 267 | expect(none[1]!.secondary).toBe("3; most often “No account may be used here” · Add or allow an account: /settings/subscriptions"); | |
| 268 | }); | |
| 269 | ||
| 252 | 270 | test("the crew page costs a bounded number of statements", async () => { |
| 253 | 271 | const n = await statements(app.db, async () => { |
| 254 | 272 | await (await fetch(`${servers.url}/settings/crew`, { headers: { cookie } })).text(); |
test/mcp-scorecard-decide.test.ts +1 −1
| @@ -35,7 +35,7 @@ const call = async (token: string, args: unknown) => { | ||
| 35 | 35 | return { error: body.result?.isError === true || body.error !== undefined, text: String(body.result?.content?.[0]?.text ?? body.error?.message ?? "") }; |
| 36 | 36 | }; |
| 37 | 37 | |
| 38 | const before: ModelStats = { model: "opus", opened: 9, landed: 9, costPerLanded: 20, redRate: 0.1, reworkRounds: 0, reverts: 0, hardShare: 0 }; | |
| 38 | const before: ModelStats = { model: "opus", opened: 9, landed: 9, costPerLanded: 20, redRate: 0.1, reworkRounds: 0, reverts: 0, hardShare: 0, checked: 9, firstGreen: 8 }; | |
| 39 | 39 | const ask = () => recordChange(app.db, { agentId: botId, fromModel: "opus", toModel: "sonnet", state: "asked", why: "healthy", before, at: new Date() }); |
| 40 | 40 | |
| 41 | 41 | beforeAll(async () => { |
test/model-review.test.ts +81 −4
| @@ -12,7 +12,8 @@ import { runModelReview, decideChange, readReview } from "../src/actions/model_r | ||
| 12 | 12 | import { readScorecards } from "../src/actions/scorecard.ts"; |
| 13 | 13 | import { createAgentRow, getAgent } from "../src/core/agents.ts"; |
| 14 | 14 | import { createIssue } from "../src/core/issues.ts"; |
| 15 | import { getChange, recordChange, review, type ModelStats } from "../src/core/model_review.ts"; | |
| 15 | import { getChange, kindStats, recordChange, review, wilson, type ModelStats } from "../src/core/model_review.ts"; | |
| 16 | import { spendFacts, weekSpend } from "../src/crew/week_card.ts"; | |
| 16 | 17 | import { claimRun, createRun, finishRun, noteRunProgress } from "../src/core/runs.ts"; |
| 17 | 18 | import { createSession } from "../src/core/sessions.ts"; |
| 18 | 19 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| @@ -26,7 +27,7 @@ quietLogs(); | ||
| 26 | 27 | |
| 27 | 28 | const stats = (o: Partial<ModelStats> = {}): ModelStats => ({ |
| 28 | 29 | model: "opus", opened: 10, landed: 10, costPerLanded: 25, redRate: 0.1, |
| 29 | reworkRounds: 0.2, reverts: 0, hardShare: 0.1, ...o, | |
| 30 | reworkRounds: 0.2, reverts: 0, hardShare: 0.1, checked: 10, firstGreen: 9, ...o, | |
| 30 | 31 | }); |
| 31 | 32 | const limits = { minLanded: 8, slackPct: 10 }; |
| 32 | 33 | |
| @@ -45,8 +46,33 @@ describe("the verdict, as plain code", () => { | ||
| 45 | 46 | test("mostly hard work is not handed to a cheaper model", () => { |
| 46 | 47 | expect(review("opus", [stats({ hardShare: 0.9 })], limits).kind).toBe("hold"); |
| 47 | 48 | }); |
| 48 | test("a model that reverts steps up, never down", () => { | |
| 49 | expect(review("sonnet", [stats({ model: "sonnet", reverts: 1 })], limits)).toMatchObject({ kind: "propose", to: "opus", direction: "up" }); | |
| 49 | test("poor numbers alone never buy a dearer model: it steps up only when its own pulls did clearly better", () => { | |
| 50 | const sonnet = stats({ model: "sonnet", reverts: 1, checked: 40, firstGreen: 10 }); | |
| 51 | const alone = review("sonnet", [sonnet], limits); | |
| 52 | expect(alone.kind).toBe("hold"); | |
| 53 | expect(alone.kind === "hold" && alone.note).toContain("too few to show it does better"); | |
| 54 | expect(review("sonnet", [sonnet, stats({ checked: 40, firstGreen: 32 })], limits)).toMatchObject({ kind: "propose", to: "opus", direction: "up" }); | |
| 55 | }); | |
| 56 | test("greener first time but worse on rework is not clearly better", () => { | |
| 57 | const sonnet = stats({ model: "sonnet", reverts: 1, reworkRounds: 0.5, checked: 40, firstGreen: 10 }); | |
| 58 | expect(review("sonnet", [sonnet, stats({ checked: 40, firstGreen: 32, reworkRounds: 1.5 })], limits).kind).toBe("hold"); | |
| 59 | }); | |
| 60 | test("production's 14 days to 2026-11-29: opus as green first time as sonnet at twice the cost holds, and says both", () => { | |
| 61 | const sonnet = stats({ model: "sonnet", opened: 443, landed: 436, costPerLanded: 1.17, redRate: 0.52, reworkRounds: 0.83, reverts: 4, checked: 443, firstGreen: 109 }); | |
| 62 | const opus = stats({ opened: 277, landed: 260, costPerLanded: 2.24, redRate: 0.47, reworkRounds: 1.2, reverts: 1, checked: 276, firstGreen: 70 }); | |
| 63 | const v = review("sonnet", [sonnet, opus], limits); | |
| 64 | expect(v.kind).toBe("hold"); | |
| 65 | const note = v.kind === "hold" ? v.note : ""; | |
| 66 | expect(note).toContain("sonnet: 436 landed at $1.17 each, 25% green first time"); | |
| 67 | expect(note).toContain("opus: 260 landed at $2.24 each, 25% green first time"); | |
| 68 | expect(note).toContain("not clearly better"); | |
| 69 | }); | |
| 70 | test("the interval: nothing is all of [0, 1], and a rate sits inside its own", () => { | |
| 71 | expect(wilson(0, 0)).toEqual({ lo: 0, hi: 1 }); | |
| 72 | const w = wilson(109, 443); | |
| 73 | expect(w.lo).toBeLessThan(109 / 443); | |
| 74 | expect(w.hi).toBeGreaterThan(109 / 443); | |
| 75 | expect(w.hi - w.lo).toBeLessThan(0.09); | |
| 50 | 76 | }); |
| 51 | 77 | test("a cheaper model with its own worse numbers stays where it is", () => { |
| 52 | 78 | const v = review("opus", [stats(), stats({ model: "sonnet", costPerLanded: 1, redRate: 0.6 })], limits); |
| @@ -226,11 +252,62 @@ describe("the weekly review", () => { | ||
| 226 | 252 | setLimit(app.db, "model_review.auto", 1, agent.id); |
| 227 | 253 | app.db.query("UPDATE agent SET model = 'sonnet' WHERE user_id = ?1").run(agent.id); |
| 228 | 254 | many(8, "sonnet", day(-3), { reverted: true }); |
| 255 | many(8, "opus", day(-5)); | |
| 229 | 256 | const [c] = runModelReview(app, t0); |
| 230 | 257 | expect(c).toMatchObject({ state: "asked", toModel: "opus" }); |
| 231 | 258 | expect(model()).toBe("sonnet"); |
| 232 | 259 | }); |
| 233 | 260 | |
| 261 | test("an ask for a dearer model made on poor numbers alone is held at the next tick, with the numbers", () => { | |
| 262 | app.db.query("UPDATE agent SET model = 'sonnet' WHERE user_id = ?1").run(agent.id); | |
| 263 | many(8, "sonnet", day(-3), { reverted: true }); | |
| 264 | const id = recordChange(app.db, { | |
| 265 | agentId: agent.id, fromModel: "sonnet", toModel: "opus", state: "asked", | |
| 266 | why: "sonnet is not holding its quality", before: stats({ model: "sonnet" }), at: day(-1), | |
| 267 | }); | |
| 268 | expect(runModelReview(app, t0)).toEqual([]); | |
| 269 | const held = getChange(app.db, id)!; | |
| 270 | expect(held.state).toBe("declined"); | |
| 271 | expect(held.result).toContain("held: sonnet: 8 landed"); | |
| 272 | expect(held.result).toContain("too few to show it does better"); | |
| 273 | expect(model()).toBe("sonnet"); | |
| 274 | expect(events("crew.model_declined")[0]!.payload).toContain("held"); | |
| 275 | }); | |
| 276 | ||
| 277 | test("by kind of work: each run's own spend, a pull once per row, no cost per merge under twenty; and the runs that reached no account", () => { | |
| 278 | landed("sonnet", new Date()); | |
| 279 | const pullId = app.db.query<{ id: string }, []>("SELECT issue_id AS id FROM pull ORDER BY rowid DESC LIMIT 1").get()!.id; | |
| 280 | const work = (reason: string, cost: number, o: { issueId?: string; sub?: string; failed?: string } = {}) => { | |
| 281 | const r = createRun(app.db, { repoId, kind: "agent", actorId: agent.id, reason, ...(o.issueId === undefined ? {} : { issueId: o.issueId }) }); | |
| 282 | claimRun(app.db, r.id); | |
| 283 | noteRunProgress(app.db, r.id, { model: "sonnet", costUsd: cost, ...(o.sub === undefined ? {} : { subscriptionId: o.sub }) }); | |
| 284 | finishRun(app.db, r.id, { state: o.failed === undefined ? "ok" : "failed", summary: o.failed ?? "" }); | |
| 285 | }; | |
| 286 | work("assigned", 2, { issueId: pullId, sub: "platform" }); | |
| 287 | work("feedback", 3, { issueId: pullId, sub: "platform" }); | |
| 288 | work("check_failed", 1, { issueId: pullId, sub: "platform" }); | |
| 289 | work("assigned", 0, { failed: "No account may be used here.\nAllow one." }); | |
| 290 | work("assigned", 0, { failed: "No account may be used here.\nAllow one." }); | |
| 291 | const platform = app.db.query<{ name: string }, []>("SELECT name FROM subscription WHERE id = 'platform'").get()?.name ?? ""; | |
| 292 | const rows = kindStats(app.db); | |
| 293 | const rework = rows.find((r) => r.kind === "rework")!; | |
| 294 | expect(rework).toMatchObject({ model: "sonnet", account: platform, runs: 2, spentUsd: 4, pulls: 1, merged: 1, perMergedUsd: null }); | |
| 295 | expect(rows.find((r) => r.kind === "build" && r.account === "")).toMatchObject({ runs: 2, spentUsd: 0, pulls: 0 }); | |
| 296 | expect(rows[0]!.kind).toBe("rework"); | |
| 297 | const spend = weekSpend(app.db); | |
| 298 | expect(spend.byKind).toMatchObject({ build: 2, rework: 4, review: 0, plan: 0, other: 1 }); | |
| 299 | expect(spend.noAccount).toEqual({ runs: 2, most: "No account may be used here." }); | |
| 300 | expect(spendFacts(spend)).toEqual([ | |
| 301 | { label: "Spent in 14 days", value: "$7: 57% rework, 29% build, 14% other" }, | |
| 302 | { | |
| 303 | label: "Runs with no account", | |
| 304 | value: "2; most often “No account may be used here”", | |
| 305 | fix: { href: "/settings/subscriptions", words: "Add or allow an account" }, | |
| 306 | }, | |
| 307 | ]); | |
| 308 | expect(readScorecards(app, admin())?.byKind).toEqual(rows); | |
| 309 | }); | |
| 310 | ||
| 234 | 311 | test("the scorecard's doors carry the review, for an admin only", () => { |
| 235 | 312 | expect(readScorecards(app, undefined)).toBeUndefined(); |
| 236 | 313 | expect(readScorecards(app, admin())?.modelReview.agents[0]?.username).toBe("torque"); |
test/tui-model-review.test.ts +1 −1
| @@ -17,7 +17,7 @@ quietLogs(); | ||
| 17 | 17 | |
| 18 | 18 | const TITLE = "Crew scorecard per agent"; |
| 19 | 19 | const before: ModelStats = { |
| 20 | model: "opus", opened: 10, landed: 10, costPerLanded: 25, redRate: 0.1, reworkRounds: 0.2, reverts: 0, hardShare: 0.1, | |
| 20 | model: "opus", opened: 10, landed: 10, costPerLanded: 25, redRate: 0.1, reworkRounds: 0.2, reverts: 0, hardShare: 0.1, checked: 10, firstGreen: 9, | |
| 21 | 21 | }; |
| 22 | 22 | let dir = ""; |
| 23 | 23 | let app: App; |
new above
offline