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

Hand a limb to the planner to re-plan as fewer, larger pieces #2561

Closed opened this in answer to
Closed without merging

scout/forge:scout/761-hand-a-limb-to-the-planner-to-re-plan-as → main 6 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +1207 −23
README.md +4 −1
@@ -300,7 +300,10 @@ repository's limbs in the order the crew takes ready work (`enter` opens a
300300 limb's own limbs). A person who administers the repository presses `r` to
301301 Raise or `l` to Lower the limb under the cursor: a preview of the new order
302302 and of the top of the ready list first, then `enter` to apply (`esc` backs
303 out), then `u` to undo the last move. It is the same fleet operation the web
303 out), then `u` to undo the last move. `p` hands the limb to the planner to
304 re-plan as fewer, larger pieces: it lists what the planner will be given, then
305 `enter` confirms; the row reads *with the planner*, and `p` takes it back
306 until the planner starts. It is the same fleet operation the web
304307 milestones page uses, and a move is heard by that page when it is open.
305308 Anyone else sees the order and no keys to change it; a guest sees only what
306309 the web shows them. Whoever may see owner facts also gets two lines under
docs/PLANNING.md +22 −2
@@ -325,13 +325,33 @@ one undo.
325325 the ready order changes. It is one fleet row, the verb `place`; undo puts
326326 the place back. Through the API and the MCP `limb` tool (`action` raise or
327327 lower, `under` when the limb sits in several places), dry-run by default.
328 - **Re-plan** (#761) hands the limb to the planner to come back as fewer,
329 larger pieces. The preview lists every open issue the planner will be
330 given. Pressing it writes the hand-over (`limb_replan`, with the issues
331 it was given) and owes the planner one pass, even with a full map, even
332 after it declined the direction, and without waiting out the hour since
333 its last pass. Its task names the limb and lists the issues. Until the
334 planner has answered — a planning run begun after the hand-over has
335 ended — the limb reads _With the planner_ on its milestone and the crew
336 picks nothing beneath it (the `with_planner` hold). The planner may close
337 an issue beneath it only as `split` into open issues made since the
338 hand-over, as for a twice-parked issue; it may not drop one, and the
339 hand-over grants nothing outside the limb. A person may **take it back**
340 until a planning run has begun. Afterwards the milestone lists which old
341 issue closed into which. Not a fleet operation: it writes no issue row,
342 so there is no receipt to undo; taking it back is the undo.
343 In the terminal, `p` on the limbs screen (Milestones in a repository)
344 previews what the planner is given and hands the limb over on confirm; the
345 row then reads _with the planner_, and `p` takes it back while allowed.
346 Through the API and the MCP `limb` tool as `action` `replan` or
347 `takeback`, dry-run by default (the dry run is the list of issues).
328348
329349 An umbrella or the gate is the plan's own and is not filed. A leaf beneath
330350 a limb that is not deferred cannot be deferred alone: defer the limb. A
331 candidate to trim offers Defer first. Handing one to the planner is #761.
351 candidate to trim offers Defer first.
332352
333353 The same is `POST /api/v1/repos/:owner/:name/milestones/:number/limb`
334 `{ "action": "defer" | "resume" | "close" | "raise" | "lower", "reason"?, "pillar"?, "under"?, "dryRun"? }`
354 `{ "action": "defer" | "resume" | "close" | "raise" | "lower" | "replan" | "takeback", "reason"?, "pillar"?, "under"?, "dryRun"? }`
335355 and the MCP's `limb`, both a dry run unless `dryRun` is false. Applying and
336356 undoing take an admin token of a person who administers the repository; an
337357 agent may look and never apply.
src/actions/issues.ts +12 −2
@@ -55,6 +55,7 @@ import {
5555 unadoptedAmong,
5656 } from "../crew/direct.ts";
5757 import { laterGate } from "../crew/later.ts";
58 import { replanSince } from "../core/limb_replan.ts";
5859 import { handedOver } from "../crew/parks.ts";
5960 import { alreadyDone, CLOSED_NOTE } from "../core/done_on_main.ts";
6061 import { listReviews } from "../core/reviews.ts";
@@ -511,17 +512,26 @@ function handedToPlanner(
511512 // Replacements must be newer than the hand-over when the crew handed the
512513 // issue over, and newer than the issue itself when the planner re-plans it
513514 // on its own pass.
514 const since = handedOver(app.db, repo, issue.id) ?? {
515 const crew = handedOver(app.db, repo, issue.id) ?? {
515516 at: issue.createdAt,
516517 id: issue.id,
517518 };
519 // A limb a person handed over (`core/limb_replan.ts`): newer than that
520 // hand-over, and only as a split — a person's issue beneath it is not dropped.
521 const limbSince = replanSince(app.db, repo, issue);
522 const since =
523 limbSince !== undefined &&
524 (limbSince.at > crew.at || (limbSince.at === crew.at && limbSince.id > crew.id))
525 ? limbSince
526 : crew;
518527 // Done on main: only when commits already name the issue, as the close
519528 // note keeps them.
520529 if (closing.reason === undefined || closing.reason === "done")
521530 return (alreadyDone(app.db, [issue.id]).get(issue.id) ?? []).length > 0;
522531 // Dropped only when no person's ask stands in it — not one the planner
523532 // wrote to replace a person's, however many times it was split since.
524 if (closing.reason === "dropped") return !standsForPerson(app.db, issue);
533 if (closing.reason === "dropped")
534 return limbSince === undefined && !standsForPerson(app.db, issue);
525535 if (closing.reason !== "split") return false;
526536 const into = closing.into ?? [];
527537 if (into.length === 0) return false;
src/actions/limb_replan.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * Hand a limb to the planner (#761): `replan` writes the hand-over, `takeback`
3 * withdraws it before the planner has been given it. Both are a person's
4 * who administers the repository; anyone who can read may see the preview,
5 * which lists every issue the planner will be given. The planner's own
6 * grant to close what is beneath is in `actions/issues.ts`.
7 */
8
9 import type { App } from "../app.ts";
10 import { listCrewRoles } from "../core/agents.ts";
11 import {
12 answeredFor,
13 given,
14 openBeneath,
15 pendingFor,
16 recordReplan,
17 recordTakenBack,
18 splitsOf,
19 type Split,
20 } from "../core/limb_replan.ts";
21 import { canAdmin, canRead, type Repo } from "../core/repos.ts";
22 import type { User } from "../core/users.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import { getIssueById } from "../core/issues.ts";
25 import type { FleetError } from "./fleet.ts";
26 import type { LimbIssue } from "./limbs.ts";
27
28 export const REPLAN_ACTIONS = ["replan", "takeback"] as const;
29 export type ReplanAction = (typeof REPLAN_ACTIONS)[number];
30
31 export const isReplanAction = (value: unknown): value is ReplanAction =>
32 (REPLAN_ACTIONS as readonly unknown[]).includes(value);
33
34 export interface ReplanPreview {
35 readonly limb: LimbIssue;
36 /** Every open issue the planner will be given: the limb's own, the limb first. */
37 readonly issues: readonly LimbIssue[];
38 /** Whether it is with the planner already, and whether it can still be taken back. */
39 readonly withPlanner: boolean;
40 readonly takeBack: boolean;
41 /** Why it cannot be handed over now, when it cannot. */
42 readonly blocked?: string;
43 }
44
45 export interface ReplanDone {
46 readonly done: "replan" | "takeback";
47 readonly limb: LimbIssue;
48 readonly issues: readonly LimbIssue[];
49 }
50
51 const fail = (code: FleetError["code"], message: string) =>
52 err<FleetError>({ code, message });
53
54 const brief = (i: { number: number; title: string }): LimbIssue => ({
55 number: i.number,
56 title: i.title,
57 });
58
59 function find(
60 app: App,
61 actor: User | undefined,
62 repo: Repo,
63 number: number,
64 ): Result<ReplanPreview, FleetError> {
65 if (!actor) return fail("unauthorized", "sign in to hand a limb to the planner");
66 if (!canRead(app.db, repo, actor)) return fail("not_found", "no such milestone here");
67 const issues = openBeneath(app.db, repo, number);
68 const limb = issues.find((i) => i.number === number);
69 if (limb === undefined) return fail("not_found", "no such milestone here");
70 const pending = pendingFor(app.db, repo, limb.id);
71 const blocked =
72 actor.kind === "agent" || !canAdmin(app.db, repo, actor)
73 ? mayAct(app, actor, repo)?.message
74 : pending !== undefined
75 ? "it is with the planner already"
76 : repo.autonomy === "off"
77 ? "the crew is not running here, so there is no planner to ask"
78 : !listCrewRoles(app.db, repo.id).some((c) => c.role === "planner")
79 ? "there is no planner on the crew"
80 : issues.length < 2
81 ? "nothing is beneath it to re-plan"
82 : undefined;
83 return ok({
84 limb: brief(limb),
85 issues: issues.map(brief),
86 withPlanner: pending !== undefined,
87 takeBack: pending !== undefined && !given(app.db, repo, pending.at),
88 ...(blocked === undefined ? {} : { blocked }),
89 });
90 }
91
92 /** The dry run: every issue the planner will be given, and nothing written. */
93 export function previewReplan(
94 app: App,
95 actor: User | undefined,
96 repo: Repo,
97 number: number,
98 ): Result<ReplanPreview, FleetError> {
99 return find(app, actor, repo, number);
100 }
101
102 function mayAct(app: App, actor: User, repo: Repo): FleetError | undefined {
103 if (actor.kind === "agent")
104 return { code: "forbidden", message: "handing a limb to the planner is a person's call" };
105 if (!canAdmin(app.db, repo, actor))
106 return { code: "forbidden", message: "only a person who administers this app hands a limb over" };
107 return undefined;
108 }
109
110 /** Hand the limb over: the planner's next pass is owed it, once. */
111 export function replanLimb(
112 app: App,
113 actor: User | undefined,
114 repo: Repo,
115 number: number,
116 ): Result<ReplanDone, FleetError> {
117 const seen = find(app, actor, repo, number);
118 if (!seen.ok) return seen;
119 const refused = mayAct(app, actor!, repo);
120 if (refused) return err(refused);
121 if (seen.value.blocked !== undefined) return fail("bad_action", seen.value.blocked);
122 const issues = openBeneath(app.db, repo, number);
123 const limb = issues.find((i) => i.number === number)!;
124 recordReplan(app.db, repo, limb, actor!.id, issues);
outdated

High: the web live client never receives this event. src/web/live.ts KINDS lists only limb.moved among the limb events, so an open milestone page misses a hand-over or take-back made in the terminal, API or MCP. Add limb.replan and limb.replan_taken_back to KINDS, and add a test for it.

125 app.bus.append({
126 kind: "limb.replan",
127 repoId: repo.id,
128 actorId: actor!.id,
129 payload: { number, issues: issues.map((i) => i.number) },
130 });
131 return ok({ done: "replan", limb: brief(limb), issues: issues.map(brief) });
132 }
133
134 /** Take it back, before the planner has been given it. */
135 export function takeBackLimb(
136 app: App,
137 actor: User | undefined,
138 repo: Repo,
139 number: number,
140 ): Result<ReplanDone, FleetError> {
141 const seen = find(app, actor, repo, number);
142 if (!seen.ok) return seen;
143 const refused = mayAct(app, actor!, repo);
144 if (refused) return err(refused);
145 const limb = openBeneath(app.db, repo, number).find((i) => i.number === number)!;
146 const pending = pendingFor(app.db, repo, limb.id);
147 if (pending === undefined) return fail("bad_action", "it is not with the planner");
148 if (!seen.value.takeBack)
149 return fail("bad_action", "the planner has it in hand already");
150 recordTakenBack(app.db, pending.id);
151 app.bus.append({
152 kind: "limb.replan_taken_back",
153 repoId: repo.id,
154 actorId: actor!.id,
155 payload: { number },
156 });
157 return ok({ done: "takeback", limb: brief(limb), issues: seen.value.issues });
158 }
159
160 /** What the planner's last answer on this limb changed: each old issue and what replaced it. */
161 export function replanResult(
162 app: App,
163 repo: Repo,
164 limbId: string,
165 ): { readonly at: string; readonly splits: readonly Split[] } | undefined {
166 if (getIssueById(app.db, limbId) === undefined) return undefined;
167 const r = answeredFor(app.db, repo, limbId);
168 return r === undefined ? undefined : { at: r.at, splits: splitsOf(app.db, repo, r) };
169 }
src/core/limb_replan.ts added +238
@@ -0,0 +1,238 @@
1 /**
2 * A limb handed to the planner (#761). A person presses Re-plan on a
3 * milestone: the limb and every open issue beneath it are written down, and
4 * the planner's next pass is owed them, once. The hand-over is pending until
5 * a planning run that was given it has ended, or the person takes it back
6 * before any run starts. While it is pending nothing beneath the limb is
7 * picked by the crew (`crew/held.ts`), and the planner may close what is
8 * beneath it only as split into what it opens after the hand-over
9 * (`actions/issues.ts`). After, the rows say which issue became which.
10 *
11 * Plain reads and writes over two tables; who may is the action's.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import { id } from "../kernel/id.ts";
16 import { transact } from "../kernel/db.ts";
17 import { getIssueById, type Issue } from "./issues.ts";
18 import { readPlan } from "./milestones.ts";
19 import type { Repo } from "./repos.ts";
20
21 export interface Replan {
22 readonly id: string;
23 readonly limbId: string;
24 readonly byUser: string;
25 readonly at: string;
26 readonly takenBackAt: string | null;
27 }
28
29 interface Row {
30 id: string;
31 limb_issue_id: string;
32 by_user: string;
33 at: string;
34 taken_back_at: string | null;
35 }
36
37 const of = (r: Row): Replan => ({
38 id: r.id,
39 limbId: r.limb_issue_id,
40 byUser: r.by_user,
41 at: r.at,
42 takenBackAt: r.taken_back_at,
43 });
44
45 /**
46 * When the last planning run that ended was created: a hand-over made
47 * before it was answered, one made at or after it was not. One read, not
48 * one per hand-over, so a crew tick does not grow with history.
49 */
50 function lastAnswer(db: Database, repo: Repo): string {
51 if (repo.directionIssueId === null) return "";
52 return (
53 db
54 .query<{ at: string | null }, [string]>(
55 `SELECT MAX(created_at) AS at FROM run
56 WHERE issue_id = ?1 AND kind = 'agent' AND state IN ('ok','failed')`,
57 )
58 .get(repo.directionIssueId)?.at ?? ""
59 );
60 }
61
62 /** Whether a planning run was started after `at`: the planner has been given it. */
63 export function given(db: Database, repo: Repo, at: string): boolean {
64 if (repo.directionIssueId === null) return false;
65 return (
66 db
67 .query<{ n: number }, [string, string]>(
68 `SELECT COUNT(*) AS n FROM run
69 WHERE issue_id = ?1 AND kind = 'agent' AND created_at > ?2`,
70 )
71 .get(repo.directionIssueId, at)?.n ?? 0
72 ) > 0;
73 }
74
75 /** The hand-overs the planner has not answered and nobody took back, newest first. */
76 export function pendingReplans(db: Database, repo: Repo): Replan[] {
77 return db
78 .query<Row, [string, string]>(
79 `SELECT * FROM limb_replan
80 WHERE repo_id = ?1 AND taken_back_at IS NULL AND at >= ?2
81 ORDER BY at DESC, id DESC`,
82 )
83 .all(repo.id, lastAnswer(db, repo))
outdated

This loads every hand-over the repository has ever had and runs one answered query per row. It runs on every heldBy (crew tick) and every milestone view, and withPlanner/replanSince then call readPlan once per pending row. Push taken_back_at IS NULL into the SQL, and bound it by the last finished planning run, so it does not grow with history.

84 .map(of);
85 }
86
87 /** The pending hand-over of this limb, if there is one. */
88 export function pendingFor(
89 db: Database,
90 repo: Repo,
91 limbId: string,
92 ): Replan | undefined {
93 return pendingReplans(db, repo).find((r) => r.limbId === limbId);
94 }
95
96 /** The newest hand-over of this limb the planner answered. */
97 export function answeredFor(
98 db: Database,
99 repo: Repo,
100 limbId: string,
101 ): Replan | undefined {
102 const row = db
103 .query<Row, [string, string, string]>(
104 `SELECT * FROM limb_replan
105 WHERE repo_id = ?1 AND limb_issue_id = ?2 AND taken_back_at IS NULL AND at < ?3
106 ORDER BY at DESC, id DESC LIMIT 1`,
107 )
108 .get(repo.id, limbId, lastAnswer(db, repo));
109 return row === null ? undefined : of(row);
110 }
111
112 /** The issues a hand-over was given, as they were then. */
113 export function givenIssueIds(db: Database, replanId: string): string[] {
114 return db
115 .query<{ issue_id: string }, [string]>(
116 `SELECT issue_id FROM limb_replan_issue WHERE replan_id = ?1`,
117 )
118 .all(replanId)
119 .map((r) => r.issue_id);
120 }
121
122 /**
123 * The open issues of a limb now, the limb included, in plan order: what
124 * only it needs, so what something outside also waits for stays out.
125 */
126 export function openBeneath(
127 db: Database,
128 repo: Repo,
129 limbNumber: number,
130 ): Issue[] {
131 return (
132 readPlan(db, repo)
133 .limb(limbNumber)
134 ?.own.filter((i) => i.state === "open" && i.kind === "issue") ?? []
135 );
136 }
137
138 /** Write the hand-over down: the limb, and each issue it was given. */
139 export function recordReplan(
140 db: Database,
141 repo: Repo,
142 limb: Issue,
143 byUser: string,
144 issues: readonly Issue[],
145 ): Replan {
146 const rid = id();
147 transact(db, () => {
148 db.query(
149 `INSERT INTO limb_replan (id, repo_id, limb_issue_id, by_user) VALUES (?1, ?2, ?3, ?4)`,
150 ).run(rid, repo.id, limb.id, byUser);
151 for (const issue of issues)
152 db.query(
153 `INSERT INTO limb_replan_issue (replan_id, issue_id) VALUES (?1, ?2)`,
154 ).run(rid, issue.id);
155 });
156 return of(db.query<Row, [string]>(`SELECT * FROM limb_replan WHERE id = ?1`).get(rid)!);
157 }
158
159 /** Take it back: it is no longer pending. */
160 export function recordTakenBack(db: Database, replanId: string): void {
161 db.query(
162 `UPDATE limb_replan SET taken_back_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
163 WHERE id = ?1 AND taken_back_at IS NULL`,
164 ).run(replanId);
165 }
166
167 /** What a pending hand-over covers now: what it was given, and what is beneath the limb today. */
168 function covered(db: Database, repo: Repo, r: Replan): Set<string> {
169 const ids = new Set(givenIssueIds(db, r.id));
170 const limb = getIssueById(db, r.limbId);
171 if (limb !== undefined)
172 for (const i of openBeneath(db, repo, limb.number)) ids.add(i.id);

Low. openBeneath includes the limb's own issue, so covered (and through it replanSince) also lets the planner close the limb itself as split. The brief tells it to keep the limb and hang the new issues beneath it. Fix: leave r.limbId out of the grant set, as handedLimbs does, while it stays in the hold.

173 return ids;
174 }
175
176 /** Every issue the crew may not pick because its limb is with the planner. */
177 export function withPlanner(db: Database, repo: Repo): Set<string> {
178 const out = new Set<string>();
179 for (const r of pendingReplans(db, repo))
180 for (const i of covered(db, repo, r)) out.add(i);
181 return out;
182 }
183
184 /**
185 * When a limb this issue sits beneath was handed over, while that is
186 * pending: the planner may split the issue only into what is made after.
187 * Nothing for an issue no pending hand-over covers.
188 */
189 export function replanSince(
190 db: Database,
191 repo: Repo,
192 issue: Issue,
193 ): { at: string; id: string } | undefined {
194 let since: { at: string; id: string } | undefined;
195 for (const r of pendingReplans(db, repo)) {
196 if (!covered(db, repo, r).has(issue.id)) continue;
197 if (since === undefined || r.at > since.at) since = { at: r.at, id: r.id };
198 }
199 return since;
200 }
201
202 /** An issue the planner closed as split, and what it became. */
203 export interface Split {
204 readonly number: number;
205 readonly title: string;
206 readonly into: readonly { readonly number: number; readonly title: string }[];
207 }
208
209 /** What a hand-over changed: each issue it was given that closed as split, into which. */
210 export function splitsOf(db: Database, repo: Repo, r: Replan): Split[] {
211 const out: Split[] = [];
outdated

This filter is the only thing that keeps a sealed report's title off a milestone page every reader sees, and no test covers it. Add a reader and guest assertion in test/limb-replan.test.ts that fails if issue.sealed or sealed = 0 is removed.

212 for (const issueId of givenIssueIds(db, r.id)) {
213 const issue = getIssueById(db, issueId);
214 // A sealed issue is never named to a reader.
215 if (issue === undefined || issue.sealed || issue.state !== "closed" || issue.closeReason !== "split")
216 continue;
217 const into = db
218 .query<{ parts: string }, [string, number]>(
219 `SELECT json_extract(payload, '$.into') AS parts FROM event

Medium (performance). This runs once per given issue on every milestone page view of a re-planned limb. It filters issue.closed on kind and does json_extract over the payload, walking event_kind(kind, id) backwards across every repository until it hits a match. On a forge with a long history that is a scan on the common request. Fix: read the split targets from where the close already lands them (the issue's own close record or its dependency rows), or add repo_id to the walk with an index on event(repo_id, kind, id).

220 WHERE repo_id = ?1 AND kind = 'issue.closed'
221 AND json_extract(payload, '$.reason') = 'split'
222 AND json_extract(payload, '$.number') = ?2
223 ORDER BY id DESC LIMIT 1`,
224 )
225 .get(repo.id, issue.number);
226 const numbers: unknown = into === null || into === undefined ? [] : JSON.parse(into.parts);
227 const parts = (Array.isArray(numbers) ? numbers : []).flatMap((n) => {
228 const part = typeof n === "number" ? db
229 .query<{ number: number; title: string }, [string, number]>(
230 `SELECT number, title FROM issue WHERE repo_id = ?1 AND number = ?2 AND sealed = 0`,
231 )
232 .get(repo.id, n) : null;
233 return part === null ? [] : [part];
234 });
235 out.push({ number: issue.number, title: issue.title, into: parts });
236 }
237 return out.sort((a, b) => a.number - b.number);
238 }
src/core/migrations/20261018110000-limb-replan.ts added +18
@@ -0,0 +1,18 @@
1 // A person hands a limb to the planner to re-plan as fewer, larger pieces
2 // (#761): one row for the hand-over, one for each open issue it was given.
3 export default `
4 CREATE TABLE limb_replan (
5 id TEXT PRIMARY KEY,
6 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
7 limb_issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
8 by_user TEXT NOT NULL,
9 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
10 taken_back_at TEXT
11 );
12 CREATE INDEX limb_replan_repo ON limb_replan(repo_id, at);
13 CREATE TABLE limb_replan_issue (
14 replan_id TEXT NOT NULL REFERENCES limb_replan(id) ON DELETE CASCADE,
15 issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
16 PRIMARY KEY (replan_id, issue_id)
17 );
18 `;
src/crew/autonomy.ts +14 −5
@@ -89,6 +89,7 @@ import { reviewSummary } from "../core/reviews.ts";
8989 import { standing } from "../core/standing.ts";
9090 import { pace, type Pace } from "./pacing.ts";
9191 import { BREAKER_NOTE, breakerTripped } from "./breaker.ts";
92 import { pendingReplans } from "../core/limb_replan.ts";
9293 import { handedOverPulls, SKIP_SUMMARY, skipsReplan } from "./guard.ts";
9394 import { atRunCap, type Held, heldBy, heldWords, replannable } from "./held.ts";
9495 import { BY_CREW, DONE_LIKE } from "../core/done_on_main.ts";
@@ -562,7 +563,8 @@ async function planIfThin(
562563 stuck: Held | null = null,
563564 ): Promise<boolean> {
564565 const handed = [...parkedTwice(app.db, [repo]), ...handedOverPulls(app.db, repo)];
565 if (ready >= THIN_MAP && handed.length === 0) return false;
566 const limbs = pendingReplans(app.db, repo);
567 if (ready >= THIN_MAP && handed.length === 0 && limbs.length === 0) return false;
566568 const planner = crew.find((c) => c.role === "planner")?.agent;
567569 if (planner === undefined) return notPlanned(repo, "no planner on the crew");
568570 if (repo.autonomyDirection.trim() === "")
@@ -582,11 +584,14 @@ async function planIfThin(
582584 // The hand-overs the planner has not been given: newer than its last pass.
583585 const seen = lastPlan?.created_at ?? "";
584586 const owed = handed.filter((issue) => issue.at > seen);
585 if (ready >= THIN_MAP && owed.length === 0) return false;
587 // A limb a person handed over is owed one pass, whatever the map and
588 // whatever the planner said of the direction before (#761).
589 const limbsOwed = limbs.filter((r) => r.at > seen);
590 if (ready >= THIN_MAP && owed.length === 0 && limbsOwed.length === 0) return false;
586591 // Nothing startable for issues held since its last pass that re-planning
587592 // lifts: owed one pass like a hand-over, once (#2244).
588593 const unstuck = stuck === null ? [] : replannable(stuck).filter((issue) => heldSince(app, issue, seen));
589 const news = owed.length + unstuck.length;
594 const news = owed.length + unstuck.length + limbsOwed.length;
590595 // The direction is the planner's standing issue, not one issue retried:
591596 // it is held to its own day's share, never the builders' cap (#2143).
592597 if (atRunCap(app, repo, direction))
@@ -606,9 +611,11 @@ async function planIfThin(
606611 return notPlanned(repo, "the planner declined; waiting for a person");
607612 if (lastPlan.state === "queued" || lastPlan.state === "running")
608613 return notPlanned(repo, "a planning run is in flight");
614 // A person's hand-over is not made to wait for the last pass's hour.
609615 if (
616 limbsOwed.length === 0 &&
610617 now.getTime() - new Date(lastPlan.created_at).getTime() <
611 REPLAN_AFTER_MS
618 REPLAN_AFTER_MS
612619 )
613620 return notPlanned(repo, "planned recently");
614621 // Nobody spoke and the map has not moved since the last pass: another
@@ -631,7 +638,9 @@ async function planIfThin(
631638 if (!assigned.ok)
632639 return notPlanned(repo, `could not assign: ${String(assigned.error)}`);
633640 log.info(
634 owed.length > 0
641 limbsOwed.length > 0
642 ? "a limb was handed over; planner asked"
643 : owed.length > 0
635644 ? "parked twice; planner asked"
636645 : unstuck.length > 0
637646 ? "nothing startable; planner asked"
src/crew/brief.ts +31 −1
@@ -186,6 +186,8 @@ export interface TaskInput extends BriefInput {
186186 readonly looks?: readonly string[] | undefined;
187187 /** For a planner: the issues the crew parked twice, with why. */
188188 readonly parkedTwice?: readonly HandedOver[] | undefined;
189 /** For a planner: the limbs a person handed over to re-plan as fewer, larger pieces. */
190 readonly limbs?: readonly HandedLimb[] | undefined;
189191 /** For a planner: the issue deferred work waits behind, if there is one. */
190192 readonly laterGate?: number | undefined;
191193 /** For a planner: nothing ready can start, and what holds it (`held.ts`). */
@@ -204,6 +206,13 @@ export interface Stuck {
204206 }[];
205207 }
206208
209 /** A limb a person handed to the planner, with every open issue beneath it. */
210 export interface HandedLimb {
211 readonly number: number;
212 readonly title: string;
213 readonly issues: readonly { readonly number: number; readonly title: string }[];
214 }
215
207216 /** An issue the crew parked twice, as the planner is told of it. */
208217 export interface HandedOver {
209218 readonly number: number;
@@ -234,7 +243,7 @@ function taskBody(input: TaskInput): string {
234243 const { issue } = input;
235244 const out: string[] = [];
236245 const isAgent = (name: string): boolean => name === input.agent.user.username;
237 const handed = [parkedTwiceLines(input), stuckLines(input)]
246 const handed = [parkedTwiceLines(input), limbLines(input), stuckLines(input)]
238247 .filter((lines) => lines.length > 0)
239248 .flatMap((lines, n) => (n === 0 ? lines : ["", ...lines]));
240249 const readers = input.readers ?? new Set<string>();
@@ -533,6 +542,27 @@ function parkedTwiceLines(input: TaskInput): string[] {
533542 ];
534543 }
535544
545 /**
546 * What a planner is told of a limb a person handed it: the limb and every
547 * open issue beneath it, to come back as fewer, larger issues. Each old
548 * issue is closed as split into the new ones, never dropped — the person
549 * asked for them. Nothing outside the limb is touched.
550 */
551 function limbLines(input: TaskInput): string[] {
552 const limbs = input.role === "planner" ? (input.limbs ?? []) : [];
553 if (limbs.length === 0) return [];
554 const issues = `$FORGE_URL/api/v1/repos/${input.repo.ownerName}/${input.repo.name}/issues`;
555 return [
556 "A person handed you these limbs to re-plan as fewer, larger pieces. Nothing beneath one is picked by the crew until you have answered:",
557 ...limbs.flatMap((limb) => [
558 `- Limb #${limb.number} ${limb.title}, ${limb.issues.length} open issue${limb.issues.length === 1 ? "" : "s"}:`,
559 ...limb.issues.map((i) => ` #${i.number} ${i.title}`),
560 ]),
561 `Open the larger issues first, each saying what done looks like. Then close every old issue of the limb 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 nothing outside the limb is yours to close this way. Do not drop an issue of the limb: a person asked for it, so what it asked for must be in a larger piece.`,
562 `If other issues wait for one you close, make them wait for what replaces it: DELETE ${issues}/D/dependencies/N, then POST ${issues}/D/dependencies with {"blockedBy":M}. Make the new issues wait for the limb's issue, so they stay beneath it.`,
563 ];
564 }
565
536566 /**
537567 * What a planner is told when no ready issue can start while builders sit
538568 * free: the count per filter, and each stalled or capped issue, to re-plan
src/crew/handed_limbs.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * The limbs a person handed to the planner (#761), as its task is told of
3 * them: each with every open issue beneath it. Only those it has not yet
4 * answered (`core/limb_replan.ts`).
5 */
6
7 import type { App } from "../app.ts";
8 import { getIssueById } from "../core/issues.ts";
9 import { openBeneath, pendingReplans } from "../core/limb_replan.ts";
10 import type { Repo } from "../core/repos.ts";
11 import type { HandedLimb } from "./brief.ts";
12
13 export function handedLimbs(app: App, repo: Repo): HandedLimb[] {
14 return pendingReplans(app.db, repo).flatMap((r) => {
15 const limb = getIssueById(app.db, r.limbId);
16 if (limb === undefined) return [];
17 const beneath = openBeneath(app.db, repo, limb.number).filter((i) => i.id !== limb.id);
18 return beneath.length === 0
19 ? []
20 : [{ number: limb.number, title: limb.title, issues: beneath.map((i) => ({ number: i.number, title: i.title })) }];
21 });
22 }
src/crew/held.ts +6
@@ -9,6 +9,8 @@
99 * - `running`: a run is in flight on it.
1010 * - `open_pull`: an open pull already proposes it (`direct.ts`).
1111 * - `planner`: the planner or a reviewer holds it, not a builder.
12 * - `with_planner`: its limb was handed to the planner by a person and the
13 * planner has not answered (`core/limb_replan.ts`).
1214 * - `done_on_main`: the crew found it done on the base branch and waits for
1315 * a person to close it (`done_on_main.ts`); nothing is left to plan.
1416 * - `stalled`: a builder ran on it and left without a pull, and nobody
@@ -27,6 +29,7 @@ import { listCrewRoles, type Agent, type CrewRole } from "../core/agents.ts";
2729 import { readyNow, repoGraph, type Ranked } from "../core/dependencies.ts";
2830 import { alreadyDone, BY_CREW, DONE_LIKE } from "../core/done_on_main.ts";
2931 import type { Issue } from "../core/issues.ts";
32 import { withPlanner } from "../core/limb_replan.ts";
3033 import type { Repo } from "../core/repos.ts";
3134 import { listActive, type Run } from "../core/runs.ts";
3235 import { getUserById } from "../core/users.ts";
@@ -42,6 +45,7 @@ export const HOLDS = [
4245 "running",
4346 "open_pull",
4447 "planner",
48 "with_planner",
4549 "done_on_main",
4650 "stalled",
4751 "run_cap",
@@ -115,10 +119,12 @@ export function heldBy(
115119 const planners = new Set(
116120 crew.filter((c) => c.role !== "builder").map((c) => c.agent.user.id),
117121 );
122 const handed = withPlanner(app.db, repo);
118123 const holdOf = (issue: Issue): HoldName | null => {
119124 if (busyIssues.has(issue.id)) return "running";
120125 if (proposed.has(issue.number)) return "open_pull";
121126 if (issue.assigneeId !== null && planners.has(issue.assigneeId)) return "planner";
127 if (handed.has(issue.id)) return "with_planner";
122128 if (alreadyDone(app.db, [issue.id]).has(issue.id)) return "done_on_main";
123129 if (stalled(app, repo, issue)) return "stalled";
124130 if (atRunCap(app, repo, issue)) return "run_cap";
src/crew/runner.ts +2
@@ -108,6 +108,7 @@ import {
108108 import { clearStaleLocks, lockedOut } from "./locks.ts";
109109 import { interruptedSummary } from "./interrupted.ts";
110110 import { laterGate } from "./later.ts";
111 import { handedLimbs } from "./handed_limbs.ts";
111112 import { parkedTwice } from "./parks.ts";
112113 import { heldNow, stuckOf } from "./held.ts";
113114 import { noteLimit } from "../core/standing.ts";
@@ -974,6 +975,7 @@ async function work(
974975 ...(brief.role === "planner" && issue.id === repo.directionIssueId
975976 ? {
976977 parkedTwice: [...parkedTwice(app.db, [repo]), ...handedOverPulls(app.db, repo)],
978 limbs: handedLimbs(app, repo),
977979 laterGate: laterGate(app.db, repo.id),
978980 stuck: stuckOf(heldNow(app, repo)),
979981 }
src/http/api.ts +18 −1
@@ -313,6 +313,12 @@ import {
313313 milestonesJson,
314314 } from "../web/pages/milestones.ts";
315315 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
316 import {
317 isReplanAction,
318 previewReplan,
319 replanLimb,
320 takeBackLimb,
321 } from "../actions/limb_replan.ts";
316322 import { appsRuntime, envsFor, type AppsRuntime } from "../apps/runtime.ts";
317323 import { isEnvName } from "../apps/data.ts";
318324 import { getAppByRepo } from "../core/apps.ts";
@@ -3157,8 +3163,19 @@ export function apiRoutes(router: Router<Handler>): void {
31573163 const repo = loadRepo(ctx);
31583164 const number = positiveInt(ctx.params.number);
31593165 if (!repo || number === undefined) return notFound();
3166 if (isReplanAction(input.action)) {
3167 if (dryRun) {
3168 const plan = previewReplan(ctx.app, ctx.auth.user, repo, number);
3169 return plan.ok ? json({ dryRun: true, ...plan.value }) : respondFleet(plan.error);
3170 }
3171 const done =
3172 input.action === "replan"
3173 ? replanLimb(ctx.app, ctx.auth.user, repo, number)
3174 : takeBackLimb(ctx.app, ctx.auth.user, repo, number);
3175 return done.ok ? json({ dryRun: false, ...done.value }, 201) : respondFleet(done.error);
3176 }
31603177 if (!isLimbAction(input.action))
3161 return apiError("bad_action", 422, "action is defer, resume, close, raise or lower");
3178 return apiError("bad_action", 422, "action is defer, resume, close, raise, lower, replan or takeback");
31623179 const request = {
31633180 action: input.action,
31643181 ...(typeof input.reason === "string" ? { reason: input.reason } : {}),
src/http/mcp.ts +25 −3
@@ -132,6 +132,12 @@ import { setArchived, setCrewOutsiders, setDecisionsBy } from "../actions/repos.
132132 import { mapJson, marksFor } from "../web/pages/map.ts";
133133 import { applyFleetIds, previewFleetIds, undoFleetOp } from "../actions/fleet.ts";
134134 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
135 import {
136 isReplanAction,
137 previewReplan,
138 replanLimb,
139 takeBackLimb,
140 } from "../actions/limb_replan.ts";
135141 import {
136142 milestoneData,
137143 milestonesJson,
@@ -2076,7 +2082,7 @@ const TOOLS: readonly Tool[] = [
20762082 {
20772083 name: "limb",
20782084 description:
2079 "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; `raise` and `lower` move it one place among its siblings — `under` says whose limbs when it is a limb of several, or `top` — and the crew takes ready work from the higher limb first; the dry run answers with the new `order` and the top of the ready list `before` and `after`. `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.",
2085 "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; `raise` and `lower` move it one place among its siblings — `under` says whose limbs when it is a limb of several, or `top` — and the crew takes ready work from the higher limb first; the dry run answers with the new `order` and the top of the ready list `before` and `after`. `replan` hands the limb to the planner to re-plan as fewer, larger pieces: the dry run lists every open issue it will be given, applying owes the planner's next pass once and holds the limb from the crew until it answers, and `takeback` withdraws it before the planner starts. `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.",
20802086 inputSchema: {
20812087 type: "object",
20822088 properties: {
@@ -2086,7 +2092,7 @@ const TOOLS: readonly Tool[] = [
20862092 minimum: 1,
20872093 description: "The limb: the number of its issue.",
20882094 },
2089 action: { type: "string", enum: ["defer", "resume", "close", "raise", "lower", "undo"] },
2095 action: { type: "string", enum: ["defer", "resume", "close", "raise", "lower", "replan", "takeback", "undo"] },
20902096 reason: {
20912097 type: "string",
20922098 description: "For close: why it is not being done, in one sentence.",
@@ -2129,13 +2135,29 @@ const TOOLS: readonly Tool[] = [
21292135 return undone.ok ? good(undone.value) : refused(undone.error);
21302136 }
21312137 const number = args["issue"];
2138 if (
2139 isReplanAction(args["action"]) &&
2140 typeof number === "number" &&
2141 Number.isInteger(number) &&
2142 number > 0
2143 ) {
2144 if (dry) {
2145 const plan = previewReplan(ctx.app, user, repo, number);
2146 return plan.ok ? good({ dryRun: true, ...plan.value }) : refused(plan.error);
2147 }
2148 const done =
2149 args["action"] === "replan"
2150 ? replanLimb(ctx.app, user, repo, number)
2151 : takeBackLimb(ctx.app, user, repo, number);
2152 return done.ok ? good({ dryRun: false, ...done.value }) : refused(done.error);
2153 }
21322154 if (
21332155 !isLimbAction(args["action"]) ||
21342156 typeof number !== "number" ||
21352157 !Number.isInteger(number) ||
21362158 number < 1
21372159 )
2138 return bad("invalid", "give the limb's issue number and an action: defer, resume, close, raise, lower or undo");
2160 return bad("invalid", "give the limb's issue number and an action: defer, resume, close, raise, lower, replan, takeback or undo");
21392161 const request = {
21402162 action: args["action"],
21412163 ...(typeof args["reason"] === "string" ? { reason: args["reason"] } : {}),
src/tui/screens/limbs.ts +65 −2
@@ -12,6 +12,11 @@
1212 * facts (`canSeeOwnerFacts`, as on the page) also gets, under the list, what
1313 * the limb under the cursor cost and landed, and its costliest issues.
1414 *
15 * `p` hands the limb under the cursor to the planner to re-plan as fewer,
16 * larger pieces (#761): `previewReplan` lists what it will be given, then
17 * `replanLimb` on confirm. The row reads "with the planner" until it
18 * answers, and `p` then takes it back while that is still allowed.
19 *
1520 * `enter` on a limb that has limbs of its own opens them, so a milestone's
1621 * sub-limbs can be moved among themselves (the `under` of the action).
1722 * Subscribed to the bus while on the stack, so a move made on the web, or in
@@ -19,6 +24,8 @@
1924 */
2025
2126 import { undoFleetOp } from "../../actions/fleet.ts";
27 import { previewReplan, replanLimb, takeBackLimb } from "../../actions/limb_replan.ts";
28 import { pendingReplans } from "../../core/limb_replan.ts";
2229 import { applyLimb, previewLimb, type LimbPreview } from "../../actions/limbs.ts";
2330 import { canAdmin, canRead, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2431 import { readPlan, type Limb, type Milestone } from "../../core/milestones.ts";
@@ -40,7 +47,7 @@ import {
4047 } from "./common.ts";
4148
4249 /** What reorders or reshapes the limbs: a move, or an issue opening or closing. */
43 const LIVE_KINDS = ["limb.moved", "issue.opened", "issue.closed", "issue.reopened"];
50 const LIVE_KINDS = ["limb.moved", "limb.replan", "limb.replan_taken_back", "issue.opened", "issue.closed", "issue.reopened"];
4451
4552 /** How many lines of the new order and of the ready list a preview shows. */
4653 const SHOWN = 6;
@@ -104,6 +111,8 @@ export function limbsScreen(
104111 let spends = new Map<number, NonNullable<Milestone["spend"]>>();
105112 /** The receipt of the last move made here, which `u` reverses once. */
106113 let last: string | undefined;
114 /** The limbs with the planner, by issue id (#761). */
115 let withPlanner = new Set<string>();
107116 // Read at use, not at open: a repository's admin can change under a session.
108117 const may = (): boolean =>
109118 f.user !== undefined && f.user.kind === "user" && canAdmin(f.db, repo, f.user);
@@ -117,6 +126,7 @@ export function limbsScreen(
117126 return;
118127 }
119128 limbs = limbsOf(f, repo, group) ?? [];
129 withPlanner = new Set(pendingReplans(f.db, repo).map((r) => r.limbId));
120130 spends = new Map();
121131 if (canSeeOwnerFacts(f.db, repo, f.user)) {
122132 const plan = readPlan(f.db, repo, { spend: true });
@@ -175,6 +185,57 @@ export function limbsScreen(
175185 );
176186 };
177187
188 /** Re-plan: hand the limb to the planner after reading what it is given; or take it back. */
189 const replan = (): void => {
190 const limb = current();
191 if (limb === undefined || !may()) return;
192 const number = limb.issue.number;
193 const seen = previewReplan(f.app, f.user, repo, number);
194 if (!seen.ok) {
195 ctx.toast(seen.error.message, "danger");
196 return;
197 }
198 const p = seen.value;
199 if (p.withPlanner && !p.takeBack) {
200 ctx.toast("the planner has it in hand already", "danger");
201 return;
202 }
203 if (!p.withPlanner && p.blocked !== undefined) {
204 ctx.toast(p.blocked, "danger");
205 return;
206 }
207 const taking = p.withPlanner;
208 const body = [
209 taking
210 ? "It is with the planner; nothing beneath it is picked. Take it back before the planner starts:"
211 : `The planner will be given ${plural(p.issues.length, "issue")}, to close as split into fewer, larger ones:`,
212 ...p.issues.slice(0, SHOWN).map((i) => ` ${line(i.number, i.title)}`),
213 ...(p.issues.length > SHOWN ? [` … ${p.issues.length - SHOWN} more`] : []),
214 ];
215 ctx.push(
216 confirmScreen(ctx, screen, {
217 title: `${taking ? "Take back" : "Re-plan"} “${limb.name}”?`,
218 body,
219 actions: [
220 { label: taking ? "Take it back" : "Hand to the planner", variant: "default" },
221 { label: "Cancel", variant: "ghost" },
222 ],
223 onChoose: (choice) => {
224 if (choice !== 0) return;
225 const done = taking
226 ? takeBackLimb(f.app, f.user, repo, number)
227 : replanLimb(f.app, f.user, repo, number);
228 if (!done.ok) {
229 ctx.toast(done.error.message, "danger");
230 return;
231 }
232 reload(number);
233 ctx.toast(taking ? "taken back" : "with the planner", "success");
234 },
235 }),
236 );
237 };
238
178239 const undo = (): void => {
179240 const id = last;
180241 if (id === undefined || !may()) return;
@@ -202,7 +263,7 @@ export function limbsScreen(
202263 const rows = (): ListRow[] =>
203264 limbs.map((l, n) => ({
204265 title: `${n + 1}. ${line(l.issue.number, l.name)}`,
205 secondary: l.deferred ? "deferred" : "",
266 secondary: withPlanner.has(l.issue.id) ? "with the planner" : l.deferred ? "deferred" : "",
206267 meta: `${l.weight.done}/${l.weight.total} done`,
207268 }));
208269
@@ -215,6 +276,7 @@ export function limbsScreen(
215276 binding(["enter"], "open"),
216277 binding(["r"], "raise", { disabled: !moves }),
217278 binding(["l"], "lower", { disabled: !moves }),
279 binding(["p"], withPlanner.has(current()?.issue.id ?? "") ? "take back" : "re-plan", { disabled: !may() || current() === undefined }),
218280 binding(["u"], "undo", { disabled: !may() || last === undefined }),
219281 ];
220282 },
@@ -246,6 +308,7 @@ export function limbsScreen(
246308 if (e.key === "enter") open();
247309 else if (e.key === "r") move("raise");
248310 else if (e.key === "l") move("lower");
311 else if (e.key === "p") replan();
249312 else if (e.key === "u") undo();
250313 else return false;
251314 return true;
src/web/live.ts +1 −1
@@ -302,7 +302,7 @@ export const liveClientJs = /* js */ `
302302 'label.created', 'label.updated', 'label.deleted',
303303 'run.queued', 'run.started', 'run.finished', 'app.serving',
304304 'app.created', 'app.updated', 'app.deleted', 'app.stopped',
305 'limb.moved', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
305 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
306306 ];
307307 var extra = (cfg.getAttribute('data-repos') || '').split(' ').filter(Boolean);
308308 var watching = [repo].concat(extra).filter(function (r, i, all) {
src/web/pages/limb.ts +4
@@ -6,6 +6,7 @@
66 * take it back once.
77 */
88
9 import { isReplanAction } from "../../actions/limb_replan.ts";
910 import { getFleetOp, undoFleetOp } from "../../actions/fleet.ts";
1011 import {
1112 applyLimb,
@@ -32,6 +33,7 @@ import { field, readForm } from "../form.ts";
3233 import { html, when, type Html } from "../html.ts";
3334 import { page, redirect } from "../layout.ts";
3435 import { btn } from "../ui.ts";
36 import { replanPreviewPage, replanSubmit } from "./limb_replan.ts";
3537 import { milestoneHref, milestonesCss } from "./milestones.ts";
3638
3739 const WORDS: Record<LimbAction, { ask: string; does: string; go: string }> = {
@@ -166,6 +168,7 @@ export function limbPreviewPage(ctx: Ctx): Response {
166168 if (!ctx.auth.user) return signInFirst(ctx);
167169 const number = Number(ctx.params.number);
168170 const action = ctx.url.searchParams.get("action");
171 if (action === "replan") return replanPreviewPage(ctx, repo, number);
169172 if (!Number.isInteger(number) || !isLimbAction(action))
170173 return notFoundPage(ctx);
171174 const request = requestOf(action, (n) => ctx.url.searchParams.get(n) ?? "");
@@ -350,6 +353,7 @@ export async function limbSubmit(ctx: Ctx): Promise<Response> {
350353 if (form instanceof Response) return form;
351354 const number = Number(ctx.params.number);
352355 const action = field(form, "action");
356 if (isReplanAction(action)) return replanSubmit(ctx, repo, number, action);
353357 if (!Number.isInteger(number) || !isLimbAction(action))
354358 return notFoundPage(ctx);
355359 const base = repoBase(repo);
src/web/pages/limb_replan.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Handing a limb to the planner from its milestone (#761): the preview that
3 * lists every issue the planner will be given, the confirm, and taking it
4 * back. Over `actions/limb_replan.ts`; the same pattern as `limb.ts`.
5 */
6
7 import {
8 previewReplan,
9 replanLimb,
10 takeBackLimb,
11 type ReplanAction,
12 } from "../../actions/limb_replan.ts";
13 import type { Repo } from "../../core/repos.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import {
16 crumbsFor,
17 notFoundPage,
18 repoBase,
19 repoHeader,
20 repoPalette,
21 } from "../chrome.ts";
22 import { html } from "../html.ts";
23 import { page, redirect } from "../layout.ts";
24 import { btn } from "../ui.ts";
25 import { milestoneHref, milestonesCss } from "./milestones.ts";
26
27 /** GET /:owner/:name/milestones/:number/limb?action=replan — what the planner will be given. */
28 export function replanPreviewPage(ctx: Ctx, repo: Repo, number: number): Response {
29 const plan = previewReplan(ctx.app, ctx.auth.user, repo, number);
30 if (!plan.ok) return notFoundPage(ctx);
31 const base = repoBase(repo);
32 const p = plan.value;
33 const back = milestoneHref(base, number);
34 return page({
35 ctx,
36 title: `Re-plan ${p.limb.title} · ${repo.name}`,
37 crumbs: crumbsFor(repo),
38 palette: repoPalette(ctx, repo),
39 styleCss: milestonesCss,
40 body: html`${repoHeader(ctx, repo, "map")}
41 <div class="ms-top mt">
42 <p class="small muted"><a href="${back}">${p.limb.title}</a></p>
43 <h1>Re-plan “${p.limb.title}”?</h1>
44 <p>
45 The planner's next pass is given this limb to re-plan as fewer,
46 larger pieces. Each issue below is closed as split into what
47 replaces it; none is dropped. The crew picks nothing beneath the
48 limb until the planner has answered, and you can take it back
49 before it starts.
50 </p>
51 </div>
52 <section class="ms-section" id="replan-issues">
53 <h2>${p.issues.length} ${p.issues.length === 1 ? "issue" : "issues"} the planner will be given</h2>
54 <ul class="ms-rows">
55 ${p.issues.map(
56 (i) =>
57 html`<li>
58 <a href="${base}/issues/${i.number}">${i.title}</a>
59 <span class="muted small">#${i.number}</span>
60 </li>`,
61 )}
62 </ul>
63 </section>
64 ${p.blocked !== undefined
65 ? html`<p class="mt" id="replan-refused">
66 Not now: ${p.blocked}. <a href="${back}">Back</a>
67 </p>`
68 : html`<form method="post" action="${back}/limb" class="bar mt">
69 <input type="hidden" name="action" value="replan" />
70 ${btn("Hand to the planner", { variant: "primary" })}

A reader who is not an admin gets this primary button and then a 409. When the viewer cannot administer the repository, show the refusal here as blocked does. Also, line 53 reads "1 issues": use plural.

71 ${btn("Back", { href: back, variant: "ghost" })}
72 </form>`}`,
73 });
74 }
75
76 /** POST /:owner/:name/milestones/:number/limb with action replan or takeback, its form already read. */
77 export function replanSubmit(
78 ctx: Ctx,
79 repo: Repo,
80 number: number,
81 action: ReplanAction,
82 ): Response {
83 if (!Number.isInteger(number)) return notFoundPage(ctx);
84 const done =
85 action === "replan"
86 ? replanLimb(ctx.app, ctx.auth.user, repo, number)
87 : takeBackLimb(ctx.app, ctx.auth.user, repo, number);
88 if (!done.ok && done.error.code === "not_found") return notFoundPage(ctx);

Every error except not_found lands on the milestone in silence: forbidden, 'it is with the planner already', 'the planner has it in hand already'. Show the refusal's message so the person knows the press did nothing.

89 const back = milestoneHref(repoBase(repo), number);
90 if (done.ok) return redirect(back);
91 // Said, not hidden: the press did nothing, and why.
92 return page({
93 ctx,
94 title: `Not done · ${repo.name}`,
95 crumbs: crumbsFor(repo),
96 palette: repoPalette(ctx, repo),
97 styleCss: milestonesCss,
98 body: html`${repoHeader(ctx, repo, "map")}
99 <div class="ms-top mt">
100 <h1>${action === "replan" ? "Not handed over" : "Not taken back"}</h1>
101 <p id="replan-refused">Nothing changed: ${done.error.message}.</p>
102 <p><a href="${back}">Back</a></p>
103 </div>`,
104 }, 409);
105 }
src/web/pages/milestones.ts +65 −4
@@ -34,6 +34,8 @@ import {
3434 import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
3535 import { isWatching } from "../../core/watches.ts";
3636 import { watchMilestone } from "../../actions/watches.ts";
37 import { replanResult } from "../../actions/limb_replan.ts";
38 import { given, pendingFor } from "../../core/limb_replan.ts";
3739 import type { Ctx } from "../../http/context.ts";
3840 import { askToLiveFor } from "../ask_to_live.ts";
3941 import {
@@ -59,7 +61,7 @@ export const milestoneHref = (base: string, number: number): string =>
5961 export const limbHref = (
6062 base: string,
6163 number: number,
62 action: LimbAction,
64 action: LimbAction | "replan",
6365 under?: string,
6466 ): string =>
6567 `${milestoneHref(base, number)}/limb?action=${action}${under === undefined ? "" : `&under=${under}`}`;
@@ -120,11 +122,13 @@ function limbActions(
120122 furniture: boolean,
121123 lead: Html | null,
122124 move: Html | null,
125 replan: Html | null,
123126 ): Html {
124127 const number = m.issue.number;
125128 return html`<p class="bar ms-actions" id="limb-actions">
126129 ${lead}
127130 ${move}
131 ${replan}
128132 ${furniture
129133 ? null
130134 : m.deferred
@@ -242,6 +246,58 @@ function folded(rows: Html[], what: string, shown: number): Html {
242246 </details>`;
243247 }
244248
249 /**
250 * Where a limb stands with the planner (#761): "with the planner" while it
251 * waits, with a way to take it back until the planner has been given it;
252 * otherwise Re-plan, for whoever administers the repository.
253 */
254 function replanControl(
255 ctx: Ctx,
256 repo: Repo,
257 m: Milestone,
258 admin: boolean,
259 ): Html | null {
260 const base = repoBase(repo);
261 const pending = pendingFor(ctx.app.db, repo, m.issue.id);
262 if (pending === undefined)
263 return admin && m.weight.open > 1
264 ? btn("Re-plan", {
265 href: limbHref(base, m.issue.number, "replan"),
266 size: "sm",
267 title: "Hand this limb to the planner to re-plan as fewer, larger pieces",
268 })
269 : null;
270 return html`<span class="ms-planner" id="ms-with-planner"
271 ><b>With the planner</b>
272 <span class="muted small">Nothing beneath it is picked until it answers.</span></span
273 >${admin && !given(ctx.app.db, repo, pending.at)
274 ? html`<form method="post" action="${milestoneHref(base, m.issue.number)}/limb">
275 <input type="hidden" name="action" value="takeback" />
276 ${btn("Take it back", { size: "sm", variant: "ghost" })}
277 </form>`
278 : null}`;
279 }
280
281 /** What the planner changed on this limb, once it has answered: each old issue and what replaced it. */
282 function replanChanged(ctx: Ctx, repo: Repo, m: Milestone): Html | null {
283 const base = repoBase(repo);
284 const result = replanResult(ctx.app, repo, m.issue.id);
285 if (result === undefined || result.splits.length === 0) return null;
286 const link = (n: { number: number; title: string }): Html =>
287 html`<a href="${base}/issues/${n.number}">${n.title}</a>
288 <span class="muted small">#${n.number}</span>`;
289 return html`<section class="ms-section" id="ms-replanned">
290 <h2>Re-planned ${time(result.at)}</h2>
291 <ul class="ms-rows">
292 ${result.splits.map(
293 (s) =>
294 html`<li>${link(s)} <span class="muted small">closed as split into</span>
295 ${s.into.map((p, n) => html`${n === 0 ? "" : ", "}${link(p)}`)}</li>`,
296 )}
297 </ul>
298 </section>`;
299 }
300
245301 /**
246302 * Watch, or stop: one button, for a person who is signed in. Watching puts
247303 * the milestone's progress in their feed and tells their phone once, when
@@ -490,17 +546,20 @@ export function milestonePage(ctx: Ctx): Response {
490546 const move = moverFor(ctx.app.db, repo, viewer, plan.read);
491547 // Its own place: among the limbs of whichever milestone holds it first.
492548 const seat = move?.homeOf(milestone.issue);
493 const actions = canAdmin(ctx.app.db, repo, ctx.auth.user)
549 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
550 const replan = replanControl(ctx, repo, milestone, admin);
551 const actions = admin
494552 ? limbActions(
495553 repoBase(repo),
496554 milestone,
497555 isStructural(pillarsOf(ctx.app.db, repo), milestone.issue.id),
498556 watch,
499557 seat === undefined ? null : (move?.(milestone.issue, seat) ?? null),
558 replan,
500559 )
501 : watch === null
560 : watch === null && replan === null
502561 ? null
503 : html`<p class="bar ms-actions">${watch}</p>`;
562 : html`<p class="bar ms-actions">${watch}${replan}</p>`;
504563 return page({
505564 ctx,
506565 title: `${milestone.name} · ${repo.name}`,
@@ -508,6 +567,7 @@ export function milestonePage(ctx: Ctx): Response {
508567 palette: repoPalette(ctx, repo),
509568 body: html`${repoHeader(ctx, repo, "map")}
510569 ${milestoneBody(repo, milestone, owner, actions, move)}
570 ${replanChanged(ctx, repo, milestone)}
511571 ${liveMount({ repo: repoBase(repo) })}`,
512572 styleCss: milestonesCss,
513573 scriptJs: liveClientJs,
@@ -621,6 +681,7 @@ export const milestonesCss = /* css */ `
621681 .ms-top h1, .ms-top p { margin: 0; }
622682 .ms-head { display: grid; grid-template-columns: minmax(0, 1fr); gap: 4px; }
623683 .ms-actions { margin-top: 4px; }
684 .ms-planner { display: inline-flex; flex-wrap: wrap; gap: 4px 8px; align-items: baseline; }
624685 .ms-move { grid-column: 1 / -1; display: flex; gap: 14px; }
625686 .ms-section { margin-top: 22px; }
626687 .ms-section h2 { font-size: 13px; margin: 0 0 6px; }
test/limb-replan.test.ts added +333
@@ -0,0 +1,333 @@
1 /**
2 * A limb handed to the planner (#761). The refusals come first: a reader, a
3 * crew agent and an `ro` token cannot hand a limb over, and the hand-over
4 * grants the planner nothing outside the limb. Then the hand-over itself:
5 * owed once, even with a full map and after a decline; the brief lists the
6 * limb; nothing beneath is picked until the planner answers; the planner
7 * closes only as split into what is new; a person takes it back before it
8 * runs; the milestone shows the change.
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { addToCrew, createAgent } from "../src/actions/crew.ts";
16 import { linkIssue } from "../src/actions/dependencies.ts";
17 import { openIssue, setIssueState } from "../src/actions/issues.ts";
18 import { previewReplan, replanLimb, takeBackLimb } from "../src/actions/limb_replan.ts";
19 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
20 import { setCrewRole } from "../src/core/agents.ts";
21 import { readyNow, repoGraph } from "../src/core/dependencies.ts";
22 import { getIssueById, type Issue } from "../src/core/issues.ts";
23 import { setSealed } from "../src/core/sealed.ts";
24 import { pendingReplans, replanSince } from "../src/core/limb_replan.ts";
25 import { getRepoById, type Repo } from "../src/core/repos.ts";
26 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
27 import { createToken } from "../src/core/tokens.ts";
28 import { createUser, getUserByName, type User } from "../src/core/users.ts";
29 import { taskPrompt } from "../src/crew/brief.ts";
30 import { driveRepo, ensureDirectionIssue } from "../src/crew/autonomy.ts";
31 import { heldNow } from "../src/crew/held.ts";
32 import { handedLimbs } from "../src/crew/handed_limbs.ts";
33 import { serve, type Servers } from "../src/http/server.ts";
34
35 describe("a limb handed to the planner", () => {
36 let dataDir: string;
37 let app: App;
38 let servers: Servers;
39 let base: string;
40 let alice: User;
41 let bob: User;
42 let mason: User;
43 let atlas: User;
44 let repo: Repo;
45 let limb: Issue;
46 let leaves: Issue[];
47 let outside: Issue;
48 let direction: Issue;
49 const cookies: Record<string, string> = {};
50
51 const fresh = () => getRepoById(app.db, repo.id)!;
52 const current = (i: Issue) => getIssueById(app.db, i.id)!;
53 const open = (title: string, by: User = alice): Issue => {
54 const made = openIssue(app, by, fresh(), { title });
55 if (!made.ok) throw new Error(String(made.error));
56 return made.value;
57 };
58 const tick = () => Bun.sleep(5);
59 /** A planning pass on the direction: queued, claimed, ended. */
60 const planned = (state: "ok" | "failed", summary: string) => {
61 const run = createRun(app.db, {
62 repoId: repo.id,
63 kind: "agent",
64 issueId: direction.id,
65 actorId: atlas.id,
66 reason: "assigned",
67 });
68 claimRun(app.db, run.id);
69 finishRun(app.db, run.id, { state, summary });
70 return run;
71 };
72 const tokenOf = (user: User, scope: "ro" | "rw" | "admin") =>
73 createToken(app.db, user.id, scope, scope).token;
74 const post = (token: string, path: string, body: unknown) =>
75 fetch(`${base}${path}`, {
76 method: "POST",
77 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
78 body: JSON.stringify(body),
79 });
80 const page = (who: string, path: string) =>
81 fetch(`${base}${path}`, { headers: { cookie: cookies[who]! }, redirect: "manual" });
82 const submit = (who: string, path: string, form: Record<string, string>) =>
83 fetch(`${base}${path}`, {
84 method: "POST",
85 headers: { cookie: cookies[who]!, origin: base },
86 body: new URLSearchParams(form),
87 redirect: "manual",
88 });
89 const brief = (limbs: ReturnType<typeof handedLimbs>) =>
90 taskPrompt({
91 agent: { user: atlas } as never,
92 repo: fresh(),
93 issue: current(direction),
94 branch: "atlas/1-direction",
95 forgeUrl: base,
96 isApp: false,
97 resuming: false,
98 role: "planner",
99 reason: "assigned",
100 comments: [],
101 reviews: [],
102 reviewComments: [],
103 since: direction.createdAt,
104 limbs,
105 });
106
107 beforeAll(async () => {
108 dataDir = await mkdtemp(join(tmpdir(), "forge-limb-replan-"));
109 app = createApp({ dataDir, port: 0 });
110 servers = await serve(app);
111 base = servers.url;
112 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
113 const made = await createUser(app.db, {
114 origin: "seed",
115 trusted: true,
116 username,
117 email: `${username}@forge.local`,
118 password: "a-good-passphrase",
119 adminIfFirst,
120 });
121 if (!made.ok) throw new Error(made.error);
122 }
123 alice = getUserByName(app.db, "alice")!;
124 bob = getUserByName(app.db, "bob")!;
125 for (const name of ["alice", "bob"])
126 cookies[name] = (
127 (
128 await fetch(`${base}/signin`, {
129 method: "POST",
130 body: new URLSearchParams({ username: name, password: "a-good-passphrase" }),
131 redirect: "manual",
132 })
133 ).headers.get("set-cookie") ?? ""
134 ).split(";")[0]!;
135 const made = await createRepo(app, alice, { name: "engine", visibility: "public" });
136 if (!made.ok) throw new Error(String(made.error));
137 repo = made.value;
138 for (const name of ["atlas", "mason"]) {
139 const agent = await createAgent(app, alice, { username: name });
140 if (!agent.ok) throw new Error(String(agent.error));
141 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
142 }
143 atlas = getUserByName(app.db, "atlas")!;
144 mason = getUserByName(app.db, "mason")!;
145 setCrewRole(app.db, repo.id, atlas.id, "planner");
146 const set = await updateRepoSettings(app, alice, repo, {
147 autonomy: "autonomous",
148 autonomyDirection: "Keep the engine small.",
149 autonomyCeilingUsd: 100,
150 autonomyBy: alice.id,
151 });
152 if (!set.ok) throw new Error(JSON.stringify(set.error));
153 // The limb waits for four small leaves; four more issues fill the map.
154 limb = open("Search");
155 leaves = ["Index titles", "Index bodies", "Rank hits", "Highlight hits"].map((t) => open(t));
156 for (const leaf of leaves) linkIssue(app, alice, fresh(), current(limb), current(leaf));
157 outside = open("Unrelated work");
158 for (const t of ["Filler one", "Filler two", "Filler three"]) open(t);
159 direction = ensureDirectionIssue(app, alice, fresh())!;
160 });
161
162 afterAll(async () => {
163 servers.stop();
164 app.close();
165 await rm(dataDir, { recursive: true, force: true });
166 });
167
168 test("a reader, a crew agent and an ro token cannot hand a limb over", async () => {
169 for (const who of [bob, mason, atlas, undefined]) {
170 const refused = replanLimb(app, who, fresh(), limb.number);
171 expect(refused.ok).toBe(false);
172 }
173 expect(takeBackLimb(app, bob, fresh(), limb.number).ok).toBe(false);
174 expect(pendingReplans(app.db, fresh())).toEqual([]);
175 const path = `/api/v1/repos/alice/engine/milestones/${limb.number}/limb`;
176 // A read token plans and changes nothing, even when it asks to apply.
177 expect((await post(tokenOf(alice, "ro"), path, { action: "replan", dryRun: false })).status).toBe(403);
178 expect((await post(tokenOf(alice, "rw"), path, { action: "replan", dryRun: false })).status).toBe(403);
179 const dry = await post(tokenOf(alice, "ro"), path, { action: "replan" });
180 expect(dry.status).toBe(200);
181 const body = (await dry.json()) as { dryRun: boolean; issues: { number: number }[] };
182 expect(body.dryRun).toBe(true);
183 expect(body.issues.map((i) => i.number).sort()).toEqual(
184 [limb, ...leaves].map((i) => i.number).sort(),
185 );
186 const rpc = await post(tokenOf(alice, "ro"), "/mcp", {
187 jsonrpc: "2.0",
188 id: 1,
189 method: "tools/call",
190 params: {
191 name: "limb",
192 arguments: { app: "alice/engine", issue: limb.number, action: "replan", dryRun: false },
193 },
194 });
195 expect(JSON.stringify(await rpc.json())).toContain("forbidden");
196 // A reader's button and form do nothing.
197 expect((await submit("bob", `/alice/engine/milestones/${limb.number}/limb`, { action: "replan" })).status).toBe(409);
198 const said = await submit("bob", `/alice/engine/milestones/${limb.number}/limb`, { action: "replan" });
199 expect(await said.text()).toContain("only a person who administers this app");
200 expect(pendingReplans(app.db, fresh())).toEqual([]);
201 expect(await (await page("bob", `/alice/engine/milestones/${limb.number}`)).text()).not.toContain("Re-plan");
202 });
203
204 test("the preview lists every issue the planner will be given, and writes nothing", async () => {
205 const seen = previewReplan(app, bob, fresh(), limb.number);
206 expect(seen.ok && seen.value.issues.map((i) => i.number)).toEqual(
207 expect.arrayContaining([limb, ...leaves].map((i) => i.number)),
208 );
209 expect(seen.ok && seen.value.issues.some((i) => i.number === outside.number)).toBe(false);
210 const html = await (await page("alice", `/alice/engine/milestones/${limb.number}/limb?action=replan`)).text();
211 for (const leaf of leaves) expect(html).toContain(leaf.title);
212 expect(html).not.toContain("Unrelated work");
213 expect(html).toContain("Hand to the planner");
214 expect(await (await page("alice", `/alice/engine/milestones/${limb.number}`)).text()).toContain("Re-plan");
215 expect(pendingReplans(app.db, fresh())).toEqual([]);
216 });
217
218 test("owed once, with a full map and after a decline; the brief lists the limb", async () => {
219 // The planner declined the direction and nobody has answered; the map is full.
220 planned("failed", "declined: nothing to add");
221 await tick();
222 expect(readyNow(repoGraph(app.db, repo.id, { sealed: true })).length).toBeGreaterThanOrEqual(3);
223 const done = replanLimb(app, alice, fresh(), limb.number);
224 expect(done.ok).toBe(true);
225 expect(replanLimb(app, alice, fresh(), limb.number).ok).toBe(false);
226 await driveRepo(app, fresh());
227 expect(current(direction).assigneeId).toBe(atlas.id);
228 const told = brief(handedLimbs(app, fresh()));
229 expect(told).toContain(`Limb #${limb.number} Search, 4 open issues`);
230 for (const leaf of leaves) expect(told).toContain(`#${leaf.number} ${leaf.title}`);
231 expect(told).not.toContain("Unrelated work");
232 expect(told).toContain('"reason":"split"');
233 expect(brief([])).not.toContain("A person handed you these limbs");
234 // The pass is owed once: with its run begun, the next tick does not ask again.
235 planned("ok", "re-planning");
236 expect(pendingReplans(app.db, fresh())).toEqual([]);
237 });
238
239 test("until the planner answers nothing beneath the limb is picked, and the page says so", async () => {
240 await tick();
241 const second = replanLimb(app, alice, fresh(), limb.number);
242 expect(second.ok).toBe(true);
243 const startable = () => heldNow(app, fresh()).startable.map((r) => r.issue.number);
244 for (const leaf of leaves) expect(startable()).not.toContain(leaf.number);
245 expect(heldNow(app, fresh()).by.with_planner.length).toBe(4);
246 expect(startable()).toContain(outside.number);
247 const html = await (await page("bob", `/alice/engine/milestones/${limb.number}`)).text();
248 expect(html).toContain("With the planner");
249 expect(html).not.toContain("Re-plan");
250 // A reader cannot take it back; a person can, before the planner runs.
251 expect(takeBackLimb(app, bob, fresh(), limb.number).ok).toBe(false);
252 expect(await (await page("alice", `/alice/engine/milestones/${limb.number}`)).text()).toContain("Take it back");
253 expect(takeBackLimb(app, alice, fresh(), limb.number).ok).toBe(true);
254 expect(pendingReplans(app.db, fresh())).toEqual([]);
255 expect(startable()).toContain(leaves[0]!.number);
256 expect(takeBackLimb(app, alice, fresh(), limb.number).ok).toBe(false);
257 });
258
259 test("the planner may close beneath the limb only as split into what is new; nothing outside", async () => {
260 await tick();
261 const old = open("Made before the hand-over", atlas);
262 await tick();
263 expect(replanLimb(app, alice, fresh(), limb.number).ok).toBe(true);
264 await tick();
265 const [a, b] = leaves.map((l) => current(l));
266 expect(replanSince(app.db, fresh(), a!)).toBeDefined();
267 expect(replanSince(app.db, fresh(), current(outside))).toBeUndefined();
268 const close = (i: Issue, closing: Parameters<typeof setIssueState>[5]) =>
269 setIssueState(app, atlas, fresh(), current(i), "closed", closing);
270 // Not dropped, not into an older issue, not without a piece.
271 expect(close(a!, { reason: "dropped" }).ok).toBe(false);
272 expect(close(a!, { reason: "split", into: [old.number] }).ok).toBe(false);
273 expect(close(a!, { reason: "split", into: [] }).ok).toBe(false);
274 expect(current(a!).state).toBe("open");
275 // A person's issue outside the limb is not the planner's to drop.
276 expect(close(outside, { reason: "dropped" }).ok).toBe(false);
277 expect(current(outside).state).toBe("open");
278 const larger = open("Search over titles and bodies", atlas);
279 expect(close(a!, { reason: "split", into: [larger.number] }).ok).toBe(true);
280 expect(close(b!, { reason: "split", into: [larger.number] }).ok).toBe(true);
281 // Once it has answered, the grant is gone.
282 planned("ok", "re-planned");
283 expect(replanSince(app.db, fresh(), current(leaves[2]!))).toBeUndefined();
284 expect(pendingReplans(app.db, fresh())).toEqual([]);
285 });
286
287 test("afterwards the milestone shows which issues were closed into which", async () => {
288 const html = await (await page("bob", `/alice/engine/milestones/${limb.number}`)).text();
289 expect(html).toContain("Re-planned");
290 expect(html).toContain("closed as split into");
291 expect(html).toContain(leaves[0]!.title);
292 expect(html).toContain("Search over titles and bodies");
293 expect(html).not.toContain("With the planner");
294 });
295
296 test("a sealed issue the planner split is named to nobody who cannot see it", async () => {
297 const sealed = leaves[1]!;
298 const path = `/alice/engine/milestones/${limb.number}`;
299 expect(setSealed(app.db, sealed.id, true)).toBe(true);
300 try {
301 for (const who of ["bob", "guest"]) {
302 const res = await fetch(`${base}${path}`, {
303 headers: who === "guest" ? {} : { cookie: cookies[who]! },
304 });
305 const text = await res.text();
306 expect(text).toContain("closed as split into");
307 expect(text).not.toContain(sealed.title);
308 }
309 } finally {
310 setSealed(app.db, sealed.id, false);
311 }
312 });
313
314 test("a viewer who cannot administer sees the refusal in place of the button", async () => {
315 const seen = previewReplan(app, bob, fresh(), limb.number);
316 expect(seen.ok && seen.value.blocked).toContain("only a person who administers");
317 const html = await (await page("bob", `/alice/engine/milestones/${limb.number}/limb?action=replan`)).text();
318 expect(html).toContain("replan-refused");
319 expect(html).not.toContain("Hand to the planner");
320 const n = seen.ok ? seen.value.issues.length : -1;
321 expect(html).toContain(`${n} ${n === 1 ? "issue" : "issues"} the planner`);
322 });
323
324 test("a take-back is refused once the planner has been given the limb", async () => {
325 await tick();
326 expect(replanLimb(app, alice, fresh(), limb.number).ok).toBe(true);
327 await tick();
328 createRun(app.db, { repoId: repo.id, kind: "agent", issueId: direction.id, actorId: atlas.id, reason: "assigned" });
329 const seen = previewReplan(app, alice, fresh(), limb.number);
330 expect(seen.ok && seen.value.takeBack).toBe(false);
331 expect(takeBackLimb(app, alice, fresh(), limb.number).ok).toBe(false);
332 });
333 });
test/tui-limbs.test.ts +53 −1
@@ -14,7 +14,10 @@ import { tmpdir } from "node:os";
1414 import { join } from "node:path";
1515 import { linkIssue } from "../src/actions/dependencies.ts";
1616 import { openIssue } from "../src/actions/issues.ts";
17 import { createRepo } from "../src/actions/repos.ts";
17 import { addToCrew, createAgent } from "../src/actions/crew.ts";
18 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
19 import { setCrewRole } from "../src/core/agents.ts";
20 import { pendingReplans } from "../src/core/limb_replan.ts";
1821 import { createApp, type App as Forge } from "../src/app.ts";
1922 import { listEvents } from "../src/core/events.ts";
2023 import { getIssueById, type Issue } from "../src/core/issues.ts";
@@ -248,5 +251,54 @@ describe("raise and lower a limb in the terminal", () => {
248251 const body = await res.text();
249252 expect(body).toContain('id="live"');
250253 expect(body).toContain("limb.moved");
254 // A hand-over to the planner, or taking it back, reaches an open page too.
255 expect(body).toMatch(/limb\.replan[^_]/);
256 expect(body).toContain("limb.replan_taken_back");
257 });
258
259 test("p hands a limb to the planner after a preview, shows it with the planner, and takes it back; a reader has no key", async () => {
260 const made = await createRepo(forge, alice, { name: "plan", visibility: "public" });
261 if (!made.ok) throw new Error("repo");
262 const r = made.value;
263 const agent = await createAgent(forge, alice, { username: "atlas" });
264 if (!agent.ok) throw new Error(String(agent.error));
265 addToCrew(forge, alice, r, "atlas");
266 setCrewRole(forge.db, r.id, getUserByName(forge.db, "atlas")!.id, "planner");
267 await updateRepoSettings(forge, alice, r, {
268 autonomy: "autonomous",
269 autonomyDirection: "Keep it small.",
270 autonomyCeilingUsd: 10,
271 autonomyBy: alice.id,
272 });
273 const search = open(r, alice, "Search everything");
274 for (const t of ["Index titles", "Index bodies"]) link(r, search, open(r, alice, t));
275 const pending = () => pendingReplans(forge.db, getRepoById(forge.db, r.id)!).length;
276
277 const reader = boot(bob);
278 await reader.toMilestones("alice/plan");
279 await reader.press("p");
280 expect(reader.text()).not.toContain("Hand to the planner");
281 expect(pending()).toBe(0);
282 reader.stop();
283
284 const h = boot(alice);
285 await h.toMilestones("alice/plan");
286 await h.press("p");
287 // The preview lists what the planner will be given; nothing is written yet.
288 expect(h.text()).toContain("Index titles");
289 expect(h.text()).toContain("Hand to the planner");
290 expect(pending()).toBe(0);
291 await h.press("esc");
292 expect(pending()).toBe(0);
293 await h.press("p", "enter");
294 expect(pending()).toBe(1);
295 expect(h.text()).toContain("with the planner");
296 // Take it back while the planner has not started.
297 await h.press("p");
298 expect(h.text()).toContain("Take it back");
299 await h.press("enter");
300 expect(pending()).toBe(0);
301 expect(h.text()).not.toContain("with the planner");
302 h.stop();
251303 });
252304 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs