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

Teams as a forge primitive: a named group of crew members (and people) with a goal, a shared map, roles, and coordination metrics #16692

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/484-teams-as-a-forge-primitive-a-named-group → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/484-teams-as-a-forge-primitive-a-named-group was merged into main as f5ad020.

Review

Sign in to review this change.
3 files changed +126 −10
docs/features/team-metrics.md +1
@@ -15,6 +15,7 @@ last 24 hours and the last 7 days, one row each (#572):
1515 - **Conflicts**: of the runs started, the share that went again because main moved under the pull.
1616 - **Cost per shipped change**: what the window's runs cost, over the pulls merged in it.
1717 - **Slots busy**: runs in flight on average, beside how many the team's agents could hold.
18 - **Held idle** (#474): slot-hours of runs a person stopped after 20 minutes or more, and how many. A proxy: the run log has no timestamps, so when the agent actually finished is not recoverable.
1819
1920 A dash is a figure the window has nothing to measure.
2021
src/core/team-metrics.ts +45 −10
@@ -10,6 +10,7 @@
1010 */
1111
1212 import type { Database } from "bun:sqlite";
13 import { stoppedBy } from "../runs/cancelled.ts";
1314 import { duration } from "./slider.ts";
1415
1516 export type Role = "planner" | "builder" | "reviewer" | "member";
@@ -21,6 +22,11 @@ export interface LedgerRun {
2122 /** `conflict` when main moved under the pull and the run went again. */
2223 readonly reason: string;
2324 readonly costUsd: number;
25 /**
26 * A person stopped it after `HELD_MIN_MS` or more: it held its slot with nothing left to do
27 * (#474).
28 */
29 readonly held?: boolean;
2430 readonly startedAt: number | null;
2531 readonly finishedAt: number | null;
2632 }
@@ -47,6 +53,12 @@ export interface LedgerDecision {
4753 readonly at: number;
4854 }
4955
56 /**
57 * How long a run sits before a person's stop counts as idle-held; the baseline's proxy (#484), the
58 * run log has no timestamps.
59 */
60 export const HELD_MIN_MS = 20 * 60_000;
61
5062 export interface Ledger {
5163 readonly runs: readonly LedgerRun[];
5264 readonly items: readonly LedgerItem[];
@@ -77,6 +89,12 @@ export interface TeamMetrics {
7789 /** Mean runs in flight across the window, beside the slots it could hold. */
7890 readonly parallelism: number;
7991 readonly slots: number;
92 /**
93 * Slot time, in ms, of runs started in the window that a person stopped after 20 minutes or more.
94 */
95 readonly heldMs: number;
96 /** How many runs that was. */
97 readonly heldRuns: number;
8098 }
8199
82100 /** The nearest-rank quantile of sorted numbers; null when there are none. */
@@ -156,6 +174,9 @@ export function teamMetrics(ledger: Ledger, from: number, to: number): TeamMetri
156174 const conflicts = started.filter((r) => r.reason === "conflict").length;
157175 const spent = started.reduce((sum, r) => sum + r.costUsd, 0);
158176
177 const held = started.filter((r) => r.held === true);
178 const heldMs = held.reduce((sum, r) => sum + Math.max(0, (r.finishedAt ?? 0) - r.startedAt!), 0);
179
159180 let busy = 0;
160181 for (const r of ledger.runs) {
161182 if (r.startedAt === null) continue;
@@ -177,6 +198,8 @@ export function teamMetrics(ledger: Ledger, from: number, to: number): TeamMetri
177198 shipped: merged.length,
178199 parallelism: busy / span,
179200 slots: ledger.slots,
201 heldMs,
202 heldRuns: held.length,
180203 };
181204 }
182205
@@ -211,20 +234,28 @@ export function teamLedger(db: Database, teamId: string, since: number): Ledger
211234 // Values, not objects, each member's runs a seek on `run_agent_actor`, never a scan of every run.
212235 const runs: LedgerRun[] = (db
213236 .query<Record<string, never>, [string, string]>(
214 `SELECT run.issue_id, run.actor_id, run.reason, run.cost_usd, run.started_at, run.finished_at
237 `SELECT run.issue_id, run.actor_id, run.reason, run.cost_usd, run.started_at, run.finished_at,
238 run.state, run.summary
215239 FROM team_member JOIN run INDEXED BY run_agent_actor ON run.actor_id = team_member.user_id
216240 WHERE team_member.team_id = ?1 AND run.kind = 'agent' AND run.issue_id IS NOT NULL
217241 AND (run.finished_at IS NULL OR run.finished_at >= ?2)`,
218242 )
219 .values(teamId, sinceIso) as [string, string, string, number, string | null, string | null][])
220 .map(([item, actor, reason, costUsd, started, finished]) => ({
221 item,
222 role: roles.get(actor) ?? "member",
223 reason,
224 costUsd,
225 startedAt: ms(started),
226 finishedAt: ms(finished),
227 }));
243 .values(teamId, sinceIso) as [string, string, string, number, string | null, string | null, string, string][])
244 .map(([item, actor, reason, costUsd, started, finished, state, summary]) => {
245 const startedAt = ms(started);
246 const finishedAt = ms(finished);
247 return {
248 item,
249 role: roles.get(actor) ?? "member",
250 reason,
251 costUsd,
252 held:
253 startedAt !== null && finishedAt !== null && finishedAt - startedAt >= HELD_MIN_MS &&

Add a test that seeds runs in the database and checks held through teamLedger. A short stop and a normal finish must both come out false.

254 stoppedBy({ state, summary }) !== undefined,
255 startedAt,
256 finishedAt,
257 };
258 });
228259
229260 // The items those runs touched, and the ones members opened, unless closed before the ledger.
230261 const rows = db
@@ -338,5 +369,9 @@ export function metricsRows(m: TeamMetrics): MetricRow[] {
338369 value: m.costPerShippedUsd === null ? "nothing shipped" : `$${m.costPerShippedUsd.toFixed(2)}, ${m.shipped} shipped`,
339370 },
340371 { label: "Slots busy", value: `${m.parallelism.toFixed(1)} of ${m.slots}` },
372 {
373 label: "Held idle",
374 value: m.heldRuns === 0 ? "none" : `${(m.heldMs / 3_600_000).toFixed(1)} slot-hours, ${m.heldRuns} stopped by hand`,
375 },
341376 ];
342377 }
test/team-metrics.test.ts +80
@@ -20,6 +20,7 @@ import {
2020 type Ledger,
2121 type LedgerRun,
2222 } from "../src/core/team-metrics.ts";
23 import { cancelledBy } from "../src/runs/cancelled.ts";
2324 import { createToken } from "../src/core/tokens.ts";
2425 import { createUser, type User } from "../src/core/users.ts";
2526 import { serve, type Servers } from "../src/http/server.ts";
@@ -115,9 +116,27 @@ describe("teamMetrics over a fixture ledger", () => {
115116 { label: "Conflicts", value: "–" },
116117 { label: "Cost per shipped change", value: "nothing shipped" },
117118 { label: "Slots busy", value: "1.0 of 3" },
119 { label: "Held idle", value: "none" },
118120 ]);
119121 });
120122
123 test("idle-held: runs a person stopped after 20 minutes, counted in slot-hours (#474)", () => {
124 const l: Ledger = {
125 ...ledger,
126 runs: [
127 { ...run("i1", "reviewer", 1, 1.75, 0), held: true },
128 { ...run("i1", "reviewer", 2, 2.5, 0), held: true },
129 run("i1", "reviewer", 3, 4, 0),
130 { ...run("i1", "reviewer", -30, -29, 0), held: true },
131 ],
132 };
133 const h = teamMetrics(l, 0, 24 * H);
134 expect(h.heldRuns).toBe(2);
135 expect(h.heldMs).toBe(1.25 * H);
136 expect(metricsRows(h)[8]).toEqual({ label: "Held idle", value: "1.3 slot-hours, 2 stopped by hand" });
137 expect(m.heldRuns).toBe(0);
138 });
139
121140 test("quantile is nearest-rank", () => {
122141 expect(quantile([], 0.5)).toBeNull();
123142 expect(quantile([1, 2, 3, 4], 0.5)).toBe(2);
@@ -299,3 +318,64 @@ describe("a team's page and the org_teams metrics action over 10k runs", () => {
299318 expect(got.day.slots).toBe(3);
300319 });
301320 });
321
322 describe("teamLedger reads idle-held runs from the database (#474)", () => {
323 test("only a run a person stopped after 20 minutes or more is held", async () => {
324 const dir = mkdtempSync(join(tmpdir(), "forge-team-held-"));
325 const app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge" });
326 try {
327 const mk = async (username: string) => {
328 const u = await createUser(app.db, {
329 origin: "seed",
330 trusted: true,
331 username,
332 email: `${username}@forge.local`,
333 password: "a-good-passphrase",
334 adminIfFirst: true,
335 });
336 if (!u.ok) throw new Error(u.error);
337 return u.value;
338 };
339 const alice = await mk("alice");
340 const agent = await mk("build");
341 proveAll(app);
342 const org = createOrg(app.db, "acme", alice.id);
343 if (!org.ok) throw new Error(org.error);
344 const team = listTeams(app.db, org.value.id).find((t) => t.name === OWNERS_TEAM)!.id;
345 app.db.run("INSERT INTO team_member (team_id, user_id, role) VALUES (?1, ?2, 'builder')", [team, agent.id]);
346 const repo = await createRepo(app, alice, { name: "work" });
347 if (!repo.ok) throw new Error(String(repo.error));
348 const now = Date.now();
349 const iso = (t: number) => new Date(t).toISOString();
350 app.db.run(
351 `INSERT INTO issue (id, repo_id, number, kind, title, author_id, state, created_at)
352 VALUES ('held-issue', ?1, 1, 'issue', 't', ?2, 'open', ?3)`,
353 [repo.value.id, agent.id, iso(now - 3 * H)],
354 );
355 const put = (id: string, state: string, summary: string, minutes: number) => {
356 const start = now - 2 * H;
357 app.db.run(
358 `INSERT INTO run (id, repo_id, kind, issue_id, state, summary, actor_id, reason, cost_usd, created_at, started_at, finished_at)
359 VALUES (?1, ?2, 'agent', 'held-issue', ?3, ?4, ?5, '', 0.25, ?6, ?6, ?7)`,
360 [id, repo.value.id, state, summary, agent.id, iso(start), iso(start + minutes * 60_000)],
361 );
362 };
363 put("stopped-long", "cancelled", cancelledBy("alice"), 25);
364 put("stopped-short", "cancelled", cancelledBy("alice"), 5);
365 put("finished-long", "ok", "done", 25);
366
367 const l = teamLedger(app.db, team, now - 24 * H);
368 expect(l.runs).toHaveLength(3);
369 const held = l.runs.filter((r) => r.held);
370 expect(held).toHaveLength(1);
371 expect(held[0]!.finishedAt! - held[0]!.startedAt!).toBe(25 * 60_000);
372 expect(held[0]!.held).toBe(true);
373 const m = teamMetrics(l, now - 24 * H, now);
374 expect(m.heldRuns).toBe(1);
375 expect(m.heldMs).toBe(25 * 60_000);
376 } finally {
377 app.close();
378 rmSync(dir, { recursive: true, force: true });
379 }
380 });
381 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs