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

Estimates are recorded against an issue, start from the forge's own history,… #11960

Parked opened this in answer to
Closed without merging

torque/forge:torque/11955-estimates-are-recorded-against-an-issue → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
29 files changed +1328 −5
docs/FLOW.md +29
@@ -161,3 +161,32 @@ toward no file's heat and is named on the feed (`too wide to count: #4840
161161 `src/crew/stale_reds.ts` `sweepStaleReds(app, repo, now, room)` runs each autonomy tick and reads only the database, so a restart or roll loses nothing. An open crew pull whose latest check on its head failed, with no run in 30 minutes and no person holding or assigned to it, is re-checked (reason `sweep`); still red, its builder is queued with the failing test named, within the free slots and 3 a tick. Past its tries it is parked and its issue is ready again. Red for over 24 h and conflicting with main, or with its issue closed, it is closed with one line. The flow report's `stale_reds` line (`src/flow/stale_reds.ts`) counts the ones not yet handled, and the keeper names `stale_reds` as a cause from 3.
162162
163163 How a person sees stale reds: `bun scripts/flow-report.ts` prints the `stale_reds:` line (count and oldest hours), and the keeper names `stale_reds` as the cause when they are what holds the flow; the terminal Flow dialog draws the keeper's line (`keeperLine`), so it shows there when the keeper picks that cause. It has no line of its own on the dialog.
164
165 ## Estimates (#11955)
166
167 An estimate is a promise about when one issue's work happens, kept against the
168 issue and scored. The `estimate` tool (MCP; `GET`/`POST
169 /api/v1/repos/:owner/:name/issues/:n/estimates`) does two things:
170
171 - **Ask**, with no `event`: the base rate for this issue from the forge's own
172 history (`src/flow/estimate_base.ts`): merged pulls in the last 30 days of the
173 same repository, size and kind (and builder when assigned), measured from the
174 first agent run on the issue (else its creation) to the pull opening, the
175 merge and the release that carried the merge going live. Quantiles are
176 nearest-rank, `sorted[round((n - 1) * q)]`. Under five samples it says so and
177 widens: builder, kind, size, then 90 days. It adds what history does not know
178 (queue position, runs going, budget left, why a release is held) and your own
179 scorecard.
180 - **Record**, with `event` (`pull_opened`, `merged`, `live`), `p50`, `p90`
181 (future instants, p50 ≤ p90) and `basis`. Rows are never edited: a new one
182 supersedes and the old stays as data.
183
184 The forge resolves, nobody by hand: opening a pull that says `Closes #N`, merging
185 it, and the keeper marking live a release cut after the merge each set the actual
186 instant; closing the issue as split or dropped (or moving it to Not now) voids
187 what is open. Scores (`src/flow/estimate_score.ts`, shown on /flow): ratio =
188 actual / p50 duration from the moment it was made, the median ratio is the bias,
189 the p90 hit rate should be about 90%; only an estimator's first estimate per
190 issue and event counts, so revising late cannot improve a score. The base rate
191 shown at the time is scored as the estimator `history`. Not yet: `live` for an
192 app's production deploy resolves only for the forge's own releases.
docs/MCP.md +1
@@ -98,6 +98,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
9898 | `edit` | — | Retitle or rewrite an issue or pull: yours, or where you write; an agent only its own | 310 |
9999 | `egress_grants` | — | Private destinations and grants: list, grant or revoke (site admin) | 289 |
100100 | `email_verify` | — | Send yourself a new verification link | 126 |
101 | `estimate` | — | Ask an issue's base rate, or record `event` with `p50`, `p90` (instants) and `basis` | 399 |
101102 | `events` | — | Repository events | 259 |
102103 | `explore` | — | The apps, people (and, for an admin, forges) you can see, ranked | 627 |
103104 | `family` | — | The forge that sent this one and, for a site admin, those it sent, with state, version | 205 |
src/actions/estimates.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * The `estimate` act (#11955), one tool for two uses: ask the base rate for an
3 * issue, or record an estimate against it. The page, the API, MCP and the
4 * terminal call these and say the same words. Validation is here, at the
5 * boundary; rows and maths are `core/estimates.ts` and `flow/estimate_*`.
6 */
7 import type { App } from "../app.ts";
8 import { addEstimate, allEstimates, currentOf, estimatesOf, isEvent, type EstimateEvent, type EstimateRow } from "../core/estimates.ts";
9 import { forgeSource } from "../settings/forge_source.ts";
10 import { getIssue, type Issue } from "../core/issues.ts";
11 import { mergedPullClosing, openPullsClosing } from "../core/pulls.ts";
12 import { nextUp } from "../core/next_up.ts";
13 import { canWrite, type Repo } from "../core/repos.ts";
14 import { listActiveRuns } from "../core/runs.ts";
15 import type { User } from "../core/users.ts";
16 import { budgetLines } from "../crew/forge_budget.ts";
17 import { baseRate, historySamples, type BaseRate } from "../flow/estimate_base.ts";
18 import { kindOf, labelsOf, sizeOf } from "../flow/estimate.ts";
19 import { lastLine } from "../flow/estimate_score.ts";
20 import { estimateLine } from "../flow/estimate_words.ts";
21 import { blocking, standingHolds } from "../keeper/hold.ts";
22 import { err, ok, type Result } from "../kernel/result.ts";
23
24 export const ESTIMATE_FORBIDDEN = "Only someone with write access, or a crew member on this repository, records an estimate.";
25 export const ESTIMATE_NOT_OPEN = "Only an open issue is estimated.";
26 export const ESTIMATE_SHAPE =
27 "`event` is pull_opened, merged or live; `p50` and `p90` are instants like 2026-11-14T07:15:00Z, both in the future with p50 no later than p90; `basis` is one line, at most 300 characters.";
28 export const ESTIMATE_PASSED = "That event has already happened, so it is not estimated.";
29 const BASIS_MAX = 300;
30 const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/;
31
32 export type EstimateError = { kind: "not_found" | "forbidden" | "invalid"; message: string };
33
34 /** What is true now that history does not know. */
35 export interface NowFacts {
36 /** Place on /next, 1 at the top; null when the issue is not on the list. */
37 readonly queuePosition: number | null;
38 readonly listed: number;
39 /** Agent runs going on this repository now. */
40 readonly buildersBusy: number;
41 /** USD left of the forge's day and month budgets. */
42 readonly budgetLeftUsd: { readonly day: number; readonly month: number };
43 /** Why the keeper will not cut a release now; null when nothing holds one. */
44 readonly releasesHeld: string | null;
45 }
46
47 export interface Asked {
48 readonly repo: string;
49 readonly number: number;
50 readonly size: string;
51 readonly kind: string;
52 readonly now: string;
53 readonly base: BaseRate;
54 readonly facts: NowFacts;
55 readonly current: readonly EstimateRow[];
56 readonly scorecard: string;
57 readonly line: string | undefined;
58 }
59
60 function startedAt(app: App, issue: Issue): number | undefined {
61 const row = app.db
62 .query<{ at: string | null }, [string]>("SELECT MIN(created_at) AS at FROM run WHERE issue_id = ?1 AND kind = 'agent'")
63 .get(issue.id);
64 const ms = row?.at == null ? NaN : Date.parse(row.at);
65 return Number.isFinite(ms) ? ms : undefined;
66 }
67
68 /**
69 * The base rate for this issue at `now`: one read of the history, the same answer for the same
70 * history.
71 */
72 export function baseFor(app: App, repo: Repo, issue: Issue, now: Date): BaseRate {
73 const labels = labelsOf(app.db, [issue.id]).get(issue.id) ?? [];
74 const started = startedAt(app, issue);
75 const samples = historySamples(app.db, repo.id, now.getTime() - 90 * 86_400_000, now.getTime());
76 return baseRate(
77 samples,
78 { size: sizeOf(issue), kind: kindOf(labels), builder: issue.assigneeName ?? null, elapsedMs: started === undefined ? 0 : Math.max(0, now.getTime() - started) },
79 `${repo.ownerName}/${repo.name}`,
80 now.getTime(),
81 );
82 }
83
84 function factsOf(app: App, repo: Repo, issue: Issue, now: Date): NowFacts {
85 const rows = nextUp(app.db, repo).rows;
86 const at = rows.findIndex((r) => r.issue.id === issue.id);
87 const [, day, month] = budgetLines(app.db, now);
88 const own = forgeSource(app.db, app.config.forgeRepo);
89 const forge = own !== undefined && own.toLowerCase() === `${repo.ownerName}/${repo.name}`.toLowerCase();
90 return {
91 queuePosition: at < 0 ? null : at + 1,
92 listed: rows.length,
93 buildersBusy: listActiveRuns(app.db, [repo.id]).length,
94 budgetLeftUsd: {
95 day: Math.max(0, Math.round((day!.limitUsd - (day!.spentUsd ?? 0)) * 100) / 100),
96 month: Math.max(0, Math.round((month!.limitUsd - (month!.spentUsd ?? 0)) * 100) / 100),
97 },
98 releasesHeld: forge ? blocking(standingHolds(app.db)) ?? null : null,
99 };
100 }
101
102 /**
103 * The issue as the act sees it: open work only for recording; any issue the viewer can see for
104 * asking.
105 */
106 export function estimateIssue(app: App, repo: Repo, number: number): Issue | undefined {
107 const issue = Number.isInteger(number) && number > 0 ? getIssue(app.db, repo.id, number) : undefined;
108 return issue !== undefined && issue.kind === "issue" ? issue : undefined;
109 }
110
111 /** Ask: the base rate for this issue and what is true now, with the asker's own scorecard. */
112 export function askEstimate(app: App, actor: User | undefined, repo: Repo, issue: Issue, now: Date = new Date()): Asked {
113 const rows = estimatesOf(app.db, issue.id);
114 const labels = labelsOf(app.db, [issue.id]).get(issue.id) ?? [];
115 return {
116 repo: `${repo.ownerName}/${repo.name}`,
117 number: issue.number,
118 size: sizeOf(issue),
119 kind: kindOf(labels),
120 now: now.toISOString(),
121 base: baseFor(app, repo, issue, now),
122 facts: factsOf(app, repo, issue, now),
123 current: currentOf(rows),
124 scorecard: actor === undefined ? "" : lastLine(allEstimates(app.db), actor.username, true),
125 line: estimateLine(currentOf(rows), now.getTime()),
126 };
127 }
128
129 export interface EstimateInput {
130 readonly event?: unknown;
131 readonly p50?: unknown;
132 readonly p90?: unknown;
133 readonly basis?: unknown;
134 }
135
136 const instant = (v: unknown): number | undefined => {
137 if (typeof v !== "string" || !INSTANT.test(v)) return undefined;
138 const ms = Date.parse(v);
139 return Number.isFinite(ms) ? ms : undefined;
140 };
141
142 /**
143 * Record: validated, stamped with who and when, and the base rate shown at that moment. A new one
144 * supersedes; the old rows stay.
145 */
146 export function recordEstimate(
147 app: App,
148 actor: User,
149 repo: Repo,
150 issue: Issue,
151 input: EstimateInput,
152 now: Date = new Date(),
153 ): Result<{ estimate: EstimateRow; base: BaseRate; scorecard: string }, EstimateError> {
154 const invalid = (message: string) => err<EstimateError>({ kind: "invalid", message });
155 if (!canWrite(app.db, repo, actor)) return err({ kind: "forbidden", message: ESTIMATE_FORBIDDEN });
156 if (issue.state !== "open") return invalid(ESTIMATE_NOT_OPEN);
157 if (!isEvent(input.event)) return invalid(ESTIMATE_SHAPE);
158 const event: EstimateEvent = input.event;
159 const p50 = instant(input.p50);
160 const p90 = instant(input.p90);
161 if (p50 === undefined || p90 === undefined) return invalid(ESTIMATE_SHAPE);
162 if (p50 <= now.getTime() || p90 <= now.getTime()) return invalid("Both times are in the future: " + ESTIMATE_SHAPE);
163 if (p50 > p90) return invalid("p50 is no later than p90.");
164 const basis = input.basis === undefined ? "" : input.basis;
165 // eslint-disable-next-line no-control-regex
166 if (typeof basis !== "string" || basis.length > BASIS_MAX || /[\u0000-\u001f\u007f]/.test(basis)) return invalid(ESTIMATE_SHAPE);
167 const happened =
168 event === "pull_opened"
169 ? openPullsClosing(app.db, repo.id).has(issue.number) || mergedPullClosing(app.db, repo.id, issue.number) !== undefined
170 : event === "merged"
171 ? mergedPullClosing(app.db, repo.id, issue.number) !== undefined
172 : false;
173 if (happened) return invalid(ESTIMATE_PASSED);
174 const base = baseFor(app, repo, issue, now);
175 const labels = labelsOf(app.db, [issue.id]).get(issue.id) ?? [];
176 const id = addEstimate(app.db, {
177 repoId: repo.id,
178 issueId: issue.id,
179 event,
180 p50At: new Date(p50).toISOString(),
181 p90At: new Date(p90).toISOString(),
182 madeAt: now.toISOString(),
183 byId: actor.id,
184 byKind: actor.kind === "agent" ? "agent" : "person",
185 basis: basis.trim(),
186 baseJson: JSON.stringify(base),
187 size: sizeOf(issue),
188 kind: kindOf(labels),
189 });
190 app.bus.append({
191 kind: "issue.estimated",
192 repoId: repo.id,
193 actorId: actor.id,
194 payload: { number: issue.number, event, estimate: id },
195 });
196 const estimate = estimatesOf(app.db, issue.id).find((e) => e.id === id)!;
197 return ok({ estimate, base, scorecard: lastLine(allEstimates(app.db), actor.username, true) });
198 }
src/actions/next.ts +3
@@ -6,6 +6,7 @@
66 */
77 import type { App } from "../app.ts";
88 import { addDependency, repoGraph } from "../core/dependencies.ts";
9 import { voidOpen } from "../core/estimates.ts";
910 import { getIssue, type Issue } from "../core/issues.ts";
1011 import { isStructural, pillarsOf } from "../core/pillars.ts";
1112 import { clearRank, lift, MAX_RANKED, ranksInRepo, writeOrder } from "../core/rank.ts";
@@ -79,6 +80,8 @@ export function rankIssue(
7980 const linked = addDependency(app.db, issue, set.gate!, actor.id);
8081 if (!linked.ok) return invalid(NEXT_INVALID);
8182 clearRank(app.db, issue.id);
83 // Not now: what it promised is void, not scored (#11955).
84 voidOpen(app.db, issue.id);
8285 return ok(undefined);
8386 }
8487 lift(app.db, repo, issue.id);
src/contract/openapi/routes/getApiV1ReposOwnerNameIssuesNumberEstimates.ts added +9
@@ -0,0 +1,9 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/issues/{number}/estimates`,
6 summary: "Read an issue's base rate from the forge's history (p50/p90 per event), the estimates recorded against it and the caller's scorecard",
7 auth: true,
8 role: "member",
9 };
src/contract/openapi/routes/index.ts +2
@@ -159,6 +159,7 @@ export { route as getApiV1ReposOwnerNameIssues } from "./getApiV1ReposOwnerNameI
159159 export { route as getApiV1ReposOwnerNameIssuesNumber } from "./getApiV1ReposOwnerNameIssuesNumber.ts";
160160 export { route as getApiV1ReposOwnerNameIssuesNumberComments } from "./getApiV1ReposOwnerNameIssuesNumberComments.ts";
161161 export { route as getApiV1ReposOwnerNameIssuesNumberDependencies } from "./getApiV1ReposOwnerNameIssuesNumberDependencies.ts";
162 export { route as getApiV1ReposOwnerNameIssuesNumberEstimates } from "./getApiV1ReposOwnerNameIssuesNumberEstimates.ts";
162163 export { route as getApiV1ReposOwnerNameIssuesNumberPlan } from "./getApiV1ReposOwnerNameIssuesNumberPlan.ts";
163164 export { route as getApiV1ReposOwnerNameIssuesNumberTeams } from "./getApiV1ReposOwnerNameIssuesNumberTeams.ts";
164165 export { route as getApiV1ReposOwnerNameIterations } from "./getApiV1ReposOwnerNameIterations.ts";
@@ -346,6 +347,7 @@ export { route as postApiV1ReposOwnerNameIssues } from "./postApiV1ReposOwnerNam
346347 export { route as postApiV1ReposOwnerNameIssuesNumberComments } from "./postApiV1ReposOwnerNameIssuesNumberComments.ts";
347348 export { route as postApiV1ReposOwnerNameIssuesNumberDependencies } from "./postApiV1ReposOwnerNameIssuesNumberDependencies.ts";
348349 export { route as postApiV1ReposOwnerNameIssuesNumberDependenciesBlockerConfirm } from "./postApiV1ReposOwnerNameIssuesNumberDependenciesBlockerConfirm.ts";
350 export { route as postApiV1ReposOwnerNameIssuesNumberEstimates } from "./postApiV1ReposOwnerNameIssuesNumberEstimates.ts";
349351 export { route as postApiV1ReposOwnerNameIssuesNumberPrivate } from "./postApiV1ReposOwnerNameIssuesNumberPrivate.ts";
350352 export { route as postApiV1ReposOwnerNameJobsIdAction } from "./postApiV1ReposOwnerNameJobsIdAction.ts";
351353 export { route as postApiV1ReposOwnerNameLabels } from "./postApiV1ReposOwnerNameLabels.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameIssuesNumberEstimates.ts added +10
@@ -0,0 +1,10 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/issues/{number}/estimates`,
6 summary: "Record an estimate against an issue: event (pull_opened, merged, live), p50 and p90 instants, a one-line basis; the forge resolves and scores it",
7 auth: true,
8 role: "member",
9 body: { event: "string", p50: "string", p90: "string", basis: "string" },
10 };
src/core/estimates.ts added +203
@@ -0,0 +1,203 @@
1 /**
2 * Estimates against an issue (#11955): rows kept, never edited. The forge sets
3 * the actual instant when the event happens (`settleEvent`, `settleLive`) and
4 * voids what an abandoned issue leaves open (`voidOpen`); nobody does it by hand.
5 * Plain data in and out; the base rate and the scores are `flow/`.
6 */
7 import type { Database } from "bun:sqlite";
8
9 export const EVENTS = ["pull_opened", "merged", "live"] as const;
10 export type EstimateEvent = (typeof EVENTS)[number];
11 export const isEvent = (v: unknown): v is EstimateEvent => typeof v === "string" && (EVENTS as readonly string[]).includes(v);
12
13 export type EstimateState = "open" | "resolved" | "void";
14
15 export interface EstimateRow {
16 readonly id: number;
17 readonly repoId: string;
18 readonly issueId: string;
19 readonly issueNumber: number;
20 readonly event: EstimateEvent;
21 readonly p50At: string;
22 readonly p90At: string;
23 readonly madeAt: string;
24 readonly byId: string;
25 readonly byName: string;
26 readonly byKind: "person" | "agent";
27 readonly basis: string;
28 /** The base rate shown when it was made: the raw JSON; `flow/estimate_base.ts` reads it. */
29 readonly baseJson: string;
30 readonly size: string;
31 readonly kind: string;
32 readonly actualAt: string | null;
33 readonly voidedAt: string | null;
34 readonly state: EstimateState;
35 }
36
37 interface Raw {
38 id: number;
39 repo_id: string;
40 issue_id: string;
41 number: number;
42 event: EstimateEvent;
43 p50_at: string;
44 p90_at: string;
45 made_at: string;
46 by_id: string;
47 username: string;
48 by_kind: "person" | "agent";
49 basis: string;
50 base_json: string;
51 size: string;
52 kind: string;
53 actual_at: string | null;
54 voided_at: string | null;
55 }
56
57 const SELECT = `SELECT e.id, e.repo_id, e.issue_id, i.number, e.event, e.p50_at, e.p90_at, e.made_at, e.by_id,
58 u.username, e.by_kind, e.basis, e.base_json, e.size, e.kind, e.actual_at, e.voided_at
59 FROM issue_estimate e JOIN issue i ON i.id = e.issue_id JOIN user u ON u.id = e.by_id`;
60
61 const toRow = (r: Raw): EstimateRow => ({
62 id: r.id,
63 repoId: r.repo_id,
64 issueId: r.issue_id,
65 issueNumber: r.number,
66 event: r.event,
67 p50At: r.p50_at,
68 p90At: r.p90_at,
69 madeAt: r.made_at,
70 byId: r.by_id,
71 byName: r.username,
72 byKind: r.by_kind,
73 basis: r.basis,
74 baseJson: r.base_json,
75 size: r.size,
76 kind: r.kind,
77 actualAt: r.actual_at,
78 voidedAt: r.voided_at,
79 state: r.voided_at !== null ? "void" : r.actual_at !== null ? "resolved" : "open",
80 });
81
82 export interface NewEstimate {
83 readonly repoId: string;
84 readonly issueId: string;
85 readonly event: EstimateEvent;
86 readonly p50At: string;
87 readonly p90At: string;
88 readonly madeAt: string;
89 readonly byId: string;
90 readonly byKind: "person" | "agent";
91 readonly basis: string;
92 readonly baseJson: string;
93 readonly size: string;
94 readonly kind: string;
95 }
96
97 /**
98 * Keep one estimate. Rows are only added: the older one for the same event is superseded by being
99 * older.
100 */
101 export function addEstimate(db: Database, e: NewEstimate): number {
102 return Number(
103 db
104 .query(
105 `INSERT INTO issue_estimate (repo_id, issue_id, event, p50_at, p90_at, made_at, by_id, by_kind, basis, base_json, size, kind)
106 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)`,
107 )
108 .run(e.repoId, e.issueId, e.event, e.p50At, e.p90At, e.madeAt, e.byId, e.byKind, e.basis, e.baseJson, e.size, e.kind)
109 .lastInsertRowid,
110 );
111 }
112
113 /** Every estimate on an issue, oldest first: the revisions are data. */
114 export function estimatesOf(db: Database, issueId: string): EstimateRow[] {
115 return db.query<Raw, [string]>(`${SELECT} WHERE e.issue_id = ?1 ORDER BY e.id`).all(issueId).map(toRow);
116 }
117
118 /** What each event stands at now: the newest estimate per event (events in their order). */
119 export function currentOf(rows: readonly EstimateRow[]): EstimateRow[] {
120 const latest = new Map<EstimateEvent, EstimateRow>();
121 for (const r of rows) latest.set(r.event, r);
122 return EVENTS.flatMap((ev) => latest.get(ev) ?? []);
123 }
124
125 /**
126 * The newest estimate per event for each issue number of a repository, for a list's rows (one
127 * read).
128 */
129 export function currentByNumber(db: Database, repoId: string, numbers: readonly number[]): Map<number, EstimateRow[]> {
130 const out = new Map<number, EstimateRow[]>();
131 if (numbers.length === 0) return out;
132 const want = new Set(numbers);
133 const all = db.query<Raw, [string]>(`${SELECT} WHERE e.repo_id = ?1 ORDER BY e.id`).all(repoId).map(toRow);
134 const byIssue = new Map<number, EstimateRow[]>();
135 for (const r of all) if (want.has(r.issueNumber)) byIssue.set(r.issueNumber, [...(byIssue.get(r.issueNumber) ?? []), r]);
136 for (const [n, rows] of byIssue) out.set(n, currentOf(rows));
137 return out;
138 }
139
140 /**
141 * Every estimate of a repository, or of every repository when none is named: what the scorecards
142 * read.
143 */
144 export function allEstimates(db: Database, repoId?: string): EstimateRow[] {
145 return (
146 repoId === undefined
147 ? db.query<Raw, []>(`${SELECT} ORDER BY e.id`).all()
148 : db.query<Raw, [string]>(`${SELECT} WHERE e.repo_id = ?1 ORDER BY e.id`).all(repoId)
149 ).map(toRow);
150 }
151
152 /**
153 * The event happened for these issue numbers: their open estimates for it get the actual instant.
154 * Returns how many.
155 */
156 export function settleEvent(db: Database, repoId: string, numbers: readonly number[], event: EstimateEvent, at: string): number {
157 let n = 0;
158 for (const number of numbers)
159 n += db
160 .query(
161 `UPDATE issue_estimate SET actual_at = ?4
162 WHERE event = ?3 AND actual_at IS NULL AND voided_at IS NULL
163 AND issue_id = (SELECT id FROM issue WHERE repo_id = ?1 AND number = ?2)`,
164 )
165 .run(repoId, number, event, at).changes;
166 return n;
167 }
168
169 /**
170 * A release went live: every open `live` estimate whose issue merged at or before the
171 * release was cut is resolved at `liveAt`. `mergedAt` says when the pull that closed
172 * an issue merged (the caller reads pulls; this module reads none).
173 */
174 export function settleLive(
175 db: Database,
176 cutAt: string,
177 liveAt: string,
178 mergedAt: (repoId: string, number: number) => string | undefined,
179 ): number {
180 const open = db
181 .query<{ id: number; repo_id: string; number: number }, []>(
182 `SELECT e.id, e.repo_id, i.number FROM issue_estimate e JOIN issue i ON i.id = e.issue_id
183 WHERE e.event = 'live' AND e.actual_at IS NULL AND e.voided_at IS NULL`,
184 )
185 .all();
186 let n = 0;
187 for (const r of open) {
188 const merged = mergedAt(r.repo_id, r.number);
189 if (merged === undefined || merged > cutAt) continue;
190 n += db.query(`UPDATE issue_estimate SET actual_at = ?2 WHERE id = ?1 AND actual_at IS NULL AND voided_at IS NULL`).run(r.id, liveAt).changes;
191 }
192 return n;
193 }
194
195 /**
196 * An issue closed as split, not-now or duplicate: what it left open is kept, marked void, never
197 * scored.
198 */
199 export function voidOpen(db: Database, issueId: string, at: string = new Date().toISOString()): number {
200 return db
201 .query(`UPDATE issue_estimate SET voided_at = ?2 WHERE issue_id = ?1 AND actual_at IS NULL AND voided_at IS NULL`)
202 .run(issueId, at).changes;
203 }
src/core/event_audience.ts +1
@@ -56,6 +56,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
5656 // the admins' (`repo.upstream_follow`).
5757 "repo.following",
5858 "issue.labeled",
59 "issue.estimated",
5960 "issue.first",
6061 "issue.ranked",
6162 "week.retro",
src/core/issues.ts +3
@@ -4,6 +4,7 @@
44 * expect to cite them. Comments and labels attach to the shared row.
55 */
66
7 import { voidOpen } from "./estimates.ts";
78 import type { Database } from "bun:sqlite";
89 import { id } from "../kernel/id.ts";
910 import { err, ok, type Result } from "../kernel/result.ts";
@@ -548,6 +549,8 @@ export function setIssueState(
548549 WHERE id = ?4 AND state != ?1`,
549550 )
550551 .run(state, closedAt, now, issueId, why, parked).changes;
552 // Split, dropped or parked: its open estimates are void, never scored (#11955).
553 if (changed > 0 && state === "closed" && (reason === "dropped" || reason === "split")) voidOpen(db, issueId, now);
551554 return changed > 0 ? getIssueById(db, issueId) : undefined;
552555 }
553556
src/core/migration-pins/20261113200000-issue-estimates.pin added +1
@@ -0,0 +1,1 @@
1 dfe23c0041426dfe2c241a8ef21756e483583eaffd04ccd8e3cfa04e2afa21db
src/core/migrations/20261113200000-issue-estimates.ts added +27
@@ -0,0 +1,27 @@
1 // Estimates of when an issue's work happens (#11955): one row per estimate, never edited.
2 // A new estimate for the same issue and event supersedes the old one on the page; the old
3 // rows stay as data. The forge alone sets `actual_at` (the event happened) or `voided_at`
4 // (the issue closed as split, not-now or duplicate). `base_json` is the base rate shown
5 // when the estimate was made, so the history itself can be scored. Additive: one table.
6 export default `
7 CREATE TABLE issue_estimate (
8 id INTEGER PRIMARY KEY AUTOINCREMENT,
9 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
10 issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
11 event TEXT NOT NULL CHECK (event IN ('pull_opened','merged','live')),
12 p50_at TEXT NOT NULL,
13 p90_at TEXT NOT NULL,
14 made_at TEXT NOT NULL,
15 by_id TEXT NOT NULL REFERENCES user(id),
16 by_kind TEXT NOT NULL CHECK (by_kind IN ('person','agent')),
17 basis TEXT NOT NULL DEFAULT '',
18 base_json TEXT NOT NULL DEFAULT 'null',
19 size TEXT NOT NULL,
20 kind TEXT NOT NULL DEFAULT '',
21 actual_at TEXT,
22 voided_at TEXT
23 );
24 CREATE INDEX issue_estimate_issue ON issue_estimate(issue_id, event, id);
25 CREATE INDEX issue_estimate_open ON issue_estimate(event, repo_id) WHERE actual_at IS NULL AND voided_at IS NULL;
26 CREATE INDEX issue_estimate_repo ON issue_estimate(repo_id, made_at);
27 `;
src/core/pulls.ts +8
@@ -6,6 +6,7 @@
66 * Forgejo left open (#30972).
77 */
88
9 import { settleEvent } from "./estimates.ts";
910 import { getRepoById } from "./repos.ts";
1011 import { repoDir } from "../git/repos.ts";
1112 import { sealedByNumber } from "./sealed.ts";
@@ -325,6 +326,8 @@ export async function createPull(
325326 await writeRef(at, `refs/pull/${issue.value.number}/head`, headOid);
326327
327328 const pull = join(db, issue.value)!;
329 // The issues this pull closes had a pull opened: their estimates for it are resolved (#11955).
330 settleEvent(db, input.repoId, closesFromBody(input.body ?? ""), "pull_opened", issue.value.createdAt);
328331 // A kept fork's pull is combined with main on our side (#9012).
329332 if (at === dir && fromKeptFork(db, pull))
330333 await combine(dir, { number: pull.number, baseOid, headOid });
@@ -1284,6 +1287,11 @@ function closeAsMerged(
12841287 landed.carried === true ? 1 : 0,
12851288 );
12861289 setIssueState(db, pullId, "closed");
1290 // The issues it closes have merged (#11955).
1291 const row = db
1292 .query<{ repo_id: string; body: string }, [string]>("SELECT repo_id, body FROM issue WHERE id = ?1")
1293 .get(pullId);
1294 if (row !== null) settleEvent(db, row.repo_id, closesFromBody(row.body), "merged", now);
12871295 });
12881296 }
12891297
src/crew/brief.ts +7
@@ -369,6 +369,12 @@ export function taskPrompt(input: TaskInput): string {
369369 const MCP_SIZE_RULE =
370370 "This issue touches the MCP. Run `bun test test/mcp-size.test.ts` before pushing; it names the five costliest tools when it fails. Prefer an `action` or `kind` on an existing tool (docs/MCP.md, \"Room for a new tool\") over a new tool, and never raise the ceilings.";
371371
372 /**
373 * A time promised to the owner is a record first (#11955); the task prompt carries it, not the system brief, to keep that short.
374 */
375 export const ESTIMATE_RULE =
376 'A "by <time>" you say to the owner is recorded first with the `estimate` tool (ask it for the issue\'s base rate, then record `event` pull_opened, merged or live with `p50` and `p90` instants and a one-line `basis`), or it is not said. The forge resolves it when the event happens and scores it.';
377
372378 /** A plan on the issue is how a person sees where a run is without reading its log; only the forge serves the tool. */
373379 const PLAN_RULE =
374380 "Keep a short plan on this issue with the `keep_plan` tool (up to 12 items, replaced whole each time): call it once you have read the code and again as items finish, so a person sees where you are without a log.";
@@ -475,6 +481,7 @@ function taskBody(input: TaskInput): string {
475481 if (input.pull === undefined && isForge(input.repo) && namesMcp(issue.title, issue.body))
476482 out.push("", MCP_SIZE_RULE);
477483 if (input.pull === undefined && isForge(input.repo)) out.push("", PLAN_RULE);
484 if (input.pull === undefined && isForge(input.repo)) out.push("", ESTIMATE_RULE);
478485 out.push(
479486 "",
480487 `Work it on the branch \`${input.branch}\` and push when done.`,
src/flow/estimate_base.ts added +177
@@ -0,0 +1,177 @@
1 /**
2 * The base rate for an issue (#11955): how long past issues like it took from the
3 * start of work to each event, from the forge's own history. Measured, never
4 * guessed; the same history gives the same answer. Plain data in and out;
5 * `historySamples` is the one read.
6 *
7 * Start of work is the first agent run on the issue, else its creation. Time
8 * waiting in the queue is therefore not in the rates: it is said beside them
9 * (`flow/estimate_now.ts`). Quantiles are nearest-rank over the sorted
10 * durations, `sorted[round((n - 1) * q)]`, so a test can do it by hand.
11 */
12 import type { Database } from "bun:sqlite";
13 import type { EstimateEvent } from "../core/estimates.ts";
14 import { closesFromBody } from "../core/pulls.ts";
15 import { kindOf, labelsOf, sizeOf, type Size } from "./estimate.ts";
16 import { durationWords } from "./estimate_words.ts";
17
18 /** Samples a group needs before it speaks plainly. */
19 export const MIN_BASE = 5;
20 const DAY = 86_400_000;
21 /** The most merged pulls one read walks. */
22 const PULLS_MAX = 600;
23
24 export interface HistorySample {
25 readonly number: number;
26 readonly size: Size;
27 readonly kind: string;
28 readonly builder: string | null;
29 /**
30 * Milliseconds from the start of work to each event; live is absent when no release since the
31 * merge has served.
32 */
33 readonly pull: number;
34 readonly merged: number;
35 readonly live: number | undefined;
36 readonly mergedAtMs: number;
37 }
38
39 export interface EventRate {
40 readonly n: number;
41 /** From now, in ms. */
42 readonly p50Ms: number;
43 readonly p90Ms: number;
44 readonly p50At: string;
45 readonly p90At: string;
46 }
47
48 export interface BaseRate {
49 readonly n: number;
50 /** True when fewer than {@link MIN_BASE} samples were found even after widening. */
51 readonly thin: boolean;
52 /** What was widened, in order, e.g. ["dropped the builder", "dropped the kind"]. */
53 readonly widened: readonly string[];
54 readonly basis: string;
55 readonly events: Record<EstimateEvent, EventRate | null>;
56 }
57
58 /** Nearest-rank quantile of an ascending array. */
59 export const quantile = (sorted: readonly number[], q: number): number => sorted[Math.round((sorted.length - 1) * q)]!;
60 const ascending = (xs: readonly number[]): number[] => [...xs].sort((a, b) => a - b);
61
62 /**
63 * Past issues finished in the window: merged pulls that closed them, with when work started and
64 * when each release went live.
65 */
66 export function historySamples(db: Database, repoId: string, sinceMs: number, nowMs: number): HistorySample[] {
67 const since = new Date(sinceMs).toISOString();
68 const pulls = db
69 .query<{ body: string; opened: string; merged: string }, [string, string, number]>(
70 `SELECT i.body, i.created_at AS opened, p.merged_at AS merged FROM pull p JOIN issue i ON i.id = p.issue_id
71 WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL AND p.merged_at >= ?2 ORDER BY p.merged_at DESC LIMIT ?3`,
72 )
73 .all(repoId, since, PULLS_MAX);
74 const closed = new Map<number, { opened: string; merged: string }>();
75 for (const p of pulls) for (const n of closesFromBody(p.body)) if (!closed.has(n)) closed.set(n, p);
76 if (closed.size === 0) return [];
77 const issues = db
78 .query<{ id: string; number: number; title: string; body: string; created_at: string; assignee: string | null; started: string | null }, [string]>(
79 `SELECT i.id, i.number, i.title, i.body, i.created_at, a.username AS assignee,
80 (SELECT MIN(r.created_at) FROM run r WHERE r.issue_id = i.id AND r.kind = 'agent') AS started
81 FROM issue i LEFT JOIN user a ON a.id = i.assignee_id
82 WHERE i.repo_id = ?1 AND i.kind = 'issue' AND i.state = 'closed' AND i.close_reason = 'done'`,
83 )
84 .all(repoId)
85 .filter((i) => closed.has(i.number));
86 const labels = labelsOf(db, issues.map((i) => i.id));
87 const releases = db
88 .query<{ cut_at: string; live_at: string }, [string]>(
89 `SELECT cut_at, live_at FROM keeper_release WHERE live_at IS NOT NULL AND stage != 'rolled_back' AND cut_at >= ?1 ORDER BY cut_at`,
90 )
91 .all(since);
92 const out: HistorySample[] = [];
93 for (const i of issues) {
94 const c = closed.get(i.number)!;
95 const start = Date.parse(i.started ?? i.created_at);
96 const merged = Date.parse(c.merged);
97 const opened = Date.parse(c.opened);
98 if (![start, merged, opened].every(Number.isFinite) || merged < start || merged > nowMs) continue;
99 const release = releases.find((r) => r.cut_at >= c.merged);
100 const live = release === undefined ? undefined : Date.parse(release.live_at);
101 out.push({
102 number: i.number,
103 size: sizeOf(i),
104 kind: kindOf(labels.get(i.id) ?? []),
105 builder: i.assignee,
106 pull: Math.max(0, Math.min(opened, merged) - start),
107 merged: merged - start,
108 live: live === undefined || !Number.isFinite(live) || live < merged ? undefined : live - start,
109 mergedAtMs: merged,
110 });
111 }
112 return out;
113 }
114
115 export interface Target {
116 readonly size: Size;
117 readonly kind: string;
118 readonly builder: string | null;
119 /** Milliseconds since work started on it; 0 when it has not. */
120 readonly elapsedMs: number;
121 }
122
123 /**
124 * From now: those still running at `elapsed` count what is left; if fewer than {@link MIN_BASE}
125 * still run, all count in full.
126 */
127 function fromNow(durations: readonly number[], elapsedMs: number, nowMs: number): EventRate | null {
128 if (durations.length === 0) return null;
129 const running = durations.filter((d) => d > elapsedMs).map((d) => d - elapsedMs);
130 const left = ascending(elapsedMs > 0 && running.length >= MIN_BASE ? running : durations);
131 const p50Ms = quantile(left, 0.5);
132 const p90Ms = quantile(left, 0.9);
133 return { n: durations.length, p50Ms, p90Ms, p50At: new Date(nowMs + p50Ms).toISOString(), p90At: new Date(nowMs + p90Ms).toISOString() };
134 }
135
136 /**
137 * The base rate of `target` among `samples` (all within 90 days), widening until {@link MIN_BASE}
138 * are found.
139 */
140 export function baseRate(samples: readonly HistorySample[], target: Target, where: string, nowMs: number): BaseRate {
141 const inDays = (days: number) => samples.filter((s) => s.mergedAtMs >= nowMs - days * DAY);
142 const levels: { widen: string | null; pick: () => HistorySample[]; who: string }[] = [
143 ...(target.builder === null
144 ? []
145 : [{ widen: null, who: `${target.size} ${target.kind === "" ? "" : `${target.kind} `}issues by ${target.builder}, last 30 days`, pick: () => inDays(30).filter((s) => s.size === target.size && s.kind === target.kind && s.builder === target.builder) }]),
146 { widen: target.builder === null ? null : "dropped the builder", who: `${target.size} ${target.kind === "" ? "" : `${target.kind} `}issues, last 30 days`, pick: () => inDays(30).filter((s) => s.size === target.size && s.kind === target.kind) },
147 { widen: "dropped the kind", who: `${target.size} issues, last 30 days`, pick: () => inDays(30).filter((s) => s.size === target.size) },
148 { widen: "dropped the size", who: "issues of any size, last 30 days", pick: () => inDays(30) },
149 { widen: "widened to 90 days", who: "issues of any size, last 90 days", pick: () => inDays(90) },
150 ];
151 const widened: string[] = [];
152 let used = levels[levels.length - 1]!;
153 let group: HistorySample[] = [];
154 for (const level of levels) {
155 if (level.widen !== null) widened.push(level.widen);
156 group = level.pick();
157 used = level;
158 if (group.length >= MIN_BASE) break;
159 }
160 const thin = group.length < MIN_BASE;
161 const events: Record<EstimateEvent, EventRate | null> = {
162 pull_opened: fromNow(group.map((s) => s.pull), target.elapsedMs, nowMs),
163 merged: fromNow(group.map((s) => s.merged), target.elapsedMs, nowMs),
164 live: fromNow(group.flatMap((s) => (s.live === undefined ? [] : [s.live])), target.elapsedMs, nowMs),
165 };
166 const merged = events.merged;
167 const live = events.live;
168 const stage = group.flatMap((s) => (s.live === undefined ? [] : [s.live - s.merged])).sort((a, b) => a - b);
169 const parts = [
170 merged === null ? "nothing merged yet" : `${target.elapsedMs > 0 ? "now→merged" : "work start→merged"} p50 ${durationWords(merged.p50Ms)}, p90 ${durationWords(merged.p90Ms)}`,
171 stage.length === 0 || live === null ? "no release has gone live since" : `merged→live p50 ${durationWords(quantile(stage, 0.5))}, p90 ${durationWords(quantile(stage, 0.9))}`,
172 ];
173 const basis = thin
174 ? `only ${group.length} ${used.who} in ${where} (fewer than ${MIN_BASE}; ${widened.length === 0 ? "nothing wider to try" : widened.join(", ")}): ${parts.join("; ")}`
175 : `${group.length} ${used.who} in ${where}${widened.length === 0 ? "" : ` (${widened.join(", ")})`}: ${parts.join("; ")}`;
176 return { n: group.length, thin, widened, basis, events };
177 }
src/flow/estimate_score.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * Scoring estimates (#11955). For each estimate resolved: ratio = actual duration /
3 * p50 duration, both from the moment it was made. The median ratio is the bias
4 * (2.4 means it runs 2.4× late: optimistic); the p90 hit rate is the share whose
5 * actual instant was at or before the p90 (should be about 90%).
6 *
7 * One estimate counts per estimator, issue and event: the first one, so a revision
8 * after the fact cannot improve a score (later ones are kept as data and shown, not scored).
9 * The base rate shown at that moment is scored the same way as an estimator named
10 * `history`. Void estimates are counted, never scored. Plain data in and out.
11 */
12 import type { EstimateEvent, EstimateRow, EstimateState } from "../core/estimates.ts";
13 import { ratioOf, timesWords } from "./estimate_words.ts";
14
15 export const HISTORY = "history";
16 /** How many of an estimator's most recent resolved estimates the headline reads. */
17 export const LAST = 20;
18
19 export interface Scored {
20 readonly who: string;
21 readonly issueNumber: number;
22 readonly event: EstimateEvent;
23 readonly size: string;
24 readonly kind: string;
25 readonly madeAt: string;
26 readonly p50At: string;
27 readonly p90At: string;
28 readonly actualAt: string | null;
29 readonly state: EstimateState;
30 }
31
32 export interface Score {
33 readonly who: string;
34 /** "" for all of an estimator's work, else "small bug": a size and kind. */
35 readonly group: string;
36 readonly resolved: number;
37 readonly void: number;
38 readonly open: number;
39 /** Median of actual/p50 over the resolved; null with none. */
40 readonly medianRatio: number | null;
41 /** Share of the resolved whose actual was at or before the p90, 0..1; null with none. */
42 readonly p90Hit: number | null;
43 }
44
45 /** Median: the middle one, or the mean of the middle two. */
46 export function median(xs: readonly number[]): number | null {
47 if (xs.length === 0) return null;
48 const s = [...xs].sort((a, b) => a - b);
49 const mid = s.length >> 1;
50 return s.length % 2 === 1 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;
51 }
52
53 /**
54 * The estimates that count: each estimator's first per issue and event, plus the history's first
55 * per issue and event.
56 */
57 export function scoredEstimates(rows: readonly EstimateRow[]): Scored[] {
58 const seen = new Set<string>();
59 const firstOfIssueEvent = new Set<string>();
60 const out: Scored[] = [];
61 const base = (r: EstimateRow, who: string, p50At: string, p90At: string): Scored => ({
62 who, issueNumber: r.issueNumber, event: r.event, size: r.size, kind: r.kind, madeAt: r.madeAt, p50At, p90At, actualAt: r.actualAt, state: r.state,
63 });
64 for (const r of rows) {
65 const key = `${r.issueId}/${r.event}`;
66 if (!firstOfIssueEvent.has(key)) {
67 firstOfIssueEvent.add(key);
68 try {
69 const b = JSON.parse(r.baseJson) as { events?: Record<string, { p50At?: string; p90At?: string } | null> } | null;
70 const h = b?.events?.[r.event];
71 if (typeof h?.p50At === "string" && typeof h.p90At === "string") out.push(base(r, HISTORY, h.p50At, h.p90At));
72 } catch {
73 // A base that does not read is not scored; the estimate still is.
74 }
75 }
76 const mine = `${key}/${r.byName}`;
77 if (seen.has(mine)) continue;
78 seen.add(mine);
79 out.push(base(r, r.byName, r.p50At, r.p90At));
80 }
81 return out;
82 }
83
84 const groupOf = (s: Pick<Scored, "size" | "kind">): string => (s.kind === "" ? s.size : `${s.size} ${s.kind}`);
85
86 function tally(who: string, group: string, rows: readonly Scored[], last?: number): Score {
87 const resolved = rows
88 .filter((s) => s.state === "resolved" && s.actualAt !== null)
89 .sort((a, b) => (a.actualAt! < b.actualAt! ? -1 : a.actualAt! > b.actualAt! ? 1 : 0));
90 const read = last === undefined ? resolved : resolved.slice(-last);
91 const ratios = read.flatMap((s) => ratioOf(s) ?? []);
92 const held = read.filter((s) => Date.parse(s.actualAt!) <= Date.parse(s.p90At)).length;
93 return {
94 who,
95 group,
96 resolved: resolved.length,
97 void: rows.filter((s) => s.state === "void").length,
98 open: rows.filter((s) => s.state === "open").length,
99 medianRatio: median(ratios),
100 p90Hit: read.length === 0 ? null : held / read.length,
101 };
102 }
103
104 /**
105 * One score per estimator over all its estimates, then one per size and kind, the estimators in
106 * name order and `history` last.
107 */
108 export function scoreboard(rows: readonly EstimateRow[], last?: number): Score[] {
109 const scored = scoredEstimates(rows);
110 const who = [...new Set(scored.map((s) => s.who))].sort((a, b) => (a === HISTORY ? 1 : b === HISTORY ? -1 : a < b ? -1 : 1));
111 return who.flatMap((w) => {
112 const mine = scored.filter((s) => s.who === w);
113 const groups = [...new Set(mine.map(groupOf))].sort();
114 return [tally(w, "", mine, last), ...groups.map((g) => tally(w, g, mine.filter((s) => groupOf(s) === g), last))];
115 });
116 }
117
118 /**
119 * "median 2.4× late, p90 held 55%": the bias and the p90 in words; undefined with nothing resolved.
120 */
121 export function biasWords(s: Pick<Score, "medianRatio" | "p90Hit">): string | undefined {
122 if (s.medianRatio === null || s.p90Hit === null) return undefined;
123 const r = s.medianRatio;
124 const bias = r >= 1.05 ? `${timesWords(r)} late` : r > 0 && r <= 1 / 1.05 ? `${timesWords(1 / r)} early` : "on the mark";
125 return `median ${bias}, p90 held ${Math.round(s.p90Hit * 100)}%`;
126 }
127
128 /**
129 * "your last 20: median 2.4× late, p90 held 55%" for one estimator; says so when nothing has
130 * resolved yet.
131 */
132 export function lastLine(rows: readonly EstimateRow[], who: string, you = false): string {
133 const s = scoreboard(rows, LAST).find((x) => x.who === who && x.group === "");
134 const words = s === undefined ? undefined : biasWords(s);
135 const count = s === undefined ? 0 : Math.min(s.resolved, LAST);
136 const head = `${you ? "your" : `${who}'s`} last ${count}`;
137 return words === undefined ? `${you ? "you have" : `${who} has`} no resolved estimates yet` : `${head}: ${words}`;
138 }
src/flow/estimate_words.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * Estimates in words (#11955): durations as "3 h 10 m", instants as "Fri 07:15"
3 * in UTC (the page says UTC), the one line on an issue and on a /next row.
4 * Plain data in, plain strings out; no clock read except what is passed.
5 */
6 import { EVENTS, type EstimateEvent, type EstimateRow } from "../core/estimates.ts";
7
8 const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
9 const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] as const;
10 const two = (n: number): string => String(n).padStart(2, "0");
11
12 /** "25 m", "3 h 10 m", "9 h", "2 d 4 h": whole minutes below a day, hours above. */
13 export function durationWords(ms: number): string {
14 const minutes = Math.max(0, Math.round(ms / 60_000));
15 if (minutes < 60) return `${minutes} m`;
16 const hours = Math.floor(minutes / 60);
17 if (hours < 48) return minutes % 60 === 0 ? `${hours} h` : `${hours} h ${minutes % 60} m`;
18 const days = Math.floor(hours / 24);
19 return hours % 24 === 0 ? `${days} d` : `${days} d ${hours % 24} h`;
20 }
21
22 /** "Fri 07:15" UTC; with the date when it is a week or more from `now`. */
23 export function instantWords(iso: string, now: number): string {
24 const d = new Date(iso);
25 const clock = `${two(d.getUTCHours())}:${two(d.getUTCMinutes())}`;
26 const near = Math.abs(d.getTime() - now) < 6 * 86_400_000;
27 return near ? `${DAYS[d.getUTCDay()]} ${clock}` : `${DAYS[d.getUTCDay()]} ${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${clock}`;
28 }
29
30 export const EVENT_WORDS: Record<EstimateEvent, string> = {
31 pull_opened: "pull opened",
32 merged: "merged",
33 live: "live",
34 };
35 const WENT: Record<EstimateEvent, string> = { pull_opened: "pull opened", merged: "merged", live: "went live" };
36
37 /**
38 * What an estimate was: actual over the p50 duration, both from the moment it was made; undefined
39 * when not resolved or degenerate.
40 */
41 export function ratioOf(r: Pick<EstimateRow, "madeAt" | "p50At" | "actualAt">): number | undefined {
42 if (r.actualAt === null) return undefined;
43 const planned = Date.parse(r.p50At) - Date.parse(r.madeAt);
44 const took = Date.parse(r.actualAt) - Date.parse(r.madeAt);
45 return planned > 0 && took >= 0 ? took / planned : undefined;
46 }
47
48 export const timesWords = (ratio: number): string => `${(Math.round(ratio * 10) / 10).toFixed(1)}×`;
49
50 /**
51 * The base rate's p50 instant for an event, as it stood when the estimate was made, or undefined.
52 */
53 export function historySays(r: Pick<EstimateRow, "baseJson">, event: EstimateEvent): string | undefined {
54 try {
55 const base = JSON.parse(r.baseJson) as { events?: Record<string, { p50At?: string } | null> } | null;
56 return base?.events?.[event]?.p50At;
57 } catch {
58 return undefined;
59 }
60 }
61
62 /**
63 * The one line a promise carries. Open: "live by Fri 07:15 (90%: Fri 11:00) · steward ·
64 * history says Fri 09:40". Resolved: "went live Fri 10:02, 1.6× the estimate". Void: said so.
65 * The event shown is the furthest one estimated; undefined when there is none.
66 */
67 export function estimateLine(rows: readonly EstimateRow[], now: number): string | undefined {
68 const mine = [...rows].reverse();
69 const row = EVENTS.slice().reverse().map((ev) => mine.find((r) => r.event === ev)).find((r) => r !== undefined);
70 if (row === undefined) return undefined;
71 if (row.state === "resolved" && row.actualAt !== null) {
72 const ratio = ratioOf(row);
73 return `${WENT[row.event]} ${instantWords(row.actualAt, now)}${ratio === undefined ? "" : `, ${timesWords(ratio)} the estimate`}`;
74 }
75 if (row.state === "void") return `estimate void: the issue closed without the work`;
76 const says = historySays(row, row.event);
77 return `${EVENT_WORDS[row.event]} by ${instantWords(row.p50At, now)} (90%: ${instantWords(row.p90At, now)}) · ${row.byName}${says === undefined ? "" : ` · history says ${instantWords(says, now)}`}`;
78 }
src/http/api/issues.ts +23
@@ -7,6 +7,8 @@
77
88 import { holds, weakEtag } from "../etag.ts";
99 import { ISSUE_TEAMS_SAY, nameTeams } from "../../actions/issue_teams.ts";
10 import { askEstimate, recordEstimate } from "../../actions/estimates.ts";
11 import { estimatesOf } from "../../core/estimates.ts";
1012 import { confirmIssue, dependencyWords, linkIssue, unlinkIssue } from "../../actions/dependencies.ts";
1113 import {
1214 addCommentThrough,
@@ -327,6 +329,27 @@ export function issueRoutes(router: Router<Handler>): void {
327329 return json({ repo: there, clone: `${ctx.url.origin}/${there}.git` }, 201);
328330 });
329331
332 // Estimates (#11955): GET asks the base rate; POST records one.
333 router.add("GET", "/api/v1/repos/:owner/:name/issues/:number/estimates", (ctx) => {
334 const found = loadIssue(ctx);
335 if ("error" in found) return found.error;
336 return json({
337 ...askEstimate(ctx.app, ctx.auth.user, found.repo, found.issue),
338 revisions: estimatesOf(ctx.app.db, found.issue.id),
339 });
340 });
341 router.add("POST", "/api/v1/repos/:owner/:name/issues/:number/estimates", async (ctx) => {
342 const denied = requireScope(ctx, "rw");
343 if (denied) return denied;
344 const found = loadIssue(ctx);
345 if ("error" in found) return found.error;
346 if (ctx.auth.user === undefined) return apiError("unauthorized", 401, "sign in to record an estimate");
347 const input = await body(ctx.request);
348 const made = recordEstimate(ctx.app, ctx.auth.user, found.repo, found.issue, input);
349 return made.ok
350 ? json(made.value, 201)
351 : apiError(made.error.kind, made.error.kind === "forbidden" ? 403 : 422, made.error.message);
352 });
330353 router.add(
331354 "GET",
332355 "/api/v1/repos/:owner/:name/issues/:number/dependencies",
src/http/mcp/tools/estimate.ts added +38
@@ -0,0 +1,38 @@
1 import { askEstimate, estimateIssue, recordEstimate } from "../../../actions/estimates.ts";
2 import { bad, good, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
3 import { mayView } from "../../../core/sealed.ts";
4
5 export const tool: Tool = {
6 name: "estimate",
7 doc: "`{ repo, issue, event?, p50?, p90?, basis? }`: with no times, the base rate for that issue from the forge's own history (p50/p90 instants and durations per event, sample size, one line of basis, what is true now, and your scorecard); with `event` (`pull_opened`, `merged`, `live`), `p50` and `p90` (future instants, p50 ≤ p90) it records an estimate, which the forge resolves when the event happens and a new one supersedes",
8 description: "Ask an issue's base rate, or record `event` with `p50`, `p90` (instants) and `basis`.",
9 inputSchema: {
10 type: "object",
11 properties: {
12 repo: REPO_ARG,
13 issue: { type: "integer", minimum: 1 },
14 event: { type: "string", enum: ["pull_opened", "merged", "live"] },
15 p50: { type: "string", maxLength: 40 },
16 p90: { type: "string", maxLength: 40 },
17 basis: { type: "string", maxLength: 300 },
18 },
19 required: ["repo", "issue"],
20 },
21 writes: true,
22 readsWithout: "event",
23 run(ctx, user, args) {
24 const repo = repoArg(ctx, user, args);
25 if (isAnswer(repo)) return repo;
26 const issue = estimateIssue(ctx.app, repo, args["issue"] as number);
27 if (issue === undefined || !mayView(ctx.app.db, repo, issue, ctx.auth.user))
28 return bad("no_such_issue", `no issue #${String(args["issue"])}`);
29 if (args["event"] === undefined) return good(askEstimate(ctx.app, user, repo, issue));
30 const made = recordEstimate(ctx.app, user, repo, issue, {
31 event: args["event"],
32 p50: args["p50"],
33 p90: args["p90"],
34 basis: args["basis"],
35 });
36 return made.ok ? good({ says: `Recorded: ${made.value.base.basis}`, ...made.value }) : bad(made.error.kind, made.error.message);
37 },
38 };
src/http/mcp/tools/index.ts +1
@@ -57,6 +57,7 @@ export { tool as economics } from "./economics.ts";
5757 export { tool as edit } from "./edit.ts";
5858 export { tool as egress_grants } from "./egress_grants.ts";
5959 export { tool as email_verify } from "./email_verify.ts";
60 export { tool as estimate } from "./estimate.ts";
6061 export { tool as events } from "./events.ts";
6162 export { tool as explore } from "./explore.ts";
6263 export { tool as family } from "./family.ts";
src/keeper/record.ts +12 −2
@@ -9,6 +9,8 @@
99 * image, a hold stands).
1010 */
1111
12 import { settleLive } from "../core/estimates.ts";
13 import { mergedPullClosing } from "../core/pulls.ts";
1214 import type { Database } from "bun:sqlite";
1315 import type { Tally } from "./verify.ts";
1416
@@ -159,8 +161,16 @@ export function countRollProbe(db: Database, id: number, ok: boolean): void {
159161
160162 /** The new version answers: the verify begins. Only one forge moves it, so a second caller gets false. */
161163 export function markLive(db: Database, id: number, at: number): boolean {
162 return db.query(`UPDATE keeper_release SET stage = 'verifying', live_at = ?2 WHERE id = ?1 AND stage = 'rolling'`).run(id, iso(at))
163 .changes === 1;
164 const moved =
165 db.query(`UPDATE keeper_release SET stage = 'verifying', live_at = ?2 WHERE id = ?1 AND stage = 'rolling'`).run(id, iso(at))
166 .changes === 1;
167 if (moved) {
168 // The release containing a merge is serving: those issues' `live` estimates resolve (#11955).
169 const cut = db.query<{ cut_at: string }, [number]>(`SELECT cut_at FROM keeper_release WHERE id = ?1`).get(id);
170 if (cut !== null)
171 settleLive(db, cut.cut_at, iso(at), (repoId, n) => mergedPullClosing(db, repoId, n)?.mergedAt ?? undefined);
172 }
173 return moved;
164174 }
165175
166176 /** The verify's numbers so far: the seconds dark it saw are added to the roll's. */
src/web/pages/flow-estimates.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * The estimate scorecard on /flow (#11955): per estimator, then per size and
3 * kind, how late (or early) the median estimate ran and how often the p90
4 * held. `history`, the forge's own base rate, is scored as one more estimator.
5 */
6 import { allEstimates } from "../../core/estimates.ts";
7 import type { Database } from "bun:sqlite";
8 import { biasWords, scoreboard, type Score } from "../../flow/estimate_score.ts";
9 import { html, type Html } from "../html.ts";
10 import { icon, row } from "../ui.ts";
11
12 const counts = (s: Score): string => `${String(s.resolved)} resolved · ${String(s.void)} void · ${String(s.open)} open`;
13
14 /** One row per score: "steward · small bug: median 2.4× late, p90 held 55% · 6 resolved …". */
15 export function estimatesSection(db: Database): Html {
16 const scores = scoreboard(allEstimates(db));
17 if (scores.length === 0) return html``;
18 return html`<h2>Estimates</h2>
19 <p class="muted small">Ratio is the actual time over the p50, both from the moment the estimate was made; the p90 should hold about 90% of the time. A revision after the fact is kept but not scored.</p>
20 <ul class="list mb" id="estimate-scores">${scores.map((s) =>
21 row({
22 lead: icon("activity"),
23 title: html`${s.who}${s.group === "" ? "" : ` · ${s.group}`}`,
24 meta: html`${biasWords(s) ?? "nothing resolved yet"} · ${counts(s)}`,
25 }),
26 )}</ul>`;
27 }
src/web/pages/flow.ts +2
@@ -24,6 +24,7 @@ import { handoverSection } from "./flow-handover.ts";
2424 import { readDrifts } from "../../flow/alarm_drift.ts";
2525 import { readHandoverLists } from "../../flow/handover_read.ts";
2626 import { readWaiting, waitingSection } from "./flow-waiting.ts";
27 import { estimatesSection } from "./flow-estimates.ts";
2728 import { clogSection, readClogView } from "./flow-clog.ts";
2829 import { cpuStopsSection } from "./flow-cpu.ts";
2930 import { cpuClosedPulls } from "../../flow/cpu_closed.ts";
@@ -108,6 +109,7 @@ export async function flowPage(ctx: Ctx): Promise<Response> {
108109 ${clogSection(readClogView(ctx.app.db))}
109110 ${cpuStopsSection(cpuStops(ctx.app.db).stopped, cpuClosedPulls(ctx.app.db, new Date()))}
110111 ${waitingSection(await readWaiting(ctx.app.db, ctx.app.reposRoot, new Date()))}
112 ${estimatesSection(ctx.app.db)}
111113 ${pipesSvg(p)}
112114 <p class="muted small">${money(p.usd)} spent in the last 7 days; ${plural(p.shipped, "pull")} shipped.</p>
113115 ${handoverSection(readHandoverLists(ctx.app.db, await readDrifts(ctx.app), Date.now()))}
src/web/pages/next.ts +8 −2
@@ -7,6 +7,8 @@
77 * beside each action (`j`/`k` choose the row), which post the same form.
88 */
99 import { placeOf, rankIssue, rankedWords, stepTo, type Place } from "../../actions/next.ts";
10 import { currentByNumber } from "../../core/estimates.ts";
11 import { estimateLine } from "../../flow/estimate_words.ts";
1012 import { nextUp, TOP, type NextRow } from "../../core/next_up.ts";
1113 import { openPullStages } from "../../flow/read.ts";
1214 import { stateWord, type StateFacts } from "./next_state.ts";
@@ -157,6 +159,7 @@ function line(
157159 position: number | null = null,
158160 state: string | null = null,
159161 mine = false,
162 promise: string | undefined = undefined,
160163 ): Html {
161164 const r = rows[at]!;
162165 const n = r.issue.number;
@@ -175,7 +178,7 @@ function line(
175178 title: r.issue.title,
176179 titleAttr: r.issue.title,
177180 lead: html`${position === null ? "·" : String(position)}`,
178 meta: html`${mine ? html`<span class="mine">Owner's pick</span> · ` : null}${r.role === "blocker" ? "Blocker" : "Enabler"} · #${n}${state === null ? "" : ` · ${state} · ${r.onIt ?? "next"}`} · ${r.roleWhy}${away ? null : html` · <span class="estimate">${rangeWords(priced.find((p) => p.number === n)?.estimate ?? { known: false, samples: 0, basis: "no estimate" })}</span>`}${state !== null || r.onIt === null ? "" : ` · on it: ${r.onIt}`}${r.why === null ? "" : ` · ${r.why}`}`,
181 meta: html`${mine ? html`<span class="mine">Owner's pick</span> · ` : null}${r.role === "blocker" ? "Blocker" : "Enabler"} · #${n}${state === null ? "" : ` · ${state} · ${r.onIt ?? "next"}`} · ${r.roleWhy}${away ? null : html` · <span class="estimate">${rangeWords(priced.find((p) => p.number === n)?.estimate ?? { known: false, samples: 0, basis: "no estimate" })}</span>`}${state !== null || r.onIt === null ? "" : ` · on it: ${r.onIt}`}${r.why === null ? "" : ` · ${r.why}`}${promise === undefined ? "" : ` · ${promise}`}`,
179182 nav: true,
180183 data: { number: String(n), ...(cost === undefined ? {} : { cost: String(cost) }) },
181184 ...(controls === null ? {} : { after: controls }),
@@ -209,6 +212,9 @@ export function nextPage(ctx: Ctx): Response {
209212 const { priced, cut, capacity, sentence } = weekView(ctx.app.db, repo.id, rows, new Date());
210213 const costs = rowCosts(priced);
211214 const stages = openPullStages(ctx.app.db, repo, scope, new Date(), new Set(rows.map((r) => r.issue.number)));
215 const promised = currentByNumber(ctx.app.db, repo.id, rows.map((r) => r.issue.number));
216 const nowMs = Date.now();
217 const promise = (r: NextRow): string | undefined => estimateLine(promised.get(r.issue.number) ?? [], nowMs);
212218 const facts = (r: NextRow): StateFacts => ({ stage: stages.get(r.issue.number) ?? "issue", waits: r.waits, held: r.state === "held", onIt: r.onIt !== null });
213219 // One numbered order, folded: the first TOP rows open, what comes after, then Later.
214220 // A filter hides rows but keeps each one's place in the whole ranking.
@@ -220,7 +226,7 @@ export function nextPage(ctx: Ctx): Response {
220226 <ul class="list setting-list"${id === undefined ? null : html` id="${id}"`}${id !== undefined && !isFiltered && costs !== null && capacity !== null && cut.unsure === null ? html` data-capacity="${String(capacity.usd)}"` : null}>
221227 ${list.flatMap((at, i) => [
222228 ...(i === mark && cut.unsure === null && id !== undefined ? [cutMark(cut, false)] : []),
223 line(base, rows, at, writer, back, false, priced, costs?.[at], at + 1, stateWord(rows[at]!, facts(rows[at]!)), rows[at]!.byOwner),
229 line(base, rows, at, writer, back, false, priced, costs?.[at], at + 1, stateWord(rows[at]!, facts(rows[at]!)), rows[at]!.byOwner, promise(rows[at]!)),
224230 ])}
225231 </ul></details>`;
226232 };
src/web/studio/tell.ts +13
@@ -1,3 +1,4 @@
1 import type { Database } from "bun:sqlite";
12 /**
23 * One tell in the studio: a tell is one sentence someone said, and the page
34 * answers three questions — who has it, what it is waiting on, and what the
@@ -50,6 +51,8 @@ import { repoDir } from "../../git/repos.ts";
5051 import type { Ctx } from "../../http/context.ts";
5152 import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
5253 import { html, when, type Html } from "../html.ts";
54 import { currentOf, estimatesOf } from "../../core/estimates.ts";
55 import { estimateLine } from "../../flow/estimate_words.ts";
5356 import { noteLine } from "./note.ts";
5457 import { threadLine } from "../describe.ts";
5558 import { page } from "../layout.ts";
@@ -522,6 +525,7 @@ async function studioTell(
522525 badge("Sealed security report", { tone: "danger", icon: "lock" }),
523526 )}
524527 ${workSpent(ctx, repo, issue.id)}
528 ${promiseLine(db, issue)}
525529 ${!direction && issue.state === "open" && canWrite(db, repo, user)
526530 ? flowButton(
527531 `${thread}/flow`,
@@ -687,3 +691,12 @@ function sealCard(ctx: Ctx, repo: Repo, issue: Issue, action: string): Html | nu
687691 )}
688692 </form>`;
689693 }
694
695 /**
696 * The promise on an issue, in one line: "live by Fri 07:15 (90%: Fri 11:00) · steward · history
697 * says Fri 09:40" (#11955).
698 */
699 function promiseLine(db: Database, issue: Issue): Html | null {
700 const words = estimateLine(currentOf(estimatesOf(db, issue.id)), Date.now());
701 return words === undefined ? null : html`<span class="estimate" id="estimate-line">${words}</span>`;
702 }
test/conversation-confirm.test.ts +1 −1
@@ -122,7 +122,7 @@ describe("the one list of what asks first", () => {
122122 const NOT_ASKED = new Set([
123123 "access", "account_requests", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas",
124124 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "valves", "cloud_accounts", "close", "confirm_wait",
125 "crew", "decisions_by", "detach", "economics", "edit", "email_verify", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
125 "crew", "decisions_by", "detach", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
126126 "follow_mode", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app",
127127 "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
128128 "repo", "restore_drill", "review", "say", "signup", "snapshot_now", "spend", "steer", "sync", "take_back", "take_updates",
test/estimates.test.ts added +306
@@ -0,0 +1,306 @@
1 /** Estimates against an issue (#11955): ask, record, resolve, void, score. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { askEstimate, recordEstimate } from "../src/actions/estimates.ts";
8 import { openIssue, setIssueStateThrough } from "../src/actions/issues.ts";
9 import { mergePull, openPull } from "../src/actions/pulls.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { allEstimates, currentOf, estimatesOf } from "../src/core/estimates.ts";
12 import { createIssue, getIssue } from "../src/core/issues.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { baseRate, quantile, type HistorySample } from "../src/flow/estimate_base.ts";
17 import { biasWords, lastLine, median, scoreboard } from "../src/flow/estimate_score.ts";
18 import { durationWords, estimateLine, ratioOf } from "../src/flow/estimate_words.ts";
19 import { markLive, recordCut } from "../src/keeper/record.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21
22 const H = 3_600_000;
23 const NOW = new Date("2026-11-13T12:00:00.000Z");
24 const at = (ms: number) => new Date(NOW.getTime() + ms).toISOString();
25
26 const sample = (n: number, mergedH: number, extra: Partial<HistorySample> = {}): HistorySample => ({
27 number: n,
28 size: "small",
29 kind: "bug",
30 builder: null,
31 pull: mergedH * H * 0.5,
32 merged: mergedH * H,
33 live: mergedH * H + 25 * 60_000,
34 mergedAtMs: NOW.getTime() - 86_400_000,
35 ...extra,
36 });
37
38 describe("the base rate", () => {
39 test("six samples: nearest-rank p50 and p90 from now, with the stage after the merge", () => {
40 const samples = [1, 2, 3, 4, 5, 6].map((h, i) => sample(i + 1, h));
41 const r = baseRate(samples, { size: "small", kind: "bug", builder: null, elapsedMs: 0 }, "trevato/forge", NOW.getTime());
42 expect(r.thin).toBe(false);
43 expect(r.n).toBe(6);
44 // sorted[round(5 * .5)] = sorted[3] = 4 h; sorted[round(5 * .9)] = sorted[5] = 6 h
45 expect(r.events.merged!.p50Ms).toBe(4 * H);
46 expect(r.events.merged!.p90Ms).toBe(6 * H);
47 expect(r.events.merged!.p50At).toBe(at(4 * H));
48 expect(r.basis).toContain("6 small bug issues, last 30 days in trevato/forge");
49 expect(r.basis).toContain("work start→merged p50 4 h, p90 6 h");
50 expect(r.basis).toContain("merged→live p50 25 m, p90 25 m");
51 });
52
53 test("fewer than five: it says so and widens, dropping the builder, then the kind", () => {
54 const samples = [
55 sample(1, 1, { builder: "torque" }),
56 sample(2, 2, { builder: "torque" }),
57 sample(3, 3, { kind: "" }),
58 sample(4, 4, { kind: "" }),
59 sample(5, 5, { kind: "" }),
60 sample(6, 6, { kind: "" }),
61 ];
62 const r = baseRate(samples, { size: "small", kind: "bug", builder: "torque", elapsedMs: 0 }, "x/y", NOW.getTime());
63 expect(r.widened).toEqual(["dropped the builder", "dropped the kind"]);
64 expect(r.n).toBe(6);
65 expect(r.thin).toBe(false);
66 const few = baseRate(samples.slice(0, 2), { size: "small", kind: "bug", builder: null, elapsedMs: 0 }, "x/y", NOW.getTime());
67 expect(few.thin).toBe(true);
68 expect(few.basis).toContain("fewer than 5");
69 });
70
71 test("work already under way counts only what is left of the slower ones", () => {
72 const samples = [1, 2, 3, 4, 5, 6, 7, 8].map((h, i) => sample(i + 1, h));
73 const r = baseRate(samples, { size: "small", kind: "bug", builder: null, elapsedMs: 2 * H }, "x/y", NOW.getTime());
74 // 3..8 h remain 1..6 h: the same nearest ranks as above
75 expect(r.events.merged!.p50Ms).toBe(4 * H);
76 });
77
78 test("durations read in words", () => {
79 expect([durationWords(25 * 60_000), durationWords(190 * 60_000), durationWords(9 * H), durationWords(52 * H)]).toEqual(["25 m", "3 h 10 m", "9 h", "2 d 4 h"]);
80 expect(quantile([1, 2, 3], 0.5)).toBe(2);
81 });
82 });
83
84 describe("the scorecard maths", () => {
85 const row = (id: number, who: string, p50H: number, actualH: number | null, p90H = p50H * 2, extra: object = {}) => ({
86 id, repoId: "r", issueId: `i${id}`, issueNumber: id, event: "merged" as const,
87 p50At: at(p50H * H), p90At: at(p90H * H), madeAt: at(0), byId: who, byName: who, byKind: "agent" as const,
88 basis: "", baseJson: "null", size: "small", kind: "bug",
89 actualAt: actualH === null ? null : at(actualH * H), voidedAt: null,
90 state: actualH === null ? ("open" as const) : ("resolved" as const), ...extra,
91 });
92
93 test("ratio is actual over p50 from the moment it was made; the median is the bias", () => {
94 expect(ratioOf(row(1, "a", 2, 5))).toBe(2.5);
95 expect(median([1, 3, 2])).toBe(2);
96 expect(median([1, 2, 3, 4])).toBe(2.5);
97 const rows = [row(1, "steward", 2, 5), row(2, "steward", 2, 4.8), row(3, "steward", 1, 2.4, 3), row(4, "steward", 2, null)];
98 const all = scoreboard(rows).find((s) => s.who === "steward" && s.group === "")!;
99 // ratios 2.5, 2.4, 2.4: median 2.4; p90 at 4, 4, 3: the first two missed, the third held
100 expect(all.medianRatio).toBeCloseTo(2.4, 10);
101 expect(all.p90Hit).toBeCloseTo(1 / 3, 10);
102 expect([all.resolved, all.open, all.void]).toEqual([3, 1, 0]);
103 expect(biasWords(all)).toBe("median 2.4× late, p90 held 33%");
104 expect(lastLine(rows, "steward", true)).toBe("your last 3: median 2.4× late, p90 held 33%");
105 expect(scoreboard(rows).some((s) => s.group === "small bug")).toBe(true);
106 });
107
108 test("void is counted, never scored; a revision after the fact does not improve the score", () => {
109 const rows = [
110 row(1, "steward", 2, 6),
111 row(2, "steward", 2, 6, 4),
112 { ...row(2, "steward", 5, 6, 8), id: 3, issueId: "i2" }, // revised later: kept, not scored
113 row(4, "steward", 2, null, 4, { voidedAt: at(H), state: "void" }),
114 ];
115 const all = scoreboard(rows).find((s) => s.who === "steward" && s.group === "")!;
116 expect(all.resolved).toBe(2);
117 expect(all.void).toBe(1);
118 expect(all.medianRatio).toBe(3);
119 });
120
121 test("the base rate shown at the time is scored as `history`", () => {
122 const baseJson = JSON.stringify({ events: { merged: { p50At: at(3 * H), p90At: at(9 * H) } } });
123 const rows = [row(1, "steward", 2, 3, 4, { baseJson })];
124 const history = scoreboard(rows).find((s) => s.who === "history" && s.group === "")!;
125 expect(history.medianRatio).toBe(1);
126 expect(history.p90Hit).toBe(1);
127 });
128
129 test("the line: open, then resolved with its ratio", () => {
130 const open = row(1, "steward", 2, null, 6, { baseJson: JSON.stringify({ events: { merged: { p50At: at(3 * H) } } }) });
131 expect(estimateLine([open], NOW.getTime())).toBe("merged by Fri 14:00 (90%: Fri 18:00) · steward · history says Fri 15:00");
132 expect(estimateLine([row(1, "steward", 2, 3)], NOW.getTime())).toBe("merged Fri 15:00, 1.5× the estimate");
133 });
134 });
135
136 describe("recording and resolving on the forge", () => {
137 let dataDir = "";
138 let app: App;
139 let servers: Servers;
140 let alice: User;
141 let stranger: User;
142 let repo: Repo;
143 let rw = "";
144
145 const issue = (title: string, body = "") => {
146 const o = openIssue(app, alice, repo, { title, body });
147 if (!o.ok) throw new Error(String(o.error));
148 return o.value;
149 };
150 const getI = (n: number) => getIssue(app.db, repo.id, n)!;
151 const say = (n: number, event: unknown, p50: string, p90: string, now = NOW, who = alice) =>
152 recordEstimate(app, who, repo, getI(n), { event, p50, p90, basis: "by hand" }, now);
153
154 beforeAll(async () => {
155 dataDir = await mkdtemp(join(tmpdir(), "forge-estimates-"));
156 app = createApp({ dataDir, port: 0 });
157 servers = await serve(app);
158 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
159 if (!made.ok) throw new Error(made.error);
160 alice = made.value;
161 const other = await createUser(app.db, { origin: "seed", trusted: true, username: "mallory", email: "[email protected]", password: "a-good-passphrase" });
162 if (!other.ok) throw new Error(other.error);
163 stranger = other.value;
164 const r = await createRepo(app, alice, { name: "forge", visibility: "public" });
165 if (!r.ok) throw new Error(String(r.error));
166 repo = r.value;
167 await commitToBranch(app, alice, repo, { branch: "main", message: "base", files: [{ path: "a.txt", content: "a\n" }] });
168 rw = createToken(app.db, alice.id, "rw", "rw").token;
169 }, 30_000);
170
171 afterAll(async () => {
172 await servers.stop();
173 app.close();
174 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
175 });
176
177 test("ask: the base rate comes from seeded history", () => {
178 for (let i = 0; i < 6; i++) {
179 const done = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: `done ${i}`, body: "" });
180 if (!done.ok) throw new Error("issue");
181 const pr = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: `pr ${i}`, body: `Closes #${done.value.number}`, kind: "pull" });
182 if (!pr.ok) throw new Error("pull");
183 const created = new Date(NOW.getTime() - (i + 2) * 86_400_000).toISOString();
184 const merged = new Date(NOW.getTime() - (i + 2) * 86_400_000 + (i + 1) * H).toISOString();
185 app.db.query(`UPDATE issue SET state='closed', close_reason='done', created_at=?2 WHERE id=?1`).run(done.value.id, created);
186 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1,'main','b','a','b',?2)`).run(pr.value.id, merged);
187 }
188 const target = issue("a small thing");
189 const asked = askEstimate(app, alice, repo, target, NOW);
190 expect(asked.base.n).toBe(6);
191 expect(asked.base.thin).toBe(false);
192 expect(asked.base.events.merged!.p50Ms).toBe(4 * H);
193 expect(asked.base.events.merged!.p90Ms).toBe(6 * H);
194 expect(asked.facts.queuePosition).not.toBeNull();
195 expect(asked.facts.budgetLeftUsd.day).toBeGreaterThanOrEqual(0);
196 expect(asked.scorecard).toBe("you have no resolved estimates yet");
197 });
198
199 test("record: validated, stamped, and a new one supersedes while the old stays", () => {
200 const n = issue("record me").number;
201 expect(say(n, "nonsense", at(H), at(2 * H)).ok).toBe(false);
202 expect(say(n, "merged", at(-H), at(2 * H)).ok).toBe(false);
203 expect(say(n, "merged", at(3 * H), at(2 * H)).ok).toBe(false);
204 expect(say(n, "merged", "tomorrow", at(2 * H)).ok).toBe(false);
205 const nobody = say(n, "merged", at(H), at(2 * H), NOW, stranger);
206 expect(nobody.ok).toBe(false);
207 if (!nobody.ok) expect(nobody.error.kind).toBe("forbidden");
208 expect(allEstimates(app.db).filter((e) => e.issueNumber === n)).toHaveLength(0);
209
210 const first = say(n, "merged", at(H), at(2 * H));
211 expect(first.ok).toBe(true);
212 if (!first.ok) return;
213 expect(first.value.estimate).toMatchObject({ byName: "alice", byKind: "person", madeAt: NOW.toISOString(), event: "merged", state: "open" });
214 expect(JSON.parse(first.value.estimate.baseJson).events).toBeDefined();
215 const second = say(n, "merged", at(4 * H), at(5 * H));
216 expect(second.ok).toBe(true);
217 const rows = estimatesOf(app.db, getI(n).id);
218 expect(rows).toHaveLength(2);
219 expect(currentOf(rows)[0]!.p50At).toBe(at(4 * H));
220 expect(rows[0]!.p50At).toBe(at(H));
221 });
222
223 test("resolved by the forge: pull opened, merged, and live; never by hand", async () => {
224 const t = issue("ship me");
225 const real = new Date();
226 const soon = (h: number) => new Date(real.getTime() + h * H).toISOString();
227 for (const ev of ["pull_opened", "merged", "live"] as const) {
228 const made = recordEstimate(app, alice, repo, t, { event: ev, p50: soon(1), p90: soon(2) }, real);
229 expect(made.ok).toBe(true);
230 }
231 await commitToBranch(app, alice, repo, { branch: "ship", base: "main", message: "ship", files: [{ path: "s.txt", content: "s\n" }] });
232 const opened = await openPull(app, alice, repo, { title: "Ship it", body: `Closes #${t.number}`, baseBranch: "main", headBranch: "ship" });
233 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
234 const state = () => Object.fromEntries(estimatesOf(app.db, t.id).map((e) => [e.event, e.state]));
235 expect(state()).toEqual({ pull_opened: "resolved", merged: "open", live: "open" });
236 // Asking for an event that already happened is refused.
237 expect(recordEstimate(app, alice, repo, t, { event: "pull_opened", p50: soon(1), p90: soon(2) }, real).ok).toBe(false);
238 const merged = await mergePull(app, alice, repo, opened.value, "squash");
239 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
240 expect(state()).toEqual({ pull_opened: "resolved", merged: "resolved", live: "open" });
241 // A release cut before the merge does not carry it; one cut after does, and its going live
242 // resolves.
243 const before = recordCut(app.db, { version: "v-old", sha: "a", knownGood: { version: "k", image: "i" }, at: real.getTime() - 3_600_000 });
244 markLive(app.db, before.id, real.getTime() + 1000);
245 expect(state().live).toBe("open");
246 const cut = recordCut(app.db, { version: "v-new", sha: "b", knownGood: { version: "k", image: "i" }, at: real.getTime() + 2000 });
247 expect(markLive(app.db, cut.id, real.getTime() + 60_000)).toBe(true);
248 expect(state()).toEqual({ pull_opened: "resolved", merged: "resolved", live: "resolved" });
249 const live = estimatesOf(app.db, t.id).find((e) => e.event === "live")!;
250 expect(live.actualAt).toBe(new Date(real.getTime() + 60_000).toISOString());
251 expect(estimateLine([live], real.getTime())).toContain("went live");
252 }, 30_000);
253
254 test("an issue closed as split or dropped voids what it left open; done does not", async () => {
255 const split = issue("too big");
256 const dropped = issue("not wanted");
257 for (const t of [split, dropped]) expect(say(t.number, "merged", at(H), at(2 * H)).ok).toBe(true);
258 const a = await setIssueStateThrough(app, alice, repo, split, "closed", { reason: "split", into: [issue("half").number] });
259 expect(a.ok).toBe(true);
260 const b = await setIssueStateThrough(app, alice, repo, dropped, "closed", { reason: "dropped" });
261 expect(b.ok).toBe(true);
262 expect(estimatesOf(app.db, split.id)[0]).toMatchObject({ state: "void" });
263 expect(estimatesOf(app.db, dropped.id)[0]!.voidedAt).not.toBeNull();
264 const voidRow = scoreboard(allEstimates(app.db)).find((s) => s.who === "alice" && s.group === "")!;
265 expect(voidRow.void).toBeGreaterThanOrEqual(2);
266 });
267
268 test("the API asks and records, and the issue page and /next carry the line", async () => {
269 const t = issue("api and page");
270 const url = `${servers.url}/api/v1/repos/alice/forge/issues/${t.number}/estimates`;
271 const asked = await fetch(url, { headers: { authorization: `Bearer ${rw}` } });
272 expect(asked.status).toBe(200);
273 expect(((await asked.json()) as any).base.basis).toBeString();
274 const soon = (h: number) => new Date(Date.now() + h * H).toISOString();
275 const bad = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" }, body: JSON.stringify({ event: "live", p50: soon(3), p90: soon(1) }) });
276 expect(bad.status).toBe(422);
277 const ok = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" }, body: JSON.stringify({ event: "live", p50: soon(3), p90: soon(5), basis: "api" }) });
278 expect(ok.status).toBe(201);
279 const page = await (await fetch(`${servers.url}/alice/forge/issues/${t.number}`)).text();
280 expect(page).toContain("live by");
281 expect(page).toContain("· alice");
282 const next = await (await fetch(`${servers.url}/alice/forge/next`)).text();
283 expect(next).toContain("live by");
284 });
285
286 test("the MCP tool asks with no times and records with them", async () => {
287 const t = issue("mcp");
288 const call = async (args: unknown) => {
289 const res = await fetch(`${servers.url}/mcp`, {
290 method: "POST",
291 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${rw}` },
292 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "estimate", arguments: args } }),
293 });
294 const body = (await res.json()) as any;
295 return { error: body.result.isError === true, value: body.result.isError === true ? body.result.content[0].text : JSON.parse(body.result.content[0].text) };
296 };
297 const asked = await call({ repo: "alice/forge", issue: t.number });
298 expect(asked.error).toBe(false);
299 expect(asked.value.base).toBeDefined();
300 const soon = (h: number) => new Date(Date.now() + h * H).toISOString();
301 const made = await call({ repo: "alice/forge", issue: t.number, event: "merged", p50: soon(1), p90: soon(2), basis: "mcp" });
302 expect(made.error).toBe(false);
303 const refused = await call({ repo: "alice/forge", issue: t.number, event: "merged", p50: soon(2), p90: soon(1) });
304 expect(refused.error).toBe(true);
305 });
306 });
test/mcp.test.ts +1
@@ -381,6 +381,7 @@ describe("the forge over MCP", () => {
381381 "ssh_keys",
382382 "steer",
383383 "email_verify",
384 "estimate",
384385 "parent_unlink",
385386 "vision",
386387 "boards",
test/route-timing-coverage.test.ts +1
@@ -21,6 +21,7 @@ import { seedAdmin } from "./helpers/admin.ts";
2121 const UNTIMED: Record<string, string> = {
2222 "/api/v1/conversations": "a person's conversation list, one indexed query; no page to phase",
2323 "/api/v1/admin/machines/:machine/disks": "an owner's per-machine disk summary, one indexed read; no page to phase",
24 "/api/v1/repos/:owner/:name/issues/:number/estimates": "an issue's base rate from one indexed read of its history; no page to phase",
2425 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
2526 };
2627

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs