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

The forge measures each new forge's seconds from first ask to first built change, and /admin/limits shows the median per plan #16829

opened this

Check · Review · Land · Live — Its check is red. Next: builder, its check is red.

Ready to land

scout/forge:scout/16777-the-forge-measures-each-new-forge-s-seco → main 6 commits fork

Review

Sign in to review this change.
12 files changed +205 −9
docs/features/plans.md +2
@@ -26,6 +26,8 @@ These are the defaults. A forge admin who is a person edits them:
2626
2727 Each plan may also carry `firstChangeSecs`, the measured whole seconds from a first ask to a first built change on that plan's size. An admin sets it in the "Seconds to a first change" field of the Plans form, with `first <seconds>` in the terminal, or in `firstChangeSecs` through the API and MCP. Until it is set (0 clears it) nothing is said: the plans words and `GET /api/v1/plans` leave it out, and once set the words read "A first built change takes about 4 minutes."
2828
29 The forge measures that time itself: the first ask on a forge and the first change built on the app it made are each recorded once, with the forge's plan (`plan` in its `parent.json`, `free` when absent), in `first_change_sample` (`src/core/first_change_samples.ts`). A forge with an ask and no built change is no sample. `/admin/limits` shows beside each plan "Measured here: median 7 min from 4 forges", or "not measured yet"; the terminal Plans screen says the same; `GET /api/v1/admin/plans` (admin only, 404 to anyone else) carries `medianSecs` (null when not measured) and `measuredForges` on each plan. An admin copies the number into the field above; nothing fills it by itself. Each forge counts the samples in its own store.
30
2931 ## What a spawn gets
3032
3133 `POST /api/v1/forges` (and the MCP `spawn`) takes `plan`. The forge's size comes from the plan (a `size` that disagrees is refused), and its credit cap is the plan's `creditUsd`, lent as a monthly cap through `src/spawn/credit.ts`: the spend is counted again each UTC calendar month. Plans are read at spawn time, so an edit governs the next spawn; forges already made keep the credit they were given.
src/actions/first_ask.ts +2
@@ -26,6 +26,7 @@ import { overTellLimit, parseFrom, tellTooLongWords } from "./tell_from.ts";
2626 import { deriveAppName } from "../web/pages/apps-name.ts";
2727 import { requireVerified } from "./verify.ts";
2828 import { recordRefusal } from "../core/first_ask_refusals.ts";
29 import { ownPlan, recordAsk } from "../core/first_change_samples.ts";
2930 import { DIRECTION_NOTE } from "../crew/direct.ts";
3031
3132 export interface FirstAsk {
@@ -76,6 +77,7 @@ export async function firstAsk(
7677 const made = await newAppFromSentence(app, actor, { sentence: text, description: "" });
7778 if (!made.ok) return refuse(NEW_APP_ERRORS[made.code] ?? NOT_TOLD_WORDS);
7879 let repo = made.repo;
80 recordAsk(app.db, repo.id, ownPlan(app.config.dataDir), Date.now());
7981 let autonomyFailed = false;
8082 if (crewCanRun) {
8183 // A builder and a reviewer seated and autonomy on as the asker, so the next tick starts the ask (#11508).
src/actions/plans.ts +22
@@ -8,6 +8,7 @@
88 import type { App } from "../app.ts";
99 import type { User } from "../core/users.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
11 import { measureOf } from "../core/first_change_samples.ts";
1112 import { getPlans, parsePlans, publicPlans, setPlans, type Plan } from "../settings/plans.ts";
1213
1314 export type PlansError = "not_found" | { readonly invalid: string };
@@ -30,3 +31,24 @@ export function editPlans(app: App, actor: User | undefined, edits: Record<strin
3031 const next = getPlans(app.db).map((p) => ({ ...p, ...(edits[p.key] ?? {}) }));
3132 return changePlans(app, actor, next);
3233 }
34
35 export interface MeasuredPlan extends Plan {
36 /** Median measured seconds from a first ask to a first built change; null when not measured. */
37 readonly medianSecs: number | null;
38 /** How many forges the median comes from. */
39 readonly measuredForges: number;
40 }
41
42 /**
43 * Every plan with its measured median and count (`core/first_change_samples.ts`); `not_found` for
44 * anyone but a person admin.
45 */
46 export function measuredPlans(app: App, actor: User | undefined): Result<MeasuredPlan[], "not_found"> {
47 if (actor?.isAdmin !== true || actor.kind === "agent") return err("not_found");
48 return ok(
49 readPlans(app).map((p) => {
50 const m = measureOf(app.db, p.key);
51 return { ...p, medianSecs: m.medianSecs ?? null, measuredForges: m.forges };
52 }),
53 );
54 }
src/actions/spawn.ts +3
@@ -798,6 +798,9 @@ async function copyInto(
798798 // No spawner signed in: the founder account is a placeholder (#11785).
799799 anonymous: owner === undefined,
800800 size: plan.size ?? DEFAULT_SIZE,
801 // The plan the child is on, so it can measure its first change under it
802 // (`core/first_change_samples.ts`).
803 ...(plan.plan === undefined ? {} : { plan: plan.plan }),
801804 ...(plan.template === undefined ? {} : { template: templateMark ?? { id: plan.template } }),
802805 // Each app: where it came from and that the child follows it (`spawn/app_links.ts`).
803806 apps: appEntries,
src/core/first_change_samples.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * Seconds from a new forge's first ask to its first built change (#16777), measured by the
3 * forge itself so no run has to time production by hand. A forge's plan is the one its
4 * `parent.json` names (absent: free). The ask is recorded once, on the app it made; the first
5 * change built on that app closes the sample once. An ask with no built change is no sample.
6 * The median per plan is read by an admin and copied into the plan by hand; nothing fills it.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { readFileSync } from "node:fs";
11 import { join } from "node:path";
12
13 /** The plan this forge was born on, from its `parent.json`; "free" when it names none. */
14 export function ownPlan(dataDir: string): string {
15 try {
16 const parsed = JSON.parse(readFileSync(join(dataDir, "parent.json"), "utf8")) as { plan?: unknown };
17 return typeof parsed.plan === "string" && /^[a-z][a-z0-9-]{0,19}$/.test(parsed.plan) ? parsed.plan : "free";
18 } catch {
19 return "free";
20 }
21 }
22
23 /** Record the first ask on an app, once: a second call for the same app changes nothing. */
24 export function recordAsk(db: Database, repoId: string, plan: string, now: number): void {
25 db.query("INSERT OR IGNORE INTO first_change_sample (repo_id, plan, asked_at) VALUES (?1, ?2, ?3)").run(repoId, plan, now);
26 }
27
28 /** Record the first built change of an app that was asked for, once. */
29 export function recordBuilt(db: Database, repoId: string, now: number): void {
30 db.query("UPDATE first_change_sample SET built_at = ?2 WHERE repo_id = ?1 AND built_at IS NULL").run(repoId, now);
31 }
32
33 export interface PlanMeasure {
34 /** Median whole seconds, or undefined when no forge on the plan has a sample. */
35 readonly medianSecs: number | undefined;
36 readonly forges: number;
37 }
38
39 /** The median seconds and sample count of one plan. */
40 export function measureOf(db: Database, plan: string): PlanMeasure {
41 const rows = db
42 .query<{ s: number }, [string]>(
43 "SELECT MAX(0, built_at - asked_at) / 1000.0 AS s FROM first_change_sample WHERE plan = ?1 AND built_at IS NOT NULL ORDER BY s",
44 )
45 .all(plan);
46 if (rows.length === 0) return { medianSecs: undefined, forges: 0 };
47 const mid = rows.length >> 1;
48 const m = rows.length % 2 === 1 ? rows[mid]!.s : (rows[mid - 1]!.s + rows[mid]!.s) / 2;
49 return { medianSecs: Math.round(m), forges: rows.length };
50 }
51
52 /** "median 7 min from 4 forges", or "not measured yet". */
53 export function measureWords(m: PlanMeasure): string {
54 if (m.medianSecs === undefined) return "not measured yet";
55 const s = m.medianSecs;
56 const t = s < 90 ? `${s} s` : s < 5400 ? `${Math.round(s / 60)} min` : `${Math.round(s / 360) / 10} h`;
57 return `median ${t} from ${m.forges} ${m.forges === 1 ? "forge" : "forges"}`;
58 }
src/core/migration-pins/20261130140000-first-change-sample.pin added +1
@@ -0,0 +1,1 @@
1 65cf03cdcc4ba13d1aeea8d8221ddbdde875ac59c78bca11b83c1c39d130f133
src/core/migrations/20261130140000-first-change-sample.ts added +10
@@ -0,0 +1,10 @@
1 // The seconds from a forge's first ask to its first built change (#16777): one row per
2 // first-ask app, its plan, when it was asked and, once, when its first change was built.
3 export default `
4 CREATE TABLE IF NOT EXISTS first_change_sample (
5 repo_id TEXT PRIMARY KEY,
6 plan TEXT NOT NULL,
7 asked_at INTEGER NOT NULL,
8 built_at INTEGER
9 );
10 `;
src/crew/land_gated.ts +4
@@ -1,5 +1,6 @@
11 /** Landing one gated step of the queue's candidate, and how: merge or squash. */
22
3 import { recordBuilt } from "../core/first_change_samples.ts";
34 import type { AccessError } from "../actions/access.ts";
45 import { addComment } from "../actions/issues.ts";
56 import { mergePull } from "../actions/pulls.ts";
@@ -132,6 +133,9 @@ export async function landGated(
132133 // there is no release to cut and nothing new was landed.
133134 if (merged.value.carried) return undefined;
134135 resolveOpen(app.db, pull.id, "land", "shipped");
136 // The seconds from the first ask to the first built change: closed once
137 // (`core/first_change_samples.ts`).
138 recordBuilt(app.db, repo.id, Date.now());
135139 // The app's first change: one sentence on the pull, and the reviewer's requests as one follow-up.
136140 if (review === "first") sayFirstLanded(app, repo, pull, by);
137141 // Said once it has landed, so the note wakes no builder: the review was
src/http/api/admin.ts +15 −3
@@ -21,7 +21,7 @@ import { DERIVED_WORDS, REASON_WORDS, changeCapacity, edgeOffDryRun, listCapacit
2121 import { changeShield, lastShieldChange, shieldState } from "../../actions/shield.ts";
2222 import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
2323 import { changeLimit, listLimits } from "../../actions/limits.ts";
24 import { changePlans } from "../../actions/plans.ts";
24 import { changePlans, measuredPlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
2626 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
@@ -41,7 +41,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
4141 import { getUserByName } from "../../core/users.ts";
4242 import { holds, weakEtag } from "../etag.ts";
4343 import { offsetPage, offsetQuery } from "../offset_page.ts";
44 import { body, json, str } from "../respond.ts";
44 import { body, forbidden, json, str } from "../respond.ts";
4545 import { offsetRefused } from "../api.ts";
4646 import type { Ctx, Handler } from "../context.ts";
4747 import { apiError, notFound, requireScope } from "../respond.ts";
@@ -385,7 +385,19 @@ export function adminRoutes(router: Router<Handler>): void {
385385 );
386386 });
387387
388 // The plans (`settings/plans.ts`): the whole list is replaced; GET is the public /api/v1/plans.
388 // The plans with the forge's own measured median seconds to a first change (admin only); the
389 // public list is /api/v1/plans.
390 router.add("GET", "/api/v1/admin/plans", (ctx) => {
391 // A person who is not an admin is told no (403), as the issue asks; anyone not signed in gets
392 // the door's own answer.
393 if (ctx.auth.user !== undefined && ctx.auth.user.isAdmin !== true) return forbidden();
394 const denied = accountAdmin(ctx, "ro");
395 if (denied) return denied;
396 const listed = measuredPlans(ctx.app, ctx.auth.user);
397 return listed.ok ? json({ items: listed.value }) : forbidden();
398 });
399
400 // The plans (`settings/plans.ts`): the whole list is replaced.
389401 router.add("PUT", "/api/v1/admin/plans", async (ctx) => {
390402 const denied = accountAdmin(ctx, "admin");
391403 if (denied) return denied;
src/tui/screens/plans.ts +8 −4
@@ -7,7 +7,8 @@
77 * and the MCP's. The gate is the action's: an admin who is a person; anyone else sees nothing.
88 */
99
10 import { editPlans, readPlans } from "../../actions/plans.ts";
10 import { measureWords } from "../../core/first_change_samples.ts";
11 import { editPlans, measuredPlans, readPlans } from "../../actions/plans.ts";
1112 import { moneyWords, centsOfUsd, usdPerMonthWords } from "../../billing/money.ts";
1213 import type { Plan } from "../../settings/plans.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
@@ -89,12 +90,15 @@ export function plansScreen(f: Session, ctx: Ctx): Screen {
8990 );
9091 };
9192
92 const rows = (plans: readonly Plan[]): ListRow[] =>
93 plans.map((p) => ({
93 const rows = (plans: readonly Plan[]): ListRow[] => {
94 const m = measuredPlans(f.app, f.user);
95 const measured = new Map((m.ok ? m.value : []).map((q) => [q.key, q]));
96 return plans.map((p) => ({
9497 title: `${p.key} · ${p.name}`,
9598 secondary: `${p.size} · ${usdPerMonthWords(p.priceUsd)} · ${moneyWords(centsOfUsd(p.creditUsd))} crew credit · ${p.forges} forges · ${first(p)}`,
96 meta: p.says,
99 meta: `${p.says} · measured here: ${measureWords({ medianSecs: measured.get(p.key)?.medianSecs ?? undefined, forges: measured.get(p.key)?.measuredForges ?? 0 })}`,
97100 }));
101 };
98102
99103 const screen: Screen = {
100104 title: "Plans",
src/web/settings/plans.ts +8 −2
@@ -5,7 +5,8 @@
55 * GET /api/v1/plans use it at once.
66 */
77
8 import { editPlans, readPlans } from "../../actions/plans.ts";
8 import { measureWords } from "../../core/first_change_samples.ts";
9 import { editPlans, measuredPlans, readPlans } from "../../actions/plans.ts";
910 import type { Ctx } from "../../http/context.ts";
1011 import { SIZES } from "../../spawn/sizes.ts";
1112 import { notFoundPage } from "../chrome.ts";
@@ -17,6 +18,11 @@ import { btn, row } from "../ui.ts";
1718 const FIELDS = ["name", "says", "size", "priceUsd", "creditUsd", "forges", "firstChangeSecs"] as const;
1819
1920 export function plansRow(ctx: Ctx): Html {
21 const measured = measuredPlans(ctx.app, ctx.auth.user);
22 const wordsOf = (key: string): string => {
23 const m = measured.ok ? measured.value.find((q) => q.key === key) : undefined;
24 return measureWords({ medianSecs: m?.medianSecs ?? undefined, forges: m?.measuredForges ?? 0 });
25 };
2026 const rows = readPlans(ctx.app).map((p) =>
2127 row({
2228 title: p.key,
@@ -30,7 +36,7 @@ export function plansRow(ctx: Ctx): Html {
3036 { label: "Price $/mo", value: html`<input class="input mono" name="${p.key}.priceUsd" inputmode="decimal" value="${String(p.priceUsd)}" ${p.key === "free" ? "readonly" : ""} aria-label="${p.key} price a month in dollars" />` },
3137 { label: "Crew credit $/mo", value: html`<input class="input mono" name="${p.key}.creditUsd" inputmode="decimal" value="${String(p.creditUsd)}" aria-label="${p.key} crew credit a month in dollars" />` },
3238 { label: "Forges", value: html`<input class="input mono" name="${p.key}.forges" type="number" min="1" max="1000" step="1" value="${String(p.forges)}" aria-label="${p.key} forges one person may hold" />` },
33 { label: "Seconds to a first change", value: html`<input class="input mono" name="${p.key}.firstChangeSecs" inputmode="numeric" value="${String(p.firstChangeSecs ?? 0)}" aria-describedby="${p.key}-first-hint" aria-label="${p.key} measured seconds to a first built change" /> <span id="${p.key}-first-hint" class="muted small">0 or blank: not measured, and the plans page says nothing.</span>` },
39 { label: "Seconds to a first change", value: html`<input class="input mono" name="${p.key}.firstChangeSecs" inputmode="numeric" value="${String(p.firstChangeSecs ?? 0)}" aria-describedby="${p.key}-first-hint" aria-label="${p.key} measured seconds to a first built change" /> <span id="${p.key}-first-hint" class="muted small">0 or blank: not measured, and the plans page says nothing.</span> <span class="muted small" id="${p.key}-measured">Measured here: ${wordsOf(p.key)}.</span>` },
3440 ],
3541 }),
3642 );
test/first-change-samples.test.ts added +72
@@ -0,0 +1,72 @@
1 /** The forge times its own first ask to first built change (#16777), per plan. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm, writeFile } 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 { createToken } from "../src/core/tokens.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { measureOf, measureWords, ownPlan, recordAsk, recordBuilt } from "../src/core/first_change_samples.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11
12 describe("first change samples", () => {
13 let dir = "";
14 let app: App;
15 let servers: Servers;
16 let admin = "";
17 let bob = "";
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-fcs-"));
20 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
21 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-new-forge-passphrase", isAdmin: true });
22 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-new-forge-passphrase" });
23 if (!a.ok || !b.ok) throw new Error("users");
24 admin = createToken(app.db, a.value.id, "admin", "admin").token;
25 bob = createToken(app.db, b.value.id, "rw", "rw").token;
26 servers = await serve(app);
27 }, 30_000);
28 afterAll(async () => {
29 servers.stop();
30 app.close();
31 await rm(dir, { recursive: true, force: true });
32 });
33
34 test("an ask then a built change is one sample with the right seconds; a second change adds none", () => {
35 recordAsk(app.db, "r1", "small", 1_000);
36 recordBuilt(app.db, "r1", 421_000);
37 recordBuilt(app.db, "r1", 900_000);
38 recordAsk(app.db, "r1", "small", 5_000);
39 expect(measureOf(app.db, "small")).toEqual({ medianSecs: 420, forges: 1 });
40 });
41
42 test("an ask with no change adds no sample, and a plan with none reads not measured yet", () => {
43 recordAsk(app.db, "r2", "medium", 1_000);
44 expect(measureOf(app.db, "medium")).toEqual({ medianSecs: undefined, forges: 0 });
45 expect(measureWords(measureOf(app.db, "medium"))).toBe("not measured yet");
46 expect(measureWords(measureOf(app.db, "small"))).toBe("median 7 min from 1 forge");
47 });
48
49 test("the median of several", () => {
50 for (const [id, s] of [["a", 60], ["b", 120], ["c", 600]] as const) {
51 recordAsk(app.db, id, "large", 0);
52 recordBuilt(app.db, id, s * 1000);
53 }
54 expect(measureOf(app.db, "large")).toEqual({ medianSecs: 120, forges: 3 });
55 });
56
57 test("a forge's plan is the one in its parent.json, free when absent", async () => {
58 expect(ownPlan(dir)).toBe("free");
59 await writeFile(join(dir, "parent.json"), JSON.stringify({ plan: "medium" }));
60 expect(ownPlan(dir)).toBe("medium");
61 });
62
63 test("GET /api/v1/admin/plans carries median and count; a non-admin gets 403", async () => {
64 const get = (t: string) => fetch(`${servers.url}/api/v1/admin/plans`, { headers: { authorization: `Bearer ${t}` } });
65 const ok = await get(admin);
66 expect(ok.status).toBe(200);
67 const items = ((await ok.json()) as { items: { key: string; medianSecs: number | null; measuredForges: number }[] }).items;
68 expect(items.find((p) => p.key === "small")).toMatchObject({ medianSecs: 420, measuredForges: 1 });
69 expect(items.find((p) => p.key === "medium")).toMatchObject({ medianSecs: null, measuredForges: 0 });
70 expect((await get(bob)).status).toBe(403);
71 });
72 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs