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

Hand a limb to the planner: re-planned as fewer, larger pieces, with preview, receipt and undo #934

Closed opened this in answer to
Closed without merging

steward/761-limb-to-planner → main 3 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +886 −93
docs/FLEET.md +3 −1
@@ -80,7 +80,9 @@ only where the row still holds what the operation left; a row someone
8080 changed since is refused as `changed since: it is … now`. It writes the
8181 rows backwards, so what was done last is undone first.
8282
83 `file` says where an issue stands in the plan: `later` puts it behind the
83 `replan` hands an issue to the repository's planner (assigns it); with a
84 planner on the crew its undo, `null`, takes it back. `file` says where an
85 issue stands in the plan: `later` puts it behind the
8486 Later gate and under the Later umbrella, out from under any pillar; a
8587 pillar's name or short form puts it under that pillar and out from behind
8688 the gate; `none` takes it out of both. Over several rows at once, a row
docs/MCP.md +1 −1
@@ -51,7 +51,7 @@ for a tunnel and a forge that sleeps.
5151 | `front_page` | `{ pinned?, hidden?, weights?, dryRun? }`: the front page as a stranger sees it, ranked, with numbers; a site admin sets what is pinned (first public one featured), hidden, and what counts (weights of forks, ships, use, fresh, 0 to 10) | yes |
5252 | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`) | |
5353 | `milestones` | `{ app, issue? }`: how far each thing asked for is (and, with `issue`, whether you watch it: `watching`), from the dependency tree: the plan's limbs with their weights, or one milestone opened (who is building, what is blocked and on what, what merged in 7 days, an estimate) | |
54 | `limb` | `{ app, issue, action, reason?, pillar?, operation?, dryRun? }`: defer, resume or close a whole limb as not doing, or undo an operation; plans unless `dryRun` is false, and applying takes an admin token | yes |
54 | `limb` | `{ app, issue, action, reason?, pillar?, operation?, dryRun? }`: defer, resume, close a whole limb as not doing, or hand it to the planner (`replan`), or undo an operation; plans unless `dryRun` is false, and applying takes an admin token | yes |
5555 | `watch` | `{ app, issue, watch? }`: watch a milestone, or stop with `watch: false`: one item in your feed that follows it, and one push to your phone when it lands | yes |
5656 | `usage` | `{ repo, days? }`: what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's | |
5757 | `link` | `{ app, issue, blockedBy }`: the issue waits for another; loops and cross-repository are refused | yes |
docs/PLANNING.md +19 −5
@@ -294,13 +294,27 @@ one undo.
294294 the limb included, as `dropped`, with the reason said on each. What other
295295 work outside the limb also waits for is not the limb's to close.
296296
297 An umbrella or the gate is the plan's own and is not filed. A leaf beneath
298 a limb that is not deferred cannot be deferred alone: defer the limb. A
299 candidate to trim offers Defer first. Raising and lowering a limb against
300 its siblings is #760; handing one to the planner is #761.
297 - **Hand to the planner** (#761) gives the limb to the repository's planner
298 to re-plan as fewer, larger pieces: the limb's issue is assigned to it
299 (the fleet's `replan`), which starts its run, and the run is given every
300 open issue of the limb's own with what each waits for
301 (`crew/handover.ts`). While the planner holds it, nothing of the limb's
302 own is ready, and the map, the milestone and their data say _with the
303 planner_. Inside the limb the planner may close an issue only as `split`
304 into open issues it made since the hand-over, and may drop nothing;
305 outside it, nothing (the same grant as a hand-over by the crew, above).
306 The milestone's closed issues say what each was split into. Undo takes
307 the limb back; and once the planner's run ends, whichever way, the limb
308 is the person's again, with a word on it. Not on a public repository,
309 where a crew assignment would let any reader steer the run (#619).
310
311 An umbrella or the gate is the plan's own and is not filed or handed over.
312 A leaf beneath a limb that is not deferred cannot be deferred alone: defer
313 the limb. A candidate to trim offers Defer first. Raising and lowering a
314 limb against its siblings is #760.
301315
302316 The same is `POST /api/v1/repos/:owner/:name/milestones/:number/limb`
303 `{ "action": "defer" | "resume" | "close", "reason"?, "pillar"?, "dryRun"? }`
317 `{ "action": "defer" | "resume" | "close" | "replan", "reason"?, "pillar"?, "dryRun"? }`
304318 and the MCP's `limb`, both a dry run unless `dryRun` is false. Applying and
305319 undoing take an admin token of a person who administers the repository; an
306320 agent may look and never apply.
scripts/gate.ts +1
@@ -157,6 +157,7 @@ export const GATE: readonly string[] = [
157157 "test/issues.test.ts",
158158 "test/kernel.test.ts",
159159 "test/keys.test.ts",
160 "test/limb-planner.test.ts",
160161 "test/limbs.test.ts",
161162 "test/live-pages.test.ts",
162163 "test/live.test.ts",
src/actions/issues.ts +6 −1
@@ -51,6 +51,7 @@ import { getUserById, type User } from "../core/users.ts";
5151 import { mayDirectCrew, unadoptedAmong } from "../crew/direct.ts";
5252 import { laterGate } from "../crew/later.ts";
5353 import { handedOverAt } from "../crew/parks.ts";
54 import { handoverOver } from "../crew/handover.ts";
5455 import { listReviews } from "../core/reviews.ts";
5556 import {
5657 applyLabelNames,
@@ -424,7 +425,11 @@ function handedToPlanner(
424425 ): boolean {
425426 if (issue.kind !== "issue" || issue.state !== "open") return false;
426427 if (crewRole(app.db, repo.id, actor.id) !== "planner") return false;
427 const handed = handedOverAt(app.db, repo, issue.id);
428 // Handed over by the crew (parked twice), or by a person with its limb
429 // (`crew/handover.ts`): since when says which replacements are fresh.
430 const handed =
431 handedOverAt(app.db, repo, issue.id) ??
432 handoverOver(app.db, repo, issue, actor.id)?.since;
428433 if (handed === undefined) return false;
429434 // Dropped only when no person's ask stands in it — not one the planner
430435 // wrote to replace a person's, however many times it was split since.
src/actions/limbs.ts +16 −2
@@ -15,6 +15,10 @@
1515 * - `close` drops every open issue of the limb, the limb included, with
1616 * one reason said on each — and never what something outside the limb
1717 * also waits for.
18 * - `replan` hands the limb to the repository's planner (the fleet's
19 * `replan`: the limb's issue is assigned to it), to be re-planned as
20 * fewer, larger pieces. Nothing of the limb's own is ready until the
21 * planner answers (`crew/handover.ts`).
1822 *
1923 * Who may is the fleet's rule, unchanged: a person who administers the
2024 * repository; an agent may preview and never apply.
@@ -35,7 +39,7 @@ import {
3539 type Plan,
3640 } from "./fleet.ts";
3741
38 export const LIMB_ACTIONS = ["defer", "resume", "close"] as const;
42 export const LIMB_ACTIONS = ["defer", "resume", "close", "replan"] as const;
3943 export type LimbAction = (typeof LIMB_ACTIONS)[number];
4044
4145 export const isLimbAction = (value: unknown): value is LimbAction =>
@@ -58,7 +62,7 @@ export interface LimbIssue {
5862 /** What a limb action takes with it beyond the rows it writes. */
5963 export interface LimbReach {
6064 readonly limb: LimbIssue;
61 /** For `defer`: what stops being ready. For `resume`: what is no longer deferred. */
65 /** For `defer`: what stops being ready. For `resume`: what is no longer deferred. For `replan`: what the planner is given. */
6266 readonly taken: readonly LimbIssue[];
6367 /** For `defer` and `close`: what beneath it stays, because something outside the limb still waits for it. */
6468 readonly kept: readonly LimbIssue[];
@@ -125,6 +129,16 @@ function shape(
125129 },
126130 });
127131 }
132 if (request.action === "replan")
133 return ok({
134 query: `${where} number:${number}`,
135 action: { verb: "replan", value: null },
136 reach: {
137 limb,
138 taken: rows.own.filter((i) => i.state === "open").map(brief),
139 kept: rows.shared.filter((i) => i.state === "open").map(brief),
140 },
141 });
128142 // Leaves first: a limb comes back from behind the gate from the bottom.
129143 return ok({
130144 query: `${where} limb:${number}^ state:open`,
src/core/dependencies.ts +112 −2
@@ -14,6 +14,7 @@ import { getIssuesByIds, type CloseReason, type Issue } from "./issues.ts";
1414 import { pillarsOf, structuralIds } from "./pillars.ts";
1515 import { getRepoById } from "./repos.ts";
1616 import { unadoptedAmong } from "../crew/direct.ts";
17 import { listCrewRoles } from "./agents.ts";
1718
1819 export type DependencyError = "self" | "cross_repo" | "cycle" | "not_an_issue";
1920
@@ -215,6 +216,11 @@ export interface Graph {
215216 * words, as every surface says it (`deferredWhy`).
216217 */
217218 readonly deferred: ReadonlyMap<string, string>;
219 /**
220 * Open issues a person handed to the planner with their limb (#761), with
221 * why (`withPlannerIn`). None of them is ready until it answers.
222 */
223 readonly withPlanner: ReadonlyMap<string, string>;
218224 }
219225
220226 /**
@@ -318,12 +324,14 @@ export function repoGraph(
318324 );
319325 const repo = getRepoById(db, repoId);
320326 const set = repo === undefined ? undefined : pillarsOf(db, repo);
327 const structural = set === undefined ? new Set<string>() : structuralIds(set);
321328 return {
322329 issues,
323330 unadopted:
324331 repo === undefined ? new Set() : unadoptedAmong(db, repo, issues),
325 structural: set === undefined ? new Set() : structuralIds(set),
332 structural,
326333 edges: kept,
334 withPlanner: withPlannerIn(db, repoId, { issues, edges: kept }, structural),
327335 held: heldRows
328336 .filter((r) => present.has(r.issue_id) && present.has(r.blocked_by_id))
329337 .map((r) => ({
@@ -340,6 +348,107 @@ export function repoGraph(
340348 };
341349 }
342350
351 /**
352 * A limb's own and shared issues (#733): from `root`, everything beneath it
353 * through the edges, the plan's furniture left out. Own is what no other
354 * open work outside the limb waits for; shared is the rest. Top down means
355 * every issue before what it waits for — siblings included, so an order
356 * among them holds — and leaves first is the same list read backwards
357 * (Kahn's walk, ties by number). An umbrella's wait is membership, not
358 * need: on a plan where every issue is linked under its pillar, a leaf is
359 * still the limb's own.
360 */
361 export function ownOf(
362 graph: Pick<Graph, "issues" | "edges">,
363 structural: ReadonlySet<string>,
364 root: string,
365 ): { own: string[]; shared: string[] } {
366 const byId = new Map(graph.issues.map((i) => [i.id, i]));
367 const waitsFor = new Map<string, string[]>();
368 const waitedBy = new Map<string, string[]>();
369 for (const edge of graph.edges) {
370 if (structural.has(edge.blockedById)) continue;
371 waitsFor.set(edge.issueId, [...(waitsFor.get(edge.issueId) ?? []), edge.blockedById]);
372 waitedBy.set(edge.blockedById, [...(waitedBy.get(edge.blockedById) ?? []), edge.issueId]);
373 }
374 const found = [root];
375 const inside = new Set(found);
376 for (let n = 0; n < found.length; n++)
377 for (const child of waitsFor.get(found[n]!) ?? [])
378 if (!inside.has(child)) {
379 inside.add(child);
380 found.push(child);
381 }
382 const waitedIn = new Map<string, number>();
383 for (const id of inside)
384 for (const child of waitsFor.get(id) ?? [])
385 if (inside.has(child)) waitedIn.set(child, (waitedIn.get(child) ?? 0) + 1);
386 const byNumberAsc = (a: string, b: string) =>
387 (byId.get(a)?.number ?? 0) - (byId.get(b)?.number ?? 0);
388 const order: string[] = [];
389 let free = found.filter((id) => (waitedIn.get(id) ?? 0) === 0).sort(byNumberAsc);
390 const placed = new Set<string>();
391 while (free.length > 0) {
392 const next = free.shift()!;
393 order.push(next);
394 placed.add(next);
395 for (const child of waitsFor.get(next) ?? []) {
396 if (!inside.has(child)) continue;
397 const left = (waitedIn.get(child) ?? 0) - 1;
398 waitedIn.set(child, left);
399 if (left === 0) free = [...free, child].sort(byNumberAsc);
400 }
401 }
402 for (const id of found) if (!placed.has(id)) order.push(id);
403 const shared = new Set<string>();
404 for (let grew = true; grew; ) {
405 grew = false;
406 for (const id of order) {
407 if (id === root || shared.has(id)) continue;
408 const needed = (waitedBy.get(id) ?? []).some(
409 (w) =>
410 byId.get(w)?.state === "open" &&
411 !structural.has(w) &&
412 (!inside.has(w) || shared.has(w)),
413 );
414 if (needed) {
415 shared.add(id);
416 grew = true;
417 }
418 }
419 }
420 return {
421 own: order.filter((id) => !shared.has(id)),
422 shared: order.filter((id) => shared.has(id)),
423 };
424 }
425
426 /**
427 * What a person handed to the planner (#761): every open issue that is the
428 * own of a limb whose issue is assigned to the repository's planner, with
429 * why. Nothing beneath such a limb is ready until the planner has answered
430 * — split what it was given into fewer, larger pieces, or let the limb go.
431 */
432 function withPlannerIn(
433 db: Database,
434 repoId: string,
435 graph: Pick<Graph, "issues" | "edges">,
436 structural: ReadonlySet<string>,
437 ): Map<string, string> {
438 const out = new Map<string, string>();
439 const planner = listCrewRoles(db, repoId).find((c) => c.role === "planner");
440 if (planner === undefined) return out;
441 const byId = new Map(graph.issues.map((i) => [i.id, i]));
442 for (const root of graph.issues) {
443 if (root.state !== "open" || root.assigneeId !== planner.agent.user.id) continue;
444 if (structural.has(root.id)) continue;
445 const why = `with the planner: #${root.number} ${root.title}`;
446 for (const id of ownOf(graph, structural, root.id).own)
447 if (byId.get(id)?.state === "open" && !out.has(id)) out.set(id, why);
448 }
449 return out;
450 }
451
343452 /** How many limbs a reason names before it counts the rest. */
344453 const NAMED_LIMBS = 2;
345454
@@ -515,7 +624,8 @@ export function readyNow(graph: Graph): Ranked[] {
515624 (r) =>
516625 !graph.unadopted.has(r.issue.id) &&
517626 !graph.structural.has(r.issue.id) &&
518 !graph.deferred.has(r.issue.id),
627 !graph.deferred.has(r.issue.id) &&
628 !graph.withPlanner.has(r.issue.id),
519629 );
520630 }
521631
src/core/milestones.ts +68 −69
@@ -14,7 +14,7 @@
1414 */
1515
1616 import type { Database } from "bun:sqlite";
17 import { deferredIn, repoGraph, type Graph } from "./dependencies.ts";
17 import { deferredIn, ownOf, repoGraph, type Graph } from "./dependencies.ts";
1818 import type { Issue } from "./issues.ts";
1919 import {
2020 isStructural,
@@ -22,6 +22,7 @@ import {
2222 PILLAR_DAYS,
2323 pillarsOf,
2424 pillarWindowStart,
25 structuralIds,
2526 type Pillars,
2627 } from "./pillars.ts";
2728 import { closesFromBody, openPullsClosing } from "./pulls.ts";
@@ -58,6 +59,8 @@ export interface Limb {
5859 readonly deferred: boolean;
5960 /** Why, in plain words: "behind the Later gate", or which deferred limb needs it. */
6061 readonly deferredBecause?: string;
62 /** With the planner since then (#761): a person handed it over to be re-planned. */
63 readonly withPlannerSince?: string;
6164 /** Why it is a candidate to trim, when it is one. */
6265 readonly trim?: string;
6366 }
@@ -68,6 +71,7 @@ export type LeafState =
6871 | "gone"
6972 | "building"
7073 | "proposed"
74 | "replanning"
7175 | "deferred"
7276 | "blocked"
7377 | "ready";
@@ -102,6 +106,8 @@ export interface Milestone extends Limb {
102106 readonly state: LeafState;
103107 /** For a deferred leaf: why. */
104108 readonly why?: string;
109 /** For a leaf closed as split: the numbers it was split into. */
110 readonly into?: readonly number[];
105111 }[];
106112 }
107113
@@ -143,6 +149,35 @@ interface MergedPull {
143149 readonly closes: readonly number[];
144150 }
145151
152 /** What an issue closed as split was split into, from its closing event. */
153 function splitInto(db: Database, issue: Issue): number[] {
154 const row = db
155 .query<{ parts: string | null }, [string, number]>(
156 `SELECT json_extract(payload, '$.into') AS parts FROM event
157 WHERE repo_id = ?1 AND kind = 'issue.closed'
158 AND json_extract(payload, '$.number') = ?2
159 ORDER BY id DESC LIMIT 1`,
160 )
161 .get(issue.repoId, issue.number);
162 const parsed: unknown =
163 row?.parts === null || row?.parts === undefined ? [] : JSON.parse(row.parts);
164 return Array.isArray(parsed) ? parsed.filter((n): n is number => typeof n === "number") : [];
165 }
166
167 /** When an issue was last assigned, by the event; undefined for none. */
168 function assignedAt(db: Database, issue: Issue): string | undefined {
169 return (
170 db
171 .query<{ at: string }, [string, number]>(
172 `SELECT created_at AS at FROM event
173 WHERE repo_id = ?1 AND kind = 'issue.assigned'
174 AND json_extract(payload, '$.number') = ?2
175 ORDER BY id DESC LIMIT 1`,
176 )
177 .get(issue.repoId, issue.number)?.at ?? undefined
178 );
179 }
180
146181 /** Is it work that counts: open, or finished. Dropped and split are neither. */
147182 const counted = (issue: Issue): boolean =>
148183 issue.state === "open" ||
@@ -288,6 +323,7 @@ export function readPlan(
288323 if (issue.state === "closed") return counted(issue) ? "done" : "gone";
289324 if (building.has(issue.id)) return "building";
290325 if (proposed.has(issue.number)) return "proposed";
326 if (graph.withPlanner.has(issue.id)) return "replanning";
291327 if (graph.deferred.has(issue.id)) return "deferred";
292328 const open = (waitsFor.get(issue.id) ?? []).some(
293329 (id) => byId.get(id)?.state === "open",
@@ -344,12 +380,18 @@ export function readPlan(
344380 ? `${weight.open} open and nobody building`
345381 : undefined;
346382 const why = graph.deferred.get(issue.id);
383 const handed = graph.withPlanner.has(issue.id)
384 ? (assignedAt(db, issue) ?? issue.updatedAt)
385 : undefined;
347386 return {
348387 issue,
349388 name: nameOf(issue),
350389 weight,
351390 deferred,
352391 ...(why === undefined ? {} : { deferredBecause: why }),
392 ...(handed === undefined || issue.assigneeId === null
393 ? {}
394 : { withPlannerSince: handed }),
353395 ...(trim === undefined ? {} : { trim }),
354396 };
355397 };
@@ -376,67 +418,10 @@ export function readPlan(
376418 limb(number: number): { own: Issue[]; shared: Issue[] } | undefined {
377419 const issue = byNumber.get(number);
378420 if (issue === undefined) return undefined;
379 const found = [issue.id];
380 const inside = new Set(found);
381 for (let n = 0; n < found.length; n++)
382 for (const child of waitsFor.get(found[n]!) ?? [])
383 if (!inside.has(child)) {
384 inside.add(child);
385 found.push(child);
386 }
387 // Top down means every issue before what it waits for — siblings
388 // included, so an order among them holds — and leaves first is the
389 // same list read backwards. Kahn's walk, ties by number.
390 const waitedIn = new Map<string, number>();
391 for (const id of inside)
392 for (const child of waitsFor.get(id) ?? [])
393 if (inside.has(child))
394 waitedIn.set(child, (waitedIn.get(child) ?? 0) + 1);
395 const byNumberAsc = (a: string, b: string) =>
396 (byId.get(a)?.number ?? 0) - (byId.get(b)?.number ?? 0);
397 const order: string[] = [];
398 let free = found.filter((id) => (waitedIn.get(id) ?? 0) === 0).sort(byNumberAsc);
399 const placed = new Set<string>();
400 while (free.length > 0) {
401 const next = free.shift()!;
402 order.push(next);
403 placed.add(next);
404 for (const child of waitsFor.get(next) ?? []) {
405 if (!inside.has(child)) continue;
406 const left = (waitedIn.get(child) ?? 0) - 1;
407 waitedIn.set(child, left);
408 if (left === 0) free = [...free, child].sort(byNumberAsc);
409 }
410 }
411 for (const id of found) if (!placed.has(id)) order.push(id);
412 // Shared: other open work outside the limb waits for it, directly or
413 // through something beneath the limb that is itself shared. An
414 // umbrella's wait is membership, not need: on a plan where every
415 // issue is linked under its pillar, a leaf is still the limb's own.
416 const shared = new Set<string>();
417 for (let grew = true; grew; ) {
418 grew = false;
419 for (const id of order) {
420 if (id === issue.id || shared.has(id)) continue;
421 const needed = (waitedBy.get(id) ?? []).some(
422 (w) =>
423 byId.get(w)?.state === "open" &&
424 !isStructural(set, w) &&
425 (!inside.has(w) || shared.has(w)),
426 );
427 if (needed) {
428 shared.add(id);
429 grew = true;
430 }
431 }
432 }
433 const issues = order
434 .map((id) => byId.get(id))
435 .filter((i): i is Issue => i !== undefined);
436 return {
437 own: issues.filter((i) => !shared.has(i.id)),
438 shared: issues.filter((i) => shared.has(i.id)),
439 };
421 const { own, shared } = ownOf(graph, structuralIds(set), issue.id);
422 const issues = (ids: string[]) =>
423 ids.map((id) => byId.get(id)).filter((i): i is Issue => i !== undefined);
424 return { own: issues(own), shared: issues(shared) };
440425 },
441426 deferral(number: number): { taken: Issue[]; kept: Issue[] } | undefined {
442427 const limb = this.limb(number);
@@ -503,7 +488,9 @@ export function readPlan(
503488 ? "Nothing beneath it counts as work yet."
504489 : open === 0
505490 ? "Everything beneath it is done."
506 : limb.deferred
491 : limb.withPlannerSince !== undefined
492 ? "With the planner: it re-plans this as fewer, larger pieces, and nothing beneath it is picked until it has answered."
493 : limb.deferred
507494 ? `Deferred${limb.deferredBecause === undefined ? "" : ` (${limb.deferredBecause})`}: the crew picks nothing beneath it until it is resumed, so there is no pace to estimate from.`
508495 : closedThisWeek === 0
509496 ? `Nothing closed here in ${PILLAR_DAYS} days, so there is no pace to estimate from.`
@@ -511,11 +498,12 @@ export function readPlan(
511498 const order: Record<LeafState, number> = {
512499 building: 0,
513500 proposed: 1,
514 ready: 2,
515 blocked: 3,
516 deferred: 4,
517 done: 5,
518 gone: 6,
501 replanning: 2,
502 ready: 3,
503 blocked: 4,
504 deferred: 5,
505 done: 6,
506 gone: 7,
519507 };
520508 return {
521509 ...limb,
@@ -541,7 +529,14 @@ export function readPlan(
541529 const state = stateOf(c);
542530 const why =
543531 state === "deferred" ? graph.deferred.get(c.id) : undefined;
544 return { issue: c, state, ...(why === undefined ? {} : { why }) };
532 const into =
533 c.closeReason === "split" ? splitInto(db, c) : undefined;
534 return {
535 issue: c,
536 state,
537 ...(why === undefined ? {} : { why }),
538 ...(into === undefined || into.length === 0 ? {} : { into }),
539 };
545540 })
546541 .sort(
547542 (a, b) =>
@@ -577,6 +572,9 @@ export function limbJson(limb: Limb): Record<string, unknown> {
577572 ...(limb.deferredBecause === undefined
578573 ? {}
579574 : { deferredBecause: limb.deferredBecause }),
575 ...(limb.withPlannerSince === undefined
576 ? {}
577 : { withPlannerSince: limb.withPlannerSince }),
580578 ...(limb.trim === undefined ? {} : { trim: limb.trim }),
581579 };
582580 }
@@ -610,6 +608,7 @@ export function milestoneJson(
610608 ...brief(leaf.issue),
611609 state: leaf.state,
612610 ...(leaf.why === undefined ? {} : { deferredBecause: leaf.why }),
611 ...(leaf.into === undefined ? {} : { splitInto: leaf.into }),
613612 })),
614613 };
615614 }
src/crew/autonomy.ts +26
@@ -714,6 +714,10 @@ export function parkIssue(
714714 * the provider or a restart cut short is interrupted, not parked: no note,
715715 * no strike.
716716 */
717 /** A run's summary as one short line for a comment. */
718 const oneLineOf = (text: string): string =>
719 text.replace(/\s+/g, " ").trim().slice(0, 160);
720
717721 export function settleAgentRun(
718722 app: App,
719723 repo: Repo,
@@ -738,6 +742,28 @@ export function settleAgentRun(
738742 if (run.reason === "review") return false;
739743 if (/opened pull #|updated pull #/.test(run.summary)) return false;
740744 if (interruptionOf(run.summary) !== undefined) return false;
745 // A planner is done with a limb a person handed it the same way: once its
746 // run ends, whichever way, the limb is the person's again and its work
747 // goes (`crew/handover.ts`).
748 if (
749 run.actorId !== null &&
750 repo.autonomyBy !== null &&
751 crewRole(app.db, repo.id, run.actorId) === "planner"
752 ) {
753 const limb = getIssueById(app.db, run.issueId);
754 const by = getUserById(app.db, repo.autonomyBy);
755 if (limb?.assigneeId === run.actorId && limb.state === "open" && by) {
756 assignIssue(app, by, repo, limb, null);
757 addComment(
758 app,
759 by,
760 repo,
761 limb,
762 `Back from the planner: its run ended${run.summary ? ` (${oneLineOf(run.summary)})` : ""}.`,
763 );
764 }
765 return false;
766 }
741767 if (answeredWithoutChange(app, repo, run)) return true;
742768 const issue = getIssueById(app.db, run.issueId);
743769 if (!issue || issue.kind !== "issue" || issue.state !== "open") return false;
src/crew/brief.ts +22 −1
@@ -12,6 +12,7 @@ import type { Comment, Issue } from "../core/issues.ts";
1212 import type { Pull } from "../core/pulls.ts";
1313 import { OUTSIDE_LABEL, OUTSIDE_TITLE, saysOutside } from "../core/reports.ts";
1414 import type { Repo } from "../core/repos.ts";
15 import type { Handover } from "./handover.ts";
1516 import { READER } from "./direct.ts";
1617 import { newsSince } from "./news.ts";
1718 import {
@@ -166,6 +167,8 @@ export interface TaskInput extends BriefInput {
166167 readonly parkedTwice?: readonly HandedOver[] | undefined;
167168 /** For a planner: the issue deferred work waits behind, if there is one. */
168169 readonly laterGate?: number | undefined;
170 /** For a planning run on a limb a person handed over (`crew/handover.ts`). */
171 readonly handover?: Handover | undefined;
169172 }
170173
171174 /** An issue the crew parked twice, as the planner is told of it. */
@@ -196,7 +199,7 @@ function taskBody(input: TaskInput): string {
196199 const { issue } = input;
197200 const out: string[] = [];
198201 const isAgent = (name: string): boolean => name === input.agent.user.username;
199 const handed = parkedTwiceLines(input);
202 const handed = [...handoverLines(input), ...parkedTwiceLines(input)];
200203 const readers = input.readers ?? new Set<string>();
201204 const said = (author: string): string =>
202205 readers.has(author) ? `@${author} ${READER}` : `@${author}`;
@@ -409,6 +412,24 @@ function taskBody(input: TaskInput): string {
409412 * repository has one, or, for an issue the crew wrote, dropped. Nothing
410413 * for anyone else, or when there are none.
411414 */
415 /** A limb a person handed to the planner: what it is given, and what it may do with it. */
416 function handoverLines(input: TaskInput): string[] {
417 const limb = input.role === "planner" ? input.handover : undefined;
418 if (limb === undefined) return [];
419 const issues = `$FORGE_URL/api/v1/repos/${input.repo.ownerName}/${input.repo.name}/issues`;
420 return [
421 `This run is not the direction. A person handed you one limb of the plan, #${limb.number} ${limb.title}, to re-plan as fewer, larger pieces. Nothing beneath it is picked until you have answered. Its open issues, the limb first:`,
422 ...limb.issues.map(
423 (i) =>
424 `- #${i.number} ${i.title}${i.waitsFor.length === 0 ? "" : ` (waits for ${i.waitsFor.map((n) => `#${n}`).join(", ")})`}`,
425 ),
426 "Read them, then leave each in exactly one of these states, and say which in a comment on it:",
427 `- Split: open the fewer, larger issues first, link each under the limb (POST ${issues}/${limb.number}/dependencies with {"blockedBy": M}) and under the limb's pillar as the plan does, then close the old one as split into them — PATCH ${issues}/N with {"state":"closed","reason":"split","into":[A,B]}. Only open issues made since the hand-over are accepted, and only for issues of this limb.`,
428 '- Kept: when it is already the right size, say so on it and leave it open.',
429 "Drop nothing: what a person asked for is split or kept, never closed as dropped. Assign nobody and push nothing. Finish with a short message that lists what replaced what; the limb comes back to the person when you are done.",
430 ];
431 }
432
412433 function parkedTwiceLines(input: TaskInput): string[] {
413434 const handed = input.role === "planner" ? (input.parkedTwice ?? []) : [];
414435 if (handed.length === 0) return [];
src/crew/handover.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * A limb handed to the planner (#761). A person who administers the
3 * repository hands a limb over to be re-planned as fewer, larger pieces:
4 * its issue is assigned to the planner (the fleet's `replan`), which gives
5 * the planner a run on it. While it holds the limb, nothing that is the
6 * limb's own is ready (`core/dependencies.ts`, `withPlanner`); the planner
7 * may close an issue of the limb only as `split` into fresh issues made
8 * since the hand-over (`actions/issues.ts`); a person takes it back by
9 * undoing the operation, and once the planner's run on it ends, whichever
10 * way, the limb is the person's again and its work goes
11 * (`autonomy.ts`, `settleAgentRun`).
12 *
13 * This module reads one hand-over: which limb, since when, and what the
14 * planner is given.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { crewRole } from "../core/agents.ts";
19 import { readPlan } from "../core/milestones.ts";
20 import { getIssueById, type Issue } from "../core/issues.ts";
21 import type { Repo } from "../core/repos.ts";
22
23 /** The limb as the planner's brief and the grant read it. */
24 export interface Handover {
25 readonly number: number;
26 readonly title: string;
27 /** When it was handed over: the planner's assignment. */
28 readonly since: string;
29 /** Every open issue that is the limb's own, the limb first, with what each waits for. */
30 readonly issues: readonly {
31 readonly number: number;
32 readonly title: string;
33 readonly waitsFor: readonly number[];
34 }[];
35 }
36
37 /** When this issue was last assigned to its assignee, by the event; undefined for none. */
38 export function assignedAt(db: Database, issue: Issue): string | undefined {
39 if (issue.assigneeId === null) return undefined;
40 return (
41 db
42 .query<{ at: string }, [string, number]>(
43 `SELECT created_at AS at FROM event
44 WHERE repo_id = ?1 AND kind = 'issue.assigned'
45 AND json_extract(payload, '$.number') = ?2
46 ORDER BY id DESC LIMIT 1`,
47 )
48 .get(issue.repoId, issue.number)?.at ?? undefined
49 );
50 }
51
52 /** Whether this open issue is a limb the planner holds. */
53 export function heldByPlanner(db: Database, repo: Repo, issue: Issue): boolean {
54 return (
55 issue.kind === "issue" &&
56 issue.state === "open" &&
57 issue.assigneeId !== null &&
58 issue.assigneeIsAgent &&
59 crewRole(db, repo.id, issue.assigneeId) === "planner"
60 );
61 }
62
63 /**
64 * The hand-over this issue is, when the planner holds it as a limb: what
65 * the brief says and the grant allows. Undefined for any other issue.
66 */
67 export function handoverOf(
68 db: Database,
69 repo: Repo,
70 issue: Issue,
71 ): Handover | undefined {
72 if (!heldByPlanner(db, repo, issue)) return undefined;
73 const plan = readPlan(db, repo);
74 const limb = plan.limb(issue.number);
75 if (limb === undefined) return undefined;
76 const since = assignedAt(db, issue);
77 if (since === undefined) return undefined;
78 const waits = new Map<string, number[]>();
79 // What each waits for, among the open issues the planner is given.
80 const given = limb.own.filter((i) => i.state === "open");
81 const numbers = new Map(given.map((i) => [i.id, i.number]));
82 for (const row of db
83 .query<{ issue_id: string; blocked_by_id: string }, string[]>(
84 `SELECT issue_id, blocked_by_id FROM issue_dependency
85 WHERE issue_id IN (${given.map((_, n) => `?${n + 1}`).join(",") || "''"})`,
86 )
87 .all(...given.map((i) => i.id))) {
88 const on = numbers.get(row.blocked_by_id);
89 if (on !== undefined)
90 waits.set(row.issue_id, [...(waits.get(row.issue_id) ?? []), on]);
91 }
92 return {
93 number: issue.number,
94 title: issue.title,
95 since,
96 issues: given.map((i) => ({
97 number: i.number,
98 title: i.title,
99 waitsFor: (waits.get(i.id) ?? []).sort((a, b) => a - b),
100 })),
101 };
102 }
103
104 /**
105 * The limb the planner holds that this issue is the own of — the issue
106 * itself, or one beneath it — and since when. What the grant reads: inside
107 * it, the planner may split; outside it, nothing.
108 */
109 export function handoverOver(
110 db: Database,
111 repo: Repo,
112 issue: Issue,
113 plannerId: string,
114 ): { root: Issue; since: string } | undefined {
115 const roots = db
116 .query<{ id: string }, [string, string]>(
117 `SELECT id FROM issue
118 WHERE repo_id = ?1 AND kind = 'issue' AND state = 'open' AND assignee_id = ?2
119 ORDER BY number`,
120 )
121 .all(repo.id, plannerId)
122 .map((r) => r.id);
123 if (roots.length === 0) return undefined;
124 const plan = readPlan(db, repo);
125 for (const rootId of roots) {
126 const root = getIssueById(db, rootId);
127 if (root === undefined || !heldByPlanner(db, repo, root)) continue;
128 const limb = plan.limb(root.number);
129 if (limb === undefined || !limb.own.some((i) => i.id === issue.id)) continue;
130 const since = assignedAt(db, root);
131 if (since !== undefined) return { root, since };
132 }
133 return undefined;
134 }
src/crew/runner.ts +6 −1
@@ -82,6 +82,7 @@ import {
8282 whenText,
8383 } from "./limits.ts";
8484 import { interruptedSummary } from "./interrupted.ts";
85 import { handoverOf } from "./handover.ts";
8586 import { laterGate } from "./later.ts";
8687 import { parkedTwice } from "./parks.ts";
8788 import { noteLimit } from "../core/standing.ts";
@@ -798,13 +799,17 @@ async function work(
798799 ...(reason === "review" && pull
799800 ? await reviewInputs(app, repo, pull, record, bare)
800801 : {}),
801 // A planning run is given what the crew handed over (`parks.ts`).
802 // A planning run is given what the crew handed over (`parks.ts`), or
803 // the limb a person handed over (`handover.ts`).
802804 ...(brief.role === "planner" && issue.id === repo.directionIssueId
803805 ? {
804806 parkedTwice: parkedTwice(app.db, [repo]),
805807 laterGate: laterGate(app.db, repo.id),
806808 }
807809 : {}),
810 ...(brief.role === "planner" && issue.id !== repo.directionIssueId
811 ? { handover: handoverOf(app.db, repo, issue) }
812 : {}),
808813 checkKind:
809814 failedCheck?.run?.kind === "check" ||
810815 failedCheck?.run?.kind === "deploy"
src/fleet/verbs.ts +6 −1
@@ -414,9 +414,14 @@ export const VERBS: Record<string, Verb> = {
414414 nextFor: (t) => t.planner ?? null,
415415 refuse(app, t, after) {
416416 if (t.issue?.kind === "pull") return "a change is told what is off, not re-planned";
417 // Nothing to hand to: no planner. With one, `null` is the undo, taking
418 // the issue back, which is always allowed.
419 if (after === null)
420 return t.planner === null || t.planner === undefined
421 ? "no planner on this crew"
422 : undefined;
417423 if (t.repo.visibility === "public")
418424 return "public: a crew assignment here lets any reader steer it";
419 if (after === null) return "no planner on this crew";
420425 return ASSIGN.refuse(app, t, after);
421426 },
422427 },
src/http/api.ts +1 −1
@@ -2426,7 +2426,7 @@ export function apiRoutes(router: Router<Handler>): void {
24262426 const number = positiveInt(ctx.params.number);
24272427 if (!repo || number === undefined) return notFound();
24282428 if (!isLimbAction(input.action))
2429 return apiError("bad_action", 422, "action is defer, resume or close");
2429 return apiError("bad_action", 422, "action is defer, resume, close or replan");
24302430 const request = {
24312431 action: input.action,
24322432 ...(typeof input.reason === "string" ? { reason: input.reason } : {}),
src/http/mcp.ts +3 −3
@@ -1215,7 +1215,7 @@ const TOOLS: readonly Tool[] = [
12151215 {
12161216 name: "limb",
12171217 description:
1218 "One action on a whole limb of the plan — a milestone and everything beneath it that only it needs. `defer` moves the limb behind the Later gate, so the crew picks none of it; `resume` brings it back, under `pillar` when you name one; `close` closes every open issue of the limb as not doing, with `reason` said on each; `undo` reverses an `operation` by its id. A dry run unless `dryRun` is false: it answers with every row before and after, what the action takes along (`taken`) and what stays because something outside the limb still waits for it (`kept`), and changes nothing. Applying and undoing take an admin token of a person who administers the app, and answer with the receipt.",
1218 "One action on a whole limb of the plan — a milestone and everything beneath it that is its own. `defer` files every issue of the limb behind the Later gate, so the crew picks none of it; `resume` brings them back, under `pillar` when you name one; `close` closes every open issue of the limb as not doing, with `reason` said on each; `replan` hands the limb to the app's planner to re-plan as fewer, larger pieces, and nothing beneath it is picked until it answers; `undo` reverses an `operation` by its id. A dry run unless `dryRun` is false: it answers with every row before and after, what the action takes along (`taken`) and what stays because something outside the limb still waits for it (`kept`), and changes nothing. Applying and undoing take an admin token of a person who administers the app, and answer with the receipt.",
12191219 inputSchema: {
12201220 type: "object",
12211221 properties: {
@@ -1225,7 +1225,7 @@ const TOOLS: readonly Tool[] = [
12251225 minimum: 1,
12261226 description: "The limb: the number of its issue.",
12271227 },
1228 action: { type: "string", enum: ["defer", "resume", "close", "undo"] },
1228 action: { type: "string", enum: ["defer", "resume", "close", "replan", "undo"] },
12291229 reason: {
12301230 type: "string",
12311231 description: "For close: why it is not being done, in one sentence.",
@@ -1269,7 +1269,7 @@ const TOOLS: readonly Tool[] = [
12691269 !Number.isInteger(number) ||
12701270 number < 1
12711271 )
1272 return bad("invalid", "give the limb's issue number and an action: defer, resume, close or undo");
1272 return bad("invalid", "give the limb's issue number and an action: defer, resume, close, replan or undo");
12731273 const request = {
12741274 action: args["action"],
12751275 ...(typeof args["reason"] === "string" ? { reason: args["reason"] } : {}),
src/web/pages/limb.ts +9 −1
@@ -50,6 +50,11 @@ const WORDS: Record<LimbAction, { ask: string; does: string; go: string }> = {
5050 does: "Every open issue that only this limb needs closes as not doing, with your reason said on each.",
5151 go: "Close as not doing",
5252 },
53 replan: {
54 ask: "Hand over",
55 does: "The planner re-plans it as fewer, larger pieces: its next run is given every open issue of the limb, and nothing beneath it is picked until it has answered. Each old issue is closed as split into what replaces it; nothing a person asked for is dropped. Undo takes it back.",
56 go: "Hand to the planner",
57 },
5358 };
5459
5560 const shown = (value: FleetValue): string =>
@@ -196,7 +201,9 @@ export function limbPreviewPage(ctx: Ctx): Response {
196201 <h2>
197202 ${action === "resume"
198203 ? `${p.taken.length} can be picked again`
199 : `${p.taken.length} stop being picked`}
204 : action === "replan"
205 ? `${p.taken.length} go to the planner`
206 : `${p.taken.length} stop being picked`}
200207 </h2>
201208 ${issueList(base, p.taken)}
202209 </section>`,
@@ -313,6 +320,7 @@ export async function limbSubmit(ctx: Ctx): Promise<Response> {
313320 function done(op: Operation): string {
314321 if (op.undoOf !== null) return "Undone";
315322 if (op.verb === "drop") return "Closed as not doing";
323 if (op.verb === "replan") return "Handed to the planner";
316324 return op.value === "later" ? "Deferred" : "Resumed";
317325 }
318326
src/web/pages/map.ts +5
@@ -505,6 +505,11 @@ export function marksFor(
505505 parked.add(id);
506506 why.set(id, READER_SUGGESTION);
507507 }
508 // What a person handed to the planner with its limb waits for its answer.
509 for (const [id, note] of graph.withPlanner) {
510 parked.add(id);
511 why.set(id, note);
512 }
508513 // An umbrella or the gate with nothing open in front of it is not ready:
509514 // it is a person's to close.
510515 for (const issue of idleFurniture(graph)) {
src/web/pages/milestones.ts +15 −4
@@ -62,7 +62,8 @@ function limbActions(
6262 lead: Html | null,
6363 ): Html {
6464 const number = m.issue.number;
65 return html`<p class="bar ms-actions" id="limb-actions">
65 // A div, not a p: the Watch form inside would end a paragraph early.
66 return html`<div class="bar ms-actions" id="limb-actions">
6667 ${lead}
6768 ${furniture
6869 ? null
@@ -81,7 +82,14 @@ function limbActions(
8182 href: limbHref(base, number, "close"),
8283 size: "sm",
8384 })}
84 </p>`;
85 ${furniture || m.withPlannerSince !== undefined
86 ? null
87 : btn("Hand to the planner", {
88 href: limbHref(base, number, "replan"),
89 size: "sm",
90 title: "The planner re-plans it as fewer, larger pieces",
91 })}
92 </div>`;
8593 }
8694
8795 const dollars = (n: number): string => `$${n.toFixed(2)}`;
@@ -162,6 +170,7 @@ const STATE_WORDS: Record<LeafState, string> = {
162170 proposed: "proposed",
163171 ready: "ready",
164172 blocked: "blocked",
173 replanning: "with the planner",
165174 deferred: "deferred",
166175 done: "done",
167176 gone: "not doing",
@@ -361,7 +370,9 @@ function milestoneBody(
361370 html`<li data-state="${leaf.state}">
362371 ${issue(leaf.issue.number, leaf.issue.title)}
363372 <span class="ms-state small"
364 >${STATE_WORDS[leaf.state]}</span
373 >${leaf.into === undefined
374 ? STATE_WORDS[leaf.state]
375 : `split into ${leaf.into.map((n) => `#${n}`).join(", ")}`}</span
365376 >
366377 </li>`,
367378 )}
@@ -402,7 +413,7 @@ export function milestonePage(ctx: Ctx): Response {
402413 )
403414 : watch === null
404415 ? null
405 : html`<p class="bar ms-actions">${watch}</p>`;
416 : html`<div class="bar ms-actions">${watch}</div>`;
406417 return page({
407418 ctx,
408419 title: `${milestone.name} · ${repo.name}`,
test/limb-planner.test.ts added +432
@@ -0,0 +1,432 @@
1 /**
2 * Handing a limb to the planner (#761): a person who administers the
3 * repository hands one limb over to be re-planned as fewer, larger pieces.
4 *
5 * The refusals come first: a reader, an agent, the planner itself, a read
6 * token, a write token and nobody hand nothing over, and on a public
7 * repository the row is refused. Then: the limb goes to the planner and
8 * nothing of its own is picked while it holds it, the pages and the data
9 * say so; the planner's grant reaches exactly the limb; the brief lists
10 * what it is given; undo takes it back, and a run that ends without an
11 * answer lets the work go.
12 */
13 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
14 import { mkdtemp, rm } from "node:fs/promises";
15 import { tmpdir } from "node:os";
16 import { join } from "node:path";
17 import { createApp, type App } from "../src/app.ts";
18 import { addToCrew, createAgent } from "../src/actions/crew.ts";
19 import { linkIssue } from "../src/actions/dependencies.ts";
20 import { undoFleetOp } from "../src/actions/fleet.ts";
21 import { openIssue } from "../src/actions/issues.ts";
22 import { applyLimb, previewLimb } from "../src/actions/limbs.ts";
23 import {
24 commitToBranch,
25 createRepo,
26 updateRepoSettings,
27 } from "../src/actions/repos.ts";
28 import { getAgentByName, setCrewRole } from "../src/core/agents.ts";
29 import { readyNow, repoGraph } from "../src/core/dependencies.ts";
30 import { getIssueById, listComments, type Issue } from "../src/core/issues.ts";
31 import { getRepoById, type Repo } from "../src/core/repos.ts";
32 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
33 import { createToken } from "../src/core/tokens.ts";
34 import { createUser, getUserByName, type User } from "../src/core/users.ts";
35 import { settleAgentRun } from "../src/crew/autonomy.ts";
36 import { taskPrompt } from "../src/crew/brief.ts";
37 import { handoverOf } from "../src/crew/handover.ts";
38 import { interruptedSummary } from "../src/crew/interrupted.ts";
39 import { serve, type Servers } from "../src/http/server.ts";
40
41 describe("a limb handed to the planner", () => {
42 let dataDir: string;
43 let app: App;
44 let servers: Servers;
45 let base: string;
46 let alice: User;
47 let bob: User;
48 let mason: User;
49 let atlas: User;
50 let shop: Repo;
51 let engine: Repo;
52 let trust: Issue;
53 let feed: Issue;
54 let gate: Issue;
55 let iface: Issue;
56 let home: Issue;
57 let lists: Issue;
58 let search: Issue;
59 let shared: Issue;
60 let ship: Issue;
61 let loose: Issue;
62 let older: Issue;
63 let open: Issue;
64 /** The receipt of the hand-over, for the undo; and what the planner opened. */
65 let handedOp = "";
66 let whole: Issue;
67 const cookies: Record<string, string> = {};
68
69 const fresh = (repo: Repo) => getRepoById(app.db, repo.id)!;
70 const current = (issue: Issue) => getIssueById(app.db, issue.id)!;
71 const issue = (repo: Repo, title: string, by: User = alice): Issue => {
72 const opened = openIssue(app, by, fresh(repo), { title });
73 if (!opened.ok) throw new Error(String(opened.error));
74 return opened.value;
75 };
76 const link = (repo: Repo, waiter: Issue, on: Issue): void => {
77 const linked = linkIssue(app, alice, fresh(repo), current(waiter), current(on));
78 if (!linked.ok) throw new Error(String(linked.error));
79 };
80 const ready = (repo: Repo): number[] =>
81 readyNow(repoGraph(app.db, repo.id))
82 .map((r) => r.issue.number)
83 .sort((a, b) => a - b);
84 const tokenOf = (user: User, scope: "ro" | "rw" | "admin"): string =>
85 createToken(app.db, user.id, scope, scope).token;
86 const call = (method: string, path: string, token: string, body?: unknown) =>
87 fetch(`${base}${path}`, {
88 method,
89 headers: {
90 authorization: `Bearer ${token}`,
91 ...(body === undefined ? {} : { "content-type": "application/json" }),
92 },
93 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
94 });
95 const get = (who: string, path: string) =>
96 fetch(`${base}${path}`, {
97 headers: who === "" ? {} : { cookie: cookies[who]! },
98 redirect: "manual",
99 });
100 const at = (repo: Repo, m: Issue) =>
101 `/api/v1/repos/alice/${repo.name}/milestones/${m.number}/limb`;
102 const page = (repo: Repo, m: Issue) => `/alice/${repo.name}/milestones/${m.number}`;
103 let nextId = 1;
104 const tool = async (token: string, args: unknown) => {
105 const res = await call("POST", "/mcp", token, {
106 jsonrpc: "2.0",
107 id: nextId++,
108 method: "tools/call",
109 params: { name: "limb", arguments: args },
110 });
111 const answer = (await res.json()) as any;
112 const text: string = answer.result.content[0].text;
113 return answer.result.isError === true ? { error: text } : { value: JSON.parse(text) };
114 };
115 /** A planning run on the limb that ends without an answer, settled as the crew would. */
116 const unanswered = (on: Issue, summary: string): boolean => {
117 const run = createRun(app.db, {
118 repoId: shop.id,
119 kind: "agent",
120 issueId: on.id,
121 actorId: atlas.id,
122 reason: "assigned",
123 });
124 claimRun(app.db, run.id);
125 const recorded = interruptedSummary(summary);
126 finishRun(app.db, run.id, { state: "failed", summary: recorded });
127 return settleAgentRun(app, fresh(shop), {
128 issueId: on.id,
129 state: "failed",
130 summary: recorded,
131 reason: "assigned",
132 actorId: atlas.id,
133 });
134 };
135
136 beforeAll(async () => {
137 dataDir = await mkdtemp(join(tmpdir(), "forge-limb-planner-"));
138 app = createApp({ dataDir, port: 0 });
139 servers = await serve(app);
140 base = servers.url;
141 for (const [username, adminIfFirst] of [
142 ["alice", true],
143 ["bob", false],
144 ] as const) {
145 const made = await createUser(app.db, {
146 trusted: true,
147 username,
148 email: `${username}@forge.local`,
149 password: "a-good-passphrase",
150 adminIfFirst,
151 });
152 if (!made.ok) throw new Error(made.error);
153 cookies[username] = (
154 (
155 await fetch(`${base}/signin`, {
156 method: "POST",
157 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
158 redirect: "manual",
159 })
160 ).headers.get("set-cookie") ?? ""
161 ).split(";")[0]!;
162 }
163 alice = getUserByName(app.db, "alice")!;
164 bob = getUserByName(app.db, "bob")!;
165 for (const name of ["mason", "atlas"]) {
166 const agent = await createAgent(app, alice, { username: name });
167 if (!agent.ok) throw new Error(String(agent.error));
168 }
169 mason = getUserByName(app.db, "mason")!;
170 atlas = getUserByName(app.db, "atlas")!;
171 const repoOf = async (name: string, visibility: "public" | "private") => {
172 const made = await createRepo(app, alice, { name, visibility });
173 if (!made.ok) throw new Error(String(made.error));
174 const seeded = await commitToBranch(app, alice, made.value, {
175 message: "Start",
176 files: [{ path: "README.md", content: `# ${name}\n` }],
177 });
178 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
179 for (const name of ["mason", "atlas"])
180 expect(addToCrew(app, alice, made.value, name).ok).toBe(true);
181 setCrewRole(app.db, made.value.id, atlas.id, "planner");
182 const set = await updateRepoSettings(app, alice, made.value, {
183 autonomy: "autonomous",
184 autonomyDirection: "Keep it small.",
185 autonomyCeilingUsd: 100,
186 autonomyBy: alice.id,
187 });
188 if (!set.ok) throw new Error(JSON.stringify(set.error));
189 return made.value;
190 };
191 // The shop is private, as a plan with a crew is; the engine is public,
192 // where a crew assignment is never made (#619).
193 shop = await repoOf("shop", "private");
194 engine = await repoOf("engine", "public");
195 const plant = (repo: Repo) => {
196 const t = issue(repo, "P0 Trust: agents contained");
197 const f = issue(repo, "P1 Feed: one front door");
198 issue(repo, "Later: work that serves no pillar now");
199 const g = issue(repo, "Later gate: nothing behind this starts");
200 link(repo, f, t);
201 link(repo, g, t);
202 link(repo, g, f);
203 const i = issue(repo, "One interface");
204 const parts = ["One home", "One list", "One search", "A shared toolbar"].map((x) =>
205 issue(repo, x),
206 );
207 for (const part of parts) link(repo, i, part);
208 link(repo, parts[2]!, parts[1]!);
209 link(repo, f, i);
210 link(repo, f, parts[0]!);
211 link(repo, f, parts[1]!);
212 const s = issue(repo, "Ship the sandbox");
213 link(repo, s, parts[3]!);
214 link(repo, t, s);
215 return { t, f, g, i, parts, s };
216 };
217 const made = plant(shop);
218 ({ t: trust, f: feed, g: gate, i: iface, s: ship } = made);
219 [home, lists, search, shared] = made.parts as [Issue, Issue, Issue, Issue];
220 loose = issue(shop, "A loose end");
221 older = issue(shop, "An older idea");
222 ({ i: open } = plant(engine));
223 }, 60_000);
224
225 afterAll(async () => {
226 servers.stop();
227 app.close();
228 await rm(dataDir, { recursive: true, force: true });
229 });
230
231 test("refused: a reader, an agent, the planner, a read token, a write token and nobody hand nothing over; a public repository refuses the row", async () => {
232 const request = { action: "replan" as const };
233 const unassigned = () => expect(current(iface).assigneeId).toBeNull();
234 // The planner cannot hand a limb to itself; a builder cannot either.
235 for (const agent of [atlas, mason]) {
236 const tried = await applyLimb(app, agent, fresh(shop), iface.number, request);
237 expect(tried.ok ? "applied" : tried.error.code).toBe("forbidden");
238 }
239 const nobody = await applyLimb(app, undefined, fresh(shop), iface.number, request);
240 expect(nobody.ok ? "applied" : nobody.error.code).toBe("unauthorized");
241 // bob cannot see the shop at all.
242 const unseen = await applyLimb(app, bob, fresh(shop), iface.number, request);
243 expect(unseen.ok ? "applied" : unseen.error.code).toBe("not_found");
244 unassigned();
245 // Over the API and the MCP: read and write tokens plan at most.
246 const apply = { action: "replan", dryRun: false };
247 expect((await call("POST", at(shop, iface), tokenOf(alice, "ro"), apply)).status).toBe(403);
248 expect((await call("POST", at(shop, iface), tokenOf(alice, "rw"), apply)).status).toBe(403);
249 expect((await call("POST", at(shop, iface), tokenOf(atlas, "admin"), apply)).status).toBe(403);
250 expect((await call("POST", at(shop, iface), tokenOf(bob, "admin"), apply)).status).toBe(404);
251 expect(
252 (await tool(tokenOf(alice, "rw"), { app: "alice/shop", issue: iface.number, action: "replan", dryRun: false })).error,
253 ).toContain("forbidden");
254 unassigned();
255 // The page: nobody signed in, and a post from another origin.
256 const press = (who: string, origin: string) =>
257 fetch(`${base}${page(shop, iface)}/limb`, {
258 method: "POST",
259 headers: { ...(who === "" ? {} : { cookie: cookies[who]! }), origin },
260 body: new URLSearchParams({ action: "replan" }),
261 redirect: "manual",
262 });
263 // Nobody signed in: the shop cannot be seen; the public engine sends them to sign in.
264 expect((await press("", base)).status).toBe(404);
265 expect(
266 (
267 await fetch(`${base}${page(engine, open)}/limb`, {
268 method: "POST",
269 headers: { origin: base },
270 body: new URLSearchParams({ action: "replan" }),
271 redirect: "manual",
272 })
273 ).status,
274 ).toBe(303);
275 expect((await press("alice", "https://evil.test")).status).toBe(403);
276 unassigned();
277 // On a public repository the row is refused: a crew assignment there
278 // would let any reader steer the run.
279 const plan = previewLimb(app, alice, fresh(engine), open.number, request);
280 expect(plan.ok && plan.value.rows.map((r) => [r.outcome, r.reason])).toEqual([
281 ["refused", "public: a crew assignment here lets any reader steer it"],
282 ]);
283 const tried = await applyLimb(app, alice, fresh(engine), open.number, request);
284 expect(tried.ok && tried.value.rows[0]!.outcome).toBe("refused");
285 expect(current(open).assigneeId).toBeNull();
286 // An umbrella is not handed over; its limbs are.
287 const umbrella = await applyLimb(app, alice, fresh(shop), feed.number, request);
288 expect(umbrella.ok ? "applied" : umbrella.error.code).toBe("bad_action");
289 });
290
291 test("handed over: the limb goes to the planner, its own work waits, what other work needs stays, and every surface says so", async () => {
292 expect(ready(shop)).toEqual(
293 [home, lists, shared, loose, older].map((i) => i.number).sort((a, b) => a - b),
294 );
295 const plan = previewLimb(app, alice, fresh(shop), iface.number, { action: "replan" });
296 if (!plan.ok) throw new Error(plan.error.message);
297 // One row: the limb's issue goes to the planner. What it is given, the
298 // limb first; what stays because P0's ship needs it.
299 expect(plan.value.rows).toMatchObject([
300 { label: `alice/shop#${iface.number}`, before: null, after: "atlas", outcome: "change" },
301 ]);
302 expect(plan.value.taken.map((i) => i.number)).toEqual(
303 [iface, home, search, lists].map((i) => i.number),
304 );
305 expect(plan.value.kept.map((i) => i.number)).toEqual([shared.number]);
306 expect(current(iface).assigneeId).toBeNull();
307
308 const op = await applyLimb(app, alice, fresh(shop), iface.number, { action: "replan" });
309 if (!op.ok) throw new Error(op.error.message);
310 handedOp = op.value.id;
311 expect(op.value.rows.map((r) => r.outcome)).toEqual(["ok"]);
312 expect(current(iface).assigneeId).toBe(atlas.id);
313 // Nothing of the limb's own is picked; what other work needs is.
314 expect(ready(shop)).toEqual([shared.number, loose.number, older.number].sort((a, b) => a - b));
315 const graph = repoGraph(app.db, shop.id);
316 const why = `with the planner: #${iface.number} One interface`;
317 for (const held of [iface, home, lists, search]) expect(graph.withPlanner.get(held.id)).toBe(why);
318 expect(graph.withPlanner.has(shared.id)).toBe(false);
319 // The map, its data, the milestone and its data.
320 const map = (await (
321 await call("GET", "/api/v1/repos/alice/shop/map", tokenOf(alice, "ro"))
322 ).json()) as { issues: { number: number; word: string; parkedBecause?: string }[]; ready: { number: number }[] };
323 expect(map.issues.find((i) => i.number === home.number)).toMatchObject({ word: "parked", parkedBecause: why });
324 expect(map.issues.find((i) => i.number === shared.number)).toMatchObject({ word: "ready" });
325 expect(map.ready.map((r) => r.number)).not.toContain(home.number);
326 const mapPage = await (await get("alice", "/alice/shop/map")).text();
327 expect(mapPage).toContain(`<title>#${home.number} One home — parked: ${why}</title>`);
328 const data = (await (
329 await call("GET", `/api/v1/repos/alice/shop/milestones/${iface.number}`, tokenOf(alice, "ro"))
330 ).json()) as { withPlannerSince?: string; leaves: { number: number; state: string }[] };
331 expect(typeof data.withPlannerSince).toBe("string");
332 expect(data.leaves.find((l) => l.number === home.number)!.state).toBe("replanning");
333 const shown = await (await get("alice", page(shop, iface))).text();
334 expect(shown).toContain("With the planner: it re-plans this as fewer, larger pieces");
335 expect(shown).toContain("with the planner");
336 expect(shown).not.toContain("limb?action=replan");
337 });
338
339 test("the planner's grant reaches exactly the limb: split into fresh issues; never drop, never done, never outside it", async () => {
340 const token = tokenOf(atlas, "rw");
341 const patch = async (number: number, body: unknown): Promise<number> =>
342 (await call("PATCH", `/api/v1/repos/alice/shop/issues/${number}`, token, body)).status;
343 const closed = { state: "closed" };
344 // Refused: outside the limb — the shared toolbar, an unrelated issue.
345 const part = issue(shop, "Shared toolbar: one bar", atlas);
346 expect(await patch(shared.number, { ...closed, reason: "split", into: [part.number] })).toBe(403);
347 expect(await patch(loose.number, { ...closed, reason: "split", into: [part.number] })).toBe(403);
348 // Refused: dropping or finishing a person's issue of the limb.
349 expect(await patch(lists.number, { ...closed, reason: "dropped" })).toBe(403);
350 expect(await patch(lists.number, closed)).toBe(403);
351 expect(await patch(lists.number, { ...closed, reason: "done" })).toBe(403);
352 // Refused: a split into anything older than the hand-over, or itself.
353 expect(await patch(lists.number, { ...closed, reason: "split", into: [older.number] })).toBe(403);
354 expect(await patch(lists.number, { ...closed, reason: "split", into: [lists.number] })).toBe(403);
355 for (const untouched of [shared, loose, lists]) expect(current(untouched).state).toBe("open");
356 // Allowed: a person's issue of the limb, split into fewer, larger pieces
357 // the planner opened since the hand-over, linked under the limb as the
358 // brief says.
359 whole = issue(shop, "One home and one list, as one page", atlas);
360 expect(
361 (await call("POST", `/api/v1/repos/alice/shop/issues/${iface.number}/dependencies`, token, { blockedBy: whole.number })).status,
362 ).toBeLessThan(300);
363 expect(await patch(home.number, { ...closed, reason: "split", into: [whole.number] })).toBe(200);
364 expect(await patch(lists.number, { ...closed, reason: "split", into: [whole.number] })).toBe(200);
365 expect(current(home).closeReason).toBe("split");
366 // The milestone shows what changed: what was closed, into what; and the
367 // new piece is the limb's, with the planner, until it answers.
368 const shown = await (await get("alice", page(shop, iface))).text();
369 expect(shown).toContain(`split into #${whole.number}`);
370 const data = (await (
371 await call("GET", `/api/v1/repos/alice/shop/milestones/${iface.number}`, tokenOf(alice, "ro"))
372 ).json()) as { leaves: { number: number; state: string; splitInto?: number[] }[] };
373 expect(data.leaves.find((l) => l.number === home.number)).toMatchObject({ state: "gone", splitInto: [whole.number] });
374 expect(data.leaves.find((l) => l.number === whole.number)!.state).toBe("replanning");
375 });
376
377 test("the planner's run is given the limb: every open issue of its own, with what each waits for", () => {
378 const given = handoverOf(app.db, fresh(shop), current(iface));
379 if (given === undefined) throw new Error("no hand-over");
380 expect(given.number).toBe(iface.number);
381 expect(given.issues.map((i) => [i.number, i.waitsFor])).toEqual([
382 [iface.number, [search.number, (given.issues.find((i) => i.title.startsWith("One home and"))?.number)!].sort((a, b) => a - b)],
383 [search.number, []],
384 [(given.issues.find((i) => i.title.startsWith("One home and"))?.number)!, []],
385 ]);
386 // Not a hand-over: an issue the planner does not hold.
387 expect(handoverOf(app.db, fresh(shop), current(shared))).toBeUndefined();
388 const brief = taskPrompt({
389 agent: getAgentByName(app.db, "atlas")!,
390 repo: fresh(shop),
391 issue: current(iface),
392 branch: "atlas/1-one-interface",
393 forgeUrl: base,
394 isApp: false,
395 resuming: false,
396 role: "planner",
397 reason: "assigned",
398 comments: [],
399 reviews: [],
400 reviewComments: [],
401 since: iface.createdAt,
402 handover: given,
403 });
404 expect(brief).toContain(`A person handed you one limb of the plan, #${iface.number} One interface`);
405 expect(brief).toContain(`- #${search.number} One search`);
406 expect(brief).toContain("Drop nothing");
407 expect(brief).toContain(`"state":"closed","reason":"split"`);
408 });
409
410 test("taken back: undo lets the work go; so does a planning run that ends without an answer", async () => {
411 const undone = await undoFleetOp(app, alice, handedOp);
412 if (!undone.ok) throw new Error(undone.error.message);
413 expect(undone.value.rows.map((r) => r.outcome)).toEqual(["ok"]);
414 expect(current(iface).assigneeId).toBeNull();
415 expect(repoGraph(app.db, shop.id).withPlanner.size).toBe(0);
416 // `One search` waits for a list that was split away: held, as before.
417 // The piece the planner opened is ready.
418 expect(ready(shop)).toContain(whole.number);
419 // Handed over again; the planner's run ends without an answer: the limb
420 // is the person's again — not parked, said on the issue — and its work
421 // goes again.
422 const again = await applyLimb(app, alice, fresh(shop), iface.number, { action: "replan" });
423 expect(again.ok && again.value.rows[0]!.outcome).toBe("ok");
424 expect(ready(shop)).not.toContain(whole.number);
425 expect(unanswered(current(iface), "no changes pushed: DECLINED: the limb is already small")).toBe(false);
426 expect(current(iface).assigneeId).toBeNull();
427 expect(ready(shop)).toContain(whole.number);
428 const said = listComments(app.db, iface.id).at(-1)!.body;
429 expect(said).toStartWith("Back from the planner: its run ended");
430 expect(said).not.toContain("Parked by the crew");
431 });
432 });
test/map.test.ts +1
@@ -70,6 +70,7 @@ function paperGraph(n: number, edges: [number, number][]): Graph {
7070 })),
7171 held: [],
7272 deferred: new Map(),
73 withPlanner: new Map(),
7374 unadopted: new Set(),
7475 structural: new Set(),
7576 };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs