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

Raise or lower a limb against its siblings, and the crew takes ready work in that order #1019

Closed opened this in answer to
Closed without merging

scout/forge:scout/760-raise-or-lower-a-limb-against-its-siblin → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +679 −28
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 or close a whole limb as not doing, raise or lower it among its siblings (the crew takes ready work from the higher limb first), 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 +13 −3
@@ -293,14 +293,24 @@ one undo.
293293 - **Close as not doing** closes every open issue that is the limb's own,
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.
296 - **Raise** and **Lower** move a limb one place among its siblings (#760):
297 a milestone's limbs, or the plan's top-level ones. The place is stored
298 (`limb_place`, `core/limb_places.ts`) and the lists show the limbs in
299 that order; a limb with no place comes after the placed ones, by number,
300 as before. The crew's ready order follows it: a ready issue beneath a
301 higher limb comes before one beneath a lower limb, an issue beneath two
302 limbs takes the higher, and within a limb the order is as it was — what
303 frees the most, then the oldest. The preview shows the new order and the
304 top of the ready list before and after; undo puts the place back. Raise
305 and Lower sit on each limb in the lists, for whoever administers the
306 repository. A limb in two groups has one place, used in both.
296307
297308 An umbrella or the gate is the plan's own and is not filed. A leaf beneath
298309 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.
310 candidate to trim offers Defer first. Handing one to the planner is #761.
301311
302312 The same is `POST /api/v1/repos/:owner/:name/milestones/:number/limb`
303 `{ "action": "defer" | "resume" | "close", "reason"?, "pillar"?, "dryRun"? }`
313 `{ "action": "defer" | "resume" | "close" | "raise" | "lower", "reason"?, "pillar"?, "dryRun"? }`
304314 and the MCP's `limb`, both a dry run unless `dryRun` is false. Applying and
305315 undoing take an admin token of a person who administers the repository; an
306316 agent may look and never apply.
src/actions/fleet.ts +17 −1
@@ -34,6 +34,7 @@ import {
3434 } from "../core/issues.ts";
3535 import { listCrewRoles } from "../core/agents.ts";
3636 import { joinMany } from "../core/pulls.ts";
37 import { readPlan } from "../core/milestones.ts";
3738 import { pillarsOf, type Pillars } from "../core/pillars.ts";
3839 import {
3940 canAdmin,
@@ -127,6 +128,7 @@ function loadTargets(
127128 kind: FleetKind,
128129 ids: readonly string[],
129130 viewer?: User,
131 withSiblings = false,
130132 ): Target[] {
131133 if (kind === "repo") {
132134 const repos = getReposByIds(app.db, ids);
@@ -179,6 +181,18 @@ function loadTargets(
179181 for (const [repoId, repo] of repos) pillars.set(repoId, pillarsOf(app.db, repo));
180182 const under = umbrellasOver(app, ids, [...pillars.values()]);
181183 const peers: ReadonlySet<string> = new Set(ids);
184 // A limb's siblings, from one plan a repository, only for a verb that asks.
185 const plans = new Map<string, ReturnType<typeof readPlan>>();
186 const siblingsOf = (repo: Repo, issue: { number: number; id: string }) => {
187 if (!withSiblings) return {};
188 let plan = plans.get(repo.id);
189 if (plan === undefined) plans.set(repo.id, (plan = readPlan(app.db, repo)));
190 const group = plan.siblings(issue.number)?.map((i) => i.id);
191 const at = group?.indexOf(issue.id) ?? -1;
192 return group === undefined || at < 0
193 ? {}
194 : { place: at + 1, siblings: group };
195 };
182196 const pull = (id: string) => {
183197 const p = pulls.get(id);
184198 return p === undefined
@@ -208,6 +222,7 @@ function loadTargets(
208222 pillars: pillars.get(repo.id)!,
209223 under: under.get(id) ?? [],
210224 peers,
225 ...siblingsOf(repo, issue),
211226 ...(viewer === undefined
212227 ? {}
213228 : {
@@ -355,7 +370,7 @@ function planOver(
355370 query: string,
356371 act: { name: string; verb: Verb; value: FleetValue },
357372 ): Plan & { verbOf: Verb; targets: Map<string, Target> } {
358 const targets = loadTargets(app, kind, ids, actor);
373 const targets = loadTargets(app, kind, ids, actor, act.verb.siblings === true);
359374 const authority = authorityOf(app, actor, act.verb);
360375 const { verb, value } = act;
361376 const rows = targets.map((t) =>
@@ -575,6 +590,7 @@ export async function undoFleetOp(
575590 op.kind,
576591 changed.map((r) => r.targetId),
577592 person.value,
593 verb.siblings === true,
578594 );
579595 const byId = new Map(targets.map((t) => [t.id, t]));
580596 const authority = authorityOf(app, person.value, verb);
src/actions/limbs.ts +46 −1
@@ -16,6 +16,11 @@
1616 * one reason said on each — and never what something outside the limb
1717 * also waits for.
1818 *
19 * - `raise` and `lower` (#760) move the limb one place among its siblings
20 * (`core/limb_places.ts`), and the crew takes ready work from the higher
21 * limb first. The preview is the new order and how the top of the ready
22 * list changes; undo puts the place back.
23 *
1924 * Who may is the fleet's rule, unchanged: a person who administers the
2025 * repository; an agent may preview and never apply.
2126 */
@@ -23,9 +28,11 @@
2328 import type { App } from "../app.ts";
2429 import type { FleetValue, Operation } from "../core/fleet_ops.ts";
2530 import type { Issue } from "../core/issues.ts";
31 import { readyNow, repoGraph } from "../core/dependencies.ts";
2632 import { readPlan } from "../core/milestones.ts";
2733 import { isStructural, pillarsOf } from "../core/pillars.ts";
2834 import { canRead, type Repo } from "../core/repos.ts";
35 import { sealedScope } from "../core/sealed.ts";
2936 import type { User } from "../core/users.ts";
3037 import { err, ok, type Result } from "../kernel/result.ts";
3138 import {
@@ -35,7 +42,7 @@ import {
3542 type Plan,
3643 } from "./fleet.ts";
3744
38 export const LIMB_ACTIONS = ["defer", "resume", "close"] as const;
45 export const LIMB_ACTIONS = ["defer", "resume", "close", "raise", "lower"] as const;
3946 export type LimbAction = (typeof LIMB_ACTIONS)[number];
4047
4148 export const isLimbAction = (value: unknown): value is LimbAction =>
@@ -62,8 +69,15 @@ export interface LimbReach {
6269 readonly taken: readonly LimbIssue[];
6370 /** For `defer` and `close`: what beneath it stays, because something outside the limb still waits for it. */
6471 readonly kept: readonly LimbIssue[];
72 /** For `raise` and `lower`: the limb's siblings in order, before and after. */
73 readonly order?: { readonly before: readonly LimbIssue[]; readonly after: readonly LimbIssue[] };
74 /** For `raise` and `lower`: the top of the crew's ready list, before and after. */
75 readonly ready?: { readonly before: readonly LimbIssue[]; readonly after: readonly LimbIssue[] };
6576 }
6677
78 /** How much of the ready list a preview shows: what the crew takes next, and a little after. */
79 const READY_SHOWN = 5
80
6781 const brief = (issue: Issue): LimbIssue => ({
6882 number: issue.number,
6983 title: issue.title,
@@ -93,6 +107,37 @@ function shape(
93107 return fail("not_found", "no such milestone here");
94108 const limb = brief(rows.own[0]);
95109 const where = `issue repo:${repo.ownerName}/${repo.name}`;
110 if (request.action === "raise" || request.action === "lower") {
111 const group = plan.siblings(number);
112 const at = group?.findIndex((i) => i.id === rows.own[0]!.id) ?? -1;
113 if (group === undefined || at < 0)
114 return fail("bad_action", "only a limb among other limbs has a place to move");
115 const to = Math.min(
116 group.length - 1,
117 Math.max(0, at + (request.action === "raise" ? -1 : 1)),
118 );
119 const moved = [...group];
120 moved.splice(to, 0, ...moved.splice(at, 1));
121 // The ready list as the crew reads it, with and without the new places.
122 const graph = repoGraph(app.db, repo.id, sealedScope(app.db, repo, actor));
123 const places = new Map(graph.places);
124 moved.forEach((i, n) => places.set(i.id, n + 1));
125 const top = (g: typeof graph) =>
126 readyNow(g)
127 .slice(0, READY_SHOWN)
128 .map((r) => brief(r.issue));
129 return ok({
130 query: `${where} number:${number}`,
131 action: { verb: "place", value: request.action },
132 reach: {
133 limb,
134 taken: [],
135 kept: [],
136 order: { before: group.map(brief), after: moved.map(brief) },
137 ready: { before: top(graph), after: top({ ...graph, places }) },
138 },
139 });
140 }
96141 if (request.action === "close") {
97142 const reason = (request.reason ?? "").trim();
98143 if (reason === "")
src/core/dependencies.ts +9 −1
@@ -11,6 +11,7 @@
1111 import type { Database } from "bun:sqlite";
1212 import { err, ok, type Result } from "../kernel/result.ts";
1313 import { getIssuesByIds, type CloseReason, type Issue } from "./issues.ts";
14 import { chainsOf, compareChains, loadPlaces } from "./limb_places.ts";
1415 import { pillarsOf, structuralIds } from "./pillars.ts";
1516 import { getRepoById } from "./repos.ts";
1617 import { unadoptedAmong } from "../crew/direct.ts";
@@ -215,6 +216,8 @@ export interface Graph {
215216 * words, as every surface says it (`deferredWhy`).
216217 */
217218 readonly deferred: ReadonlyMap<string, string>;
219 /** A limb's place among its siblings, by issue id (`limb_place.ts`); absent or empty when nobody set one. */
220 readonly places?: ReadonlyMap<string, number>;
218221 }
219222
220223 /**
@@ -323,6 +326,7 @@ export function repoGraph(
323326 unadopted:
324327 repo === undefined ? new Set() : unadoptedAmong(db, repo, issues),
325328 structural: set === undefined ? new Set() : structuralIds(set),
329 places: loadPlaces(db, repoId),
326330 edges: kept,
327331 held: heldRows
328332 .filter((r) => present.has(r.issue_id) && present.has(r.blocked_by_id))
@@ -484,6 +488,8 @@ function clearNow(graph: Graph): Ranked[] {
484488 const holds = holdsUpMap(graph, open);
485489 const waits = waitsForMap(graph, open);
486490 const held = new Set(graph.held.map((h) => h.issueId));
491 const chains = chainsOf(graph);
492 const chain = (id: string): readonly number[] => chains.get(id) ?? [];
487493 return graph.issues
488494 .filter(
489495 (i) =>
@@ -498,6 +504,7 @@ function clearNow(graph: Graph): Ranked[] {
498504 }))
499505 .sort(
500506 (a, b) =>
507 compareChains(chain(a.issue.id), chain(b.issue.id)) ||
501508 b.holdsUp - a.holdsUp ||
502509 a.issue.createdAt.localeCompare(b.issue.createdAt),
503510 );
@@ -505,7 +512,8 @@ function clearNow(graph: Graph): Ranked[] {
505512
506513 /**
507514 * Open issues nothing open stands in front of and that are not deferred,
508 * first the ones whose finishing frees the most, then the oldest — a
515 * first those beneath the higher limb (`limb_places.ts`), then the ones
516 * whose finishing frees the most, then the oldest — a
509517 * reader's suggestion only once someone who writes here adopted it, and
510518 * never the plan's own furniture: an umbrella or the Later gate is not
511519 * work. What a free crew slot takes next.
src/core/limb_places.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * A limb's place among its siblings (#760): the order a person sets with
3 * Raise and Lower, stored as one number a limb, 1 for the first. Siblings
4 * are a milestone's limbs, or the plan's top-level limbs; a limb without a
5 * place comes after the placed ones, by number, as every limb did before
6 * anyone set one.
7 *
8 * The crew follows it (`readyNow`): a ready issue's key is the places of
9 * the limbs above it, top down, and the lexicographically least chain it
10 * stands under wins — so an issue beneath two limbs takes the higher.
11 * Nothing placed means every key is equal and the ready order is untouched.
12 * One pass over the graph already in hand; no query per issue.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import type { Graph } from "./dependencies.ts";
17
18 /** Where a limb with no place stands: after every limb that has one. */
19 export const UNPLACED = Number.MAX_SAFE_INTEGER;
20
21 /** Every placed issue of one repository, by id. */
22 export function loadPlaces(db: Database, repoId: string): Map<string, number> {
23 return new Map(
24 db
25 .query<{ issue_id: string; place: number }, [string]>(
26 `SELECT p.issue_id, p.place FROM limb_place p
27 JOIN issue i ON i.id = p.issue_id WHERE i.repo_id = ?1`,
28 )
29 .all(repoId)
30 .map((r) => [r.issue_id, r.place]),
31 );
32 }
33
34 /** Give these issues places 1..n, in this order, all or nothing. */
35 export function placeLimbs(db: Database, orderedIds: readonly string[]): void {
36 const write = db.transaction(() => {
37 orderedIds.forEach((id, n) => {
38 db.query(
39 `INSERT INTO limb_place (issue_id, place) VALUES (?1, ?2)
40 ON CONFLICT(issue_id) DO UPDATE SET place = excluded.place`,
41 ).run(id, n + 1);
42 });
43 });
44 write();
45 }
46
47 /** Compare two chains of places, a missing level counting as unplaced. */
48 export function compareChains(a: readonly number[], b: readonly number[]): number {
49 for (let n = 0; n < Math.max(a.length, b.length); n++) {
50 const diff = (a[n] ?? UNPLACED) - (b[n] ?? UNPLACED);
51 if (diff !== 0) return diff;
52 }
53 return 0;
54 }
55
56 /**
57 * For each issue, the chain of places of the limbs above it, top down, of
58 * the highest chain it stands under. Empty when nothing is placed.
59 */
60 export function chainsOf(graph: Graph): Map<string, number[]> {
61 const out = new Map<string, number[]>();
62 const places = graph.places;
63 if (places === undefined || places.size === 0) return out;
64 const open = new Set(
65 graph.issues.filter((i) => i.state === "open").map((i) => i.id),
66 );
67 const waiters = new Map<string, string[]>();
68 for (const e of graph.edges)
69 if (open.has(e.issueId))
70 waiters.set(e.blockedById, [...(waiters.get(e.blockedById) ?? []), e.issueId]);
71 const visiting = new Set<string>();
72 const up = (id: string): number[] => {
73 const known = out.get(id);
74 if (known !== undefined) return known;
75 if (visiting.has(id)) return [];
76 visiting.add(id);
77 let best: number[] | undefined;
78 for (const w of waiters.get(id) ?? []) {
79 const chain = [...up(w), places.get(w) ?? UNPLACED];
80 if (best === undefined || compareChains(chain, best) < 0) best = chain;
81 }
82 visiting.delete(id);
83 out.set(id, best ?? []);
84 return best ?? [];
85 };
86 for (const i of graph.issues) up(i.id);
87 return out;
88 }
src/core/milestones.ts +28 −1
@@ -16,6 +16,7 @@
1616 import type { Database } from "bun:sqlite";
1717 import { deferredIn, repoGraph, type Graph } from "./dependencies.ts";
1818 import type { Issue } from "./issues.ts";
19 import { UNPLACED } from "./limb_places.ts";
1920 import {
2021 isStructural,
2122 LATER,
@@ -122,6 +123,12 @@ export interface Plan {
122123 * Nothing for a number that is no issue here.
123124 */
124125 limb(number: number): { own: Issue[]; shared: Issue[] } | undefined;
126 /**
127 * The limbs this limb stands among, in the order a person set (then by
128 * number): the plan's top-level limbs, or those of the lowest-numbered
129 * milestone that has it as a limb. Nothing for an issue that is no limb.
130 */
131 siblings(number: number): Issue[] | undefined;
125132 /**
126133 * What deferring this issue would take with it: the open issues that
127134 * would stop being ready, itself included, and, beneath it, the ones that
@@ -355,6 +362,9 @@ export function readPlan(
355362 };
356363
357364 const isMilestone = (id: string): boolean => childrenOf(id).length > 0;
365 /** Siblings in the order a person set; unplaced ones after, by number. */
366 const placed = (a: Issue, b: Issue): number =>
367 (graph.places?.get(a.id) ?? UNPLACED) - (graph.places?.get(b.id) ?? UNPLACED);
358368
359369 const top: Issue[] =
360370 set.pillars.length > 0
@@ -371,8 +381,25 @@ export function readPlan(
371381 ),
372382 );
373383
384 top.sort(placed);
385
374386 return {
375387 limbs: top.map(limbOf),
388 siblings(number: number): Issue[] | undefined {
389 const issue = byNumber.get(number);
390 if (issue === undefined) return undefined;
391 if (top.some((t) => t.id === issue.id)) return [...top];
392 const parents = (waitedBy.get(issue.id) ?? [])
393 .map((id) => byId.get(id))
394 .filter((i): i is Issue => i !== undefined && i.state === "open")
395 .sort((a, b) => a.number - b.number);
396 for (const parent of parents) {
397 const group = this.milestone(parent.number)?.limbs;
398 if (group?.some((l) => l.issue.id === issue.id))
399 return group.map((l) => l.issue);
400 }
401 return undefined;
402 },
376403 limb(number: number): { own: Issue[]; shared: Issue[] } | undefined {
377404 const issue = byNumber.get(number);
378405 if (issue === undefined) return undefined;
@@ -534,7 +561,7 @@ export function readPlan(
534561 .filter((pull) => pull.closes.some((n) => numbers.has(n)))
535562 .map(({ number: n, title, at }) => ({ number: n, title, at })),
536563 estimate,
537 limbs: children.filter(isLimb).map(limbOf),
564 limbs: children.filter(isLimb).sort(placed).map(limbOf),
538565 leaves: children
539566 .filter((c) => !isLimb(c))
540567 .map((c) => {
src/core/schema.ts +8
@@ -1540,4 +1540,12 @@ export const migrations: readonly string[] = [
15401540 SELECT RAISE(ABORT, 'a sealed repository is never public');
15411541 END;
15421542 `,
1543 // 71 — a limb's place among its siblings (#760): set by Raise and Lower,
1544 // read by the ready order. One row a placed limb; none means unplaced.
1545 `
1546 CREATE TABLE IF NOT EXISTS limb_place (
1547 issue_id TEXT PRIMARY KEY REFERENCES issue(id) ON DELETE CASCADE,
1548 place INTEGER NOT NULL CHECK (place >= 1)
1549 );
1550 `,
15431551 ];
src/fleet/verbs.ts +46
@@ -23,6 +23,7 @@ import { cancelRepoRun, requeueRepoRun } from "../actions/runs.ts";
2323 import { isCrew } from "../core/agents.ts";
2424 import { mergePull } from "../actions/pulls.ts";
2525 import { bringUpToDate } from "../crew/autonomy.ts";
26 import { placeLimbs } from "../core/limb_places.ts";
2627 import { getHold } from "../core/holds.ts";
2728 import { recordInteraction, removeDismissals } from "../core/interactions.ts";
2829 import { getPull } from "../core/pulls.ts";
@@ -69,6 +70,9 @@ export interface Target {
6970 readonly pillars?: Pillars;
7071 /** For an issue: the numbers of the umbrellas that wait for it directly, ascending. */
7172 readonly under?: readonly number[];
73 /** For a limb, when the verb asks: its 1-based place among its siblings, and the siblings' ids in order. */
74 readonly place?: number;
75 readonly siblings?: readonly string[];
7276 /** For an issue: the ids of every row this operation is over, itself included. */
7377 readonly peers?: ReadonlySet<string>;
7478 }
@@ -80,6 +84,8 @@ export interface Verb {
8084 parse(app: App, value: unknown): Result<FleetValue, string>;
8185 /** True when the verb changes the actor's own state, not the repository's: only they undo it. */
8286 readonly personal?: boolean;
87 /** True when the verb reads a limb's siblings (`Target.place`): loaded only for it. */
88 readonly siblings?: boolean;
8389 read(target: Target): FleetValue;
8490 next(before: FleetValue, value: FleetValue): FleetValue;
8591 /** When the value depends on the row (the repository's own planner): this, not `next`. */
@@ -676,4 +682,44 @@ export const VERBS: Record<string, Verb> = {
676682 );
677683 },
678684 },
685
686 /**
687 * Raise or lower a limb against its siblings (#760): the row holds its
688 * place among them, 1 for first, and the verb moves it one place, the
689 * limb it passes taking its old one. Undo writes the place from before.
690 * The crew takes ready work from the higher limb first (`readyNow`).
691 */
692 place: {
693 kind: "issue",
694 reversible: true,
695 siblings: true,
696 parse: (_app, value) =>
697 value === "raise" || value === "lower"
698 ? ok(value)
699 : err("place takes raise or lower"),
700 read: (t) => t.place ?? null,
701 next: replace,
702 nextFor(t, before, value) {
703 if (typeof before !== "number") return before;
704 const last = t.siblings?.length ?? before;
705 return value === "raise"
706 ? Math.max(1, before - 1)
707 : Math.min(last, before + 1);
708 },
709 refuse(_app, t, after) {
710 const last = t.siblings?.length ?? 0;
711 if (t.place === undefined) return "not a limb among others";
712 return typeof after === "number" && after >= 1 && after <= last
713 ? undefined
714 : "no such place among its siblings";
715 },
716 async write(app, _actor, t, after) {
717 const order = (t.siblings ?? []).filter((id) => id !== t.id);
718 if (typeof after !== "number" || t.place === undefined)
719 return "not a limb among others";
720 order.splice(after - 1, 0, t.id);
721 placeLimbs(app.db, order);
722 return undefined;
723 },
724 },
679725 };
src/http/api.ts +2 −2
@@ -2442,7 +2442,7 @@ export function apiRoutes(router: Router<Handler>): void {
24422442 },
24432443 );
24442444 // One action on a whole limb (#733): defer, resume, or close as not
2445 // doing. A fleet operation in every respect — a dry run by default with a
2445 // doing; raise or lower it among its siblings (#760). A fleet operation in every respect — a dry run by default with a
24462446 // read credential, an admin token to apply, the receipt in
24472447 // /api/v1/fleet/ops/:id and its undo at …/undo.
24482448 router.add(
@@ -2457,7 +2457,7 @@ export function apiRoutes(router: Router<Handler>): void {
24572457 const number = positiveInt(ctx.params.number);
24582458 if (!repo || number === undefined) return notFound();
24592459 if (!isLimbAction(input.action))
2460 return apiError("bad_action", 422, "action is defer, resume or close");
2460 return apiError("bad_action", 422, "action is defer, resume, close, raise or lower");
24612461 const request = {
24622462 action: input.action,
24632463 ...(typeof input.reason === "string" ? { reason: input.reason } : {}),
src/http/mcp.ts +3 −3
@@ -1236,7 +1236,7 @@ const TOOLS: readonly Tool[] = [
12361236 {
12371237 name: "limb",
12381238 description:
1239 "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.",
1239 "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 the limb one place among its siblings, and the crew takes ready work from the higher limb first (the dry run answers with `order` and the top of `ready`, 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.",
12401240 inputSchema: {
12411241 type: "object",
12421242 properties: {
@@ -1246,7 +1246,7 @@ const TOOLS: readonly Tool[] = [
12461246 minimum: 1,
12471247 description: "The limb: the number of its issue.",
12481248 },
1249 action: { type: "string", enum: ["defer", "resume", "close", "undo"] },
1249 action: { type: "string", enum: ["defer", "resume", "close", "raise", "lower", "undo"] },
12501250 reason: {
12511251 type: "string",
12521252 description: "For close: why it is not being done, in one sentence.",
@@ -1290,7 +1290,7 @@ const TOOLS: readonly Tool[] = [
12901290 !Number.isInteger(number) ||
12911291 number < 1
12921292 )
1293 return bad("invalid", "give the limb's issue number and an action: defer, resume, close or undo");
1293 return bad("invalid", "give the limb's issue number and an action: defer, resume, close, raise, lower or undo");
12941294 const request = {
12951295 action: args["action"],
12961296 ...(typeof args["reason"] === "string" ? { reason: args["reason"] } : {}),
src/web/pages/limb.ts +65 −7
@@ -50,8 +50,21 @@ 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 raise: {
54 ask: "Raise",
55 does: "It moves up one place among its siblings. The crew takes ready work from the higher limb first.",
56 go: "Raise this limb",
57 },
58 lower: {
59 ask: "Lower",
60 does: "It moves down one place among its siblings. The crew takes ready work from the higher limb first.",
61 go: "Lower this limb",
62 },
5363 };
5464
65 const same = (a: readonly LimbIssue[], b: readonly LimbIssue[]): boolean =>
66 a.length === b.length && a.every((x, n) => x.number === b[n]?.number);
67
5568 const shown = (value: FleetValue): string =>
5669 value === null
5770 ? "nothing"
@@ -128,6 +141,21 @@ function rowList(
128141 </ul>`;
129142 }
130143
144 /** The limb's siblings in order, the one being moved in bold. */
145 function orderList(base: string, issues: readonly LimbIssue[], mine: number): Html {
146 return html`<ol class="ms-rows limb-order">
147 ${issues.map(
148 (i) =>
149 html`<li>
150 ${i.number === mine
151 ? html`<b><a href="${base}/milestones/${i.number}">${i.title}</a></b>`
152 : html`<a href="${base}/milestones/${i.number}">${i.title}</a>`}
153 <span class="muted small">#${i.number}</span>
154 </li>`,
155 )}
156 </ol>`;
157 }
158
131159 function requestOf(
132160 action: LimbAction,
133161 get: (name: string) => string,
@@ -179,6 +207,7 @@ export function limbPreviewPage(ctx: Ctx): Response {
179207 }
180208 const p = plan.value;
181209 const willWrite = p.counts.change > 0;
210 const moving = action === "raise" || action === "lower";
182211 const pillars =
183212 action === "resume" ? pillarsOf(ctx.app.db, repo).pillars : [];
184213 const body = html`${repoHeader(ctx, repo, "map")}
@@ -189,6 +218,30 @@ export function limbPreviewPage(ctx: Ctx): Response {
189218 <h1>${words.ask} “${p.limb.title}”?</h1>
190219 <p>${words.does}</p>
191220 </div>
221 ${when(
222 p.order !== undefined && p.counts.change > 0,
223 () =>
224 html`<section class="ms-section" id="limb-order">
225 <h2>The new order</h2>
226 ${orderList(base, p.order!.after, number)}
227 </section>`,
228 )}
229 ${when(
230 p.ready !== undefined && p.counts.change > 0,
231 () =>
232 html`<section class="ms-section" id="limb-ready">
233 <h2>What the crew takes next</h2>
234 ${p.ready!.after.length === 0
235 ? html`<p class="muted small">Nothing is ready.</p>`
236 : issueList(base, p.ready!.after)}
237 ${same(p.ready!.before, p.ready!.after)
238 ? html`<p class="muted small">The same as now.</p>`
239 : html`<details class="ms-more">
240 <summary class="small">Now</summary>
241 ${issueList(base, p.ready!.before)}
242 </details>`}
243 </section>`,
244 )}
192245 ${when(
193246 p.taken.length > 0,
194247 () =>
@@ -213,12 +266,14 @@ export function limbPreviewPage(ctx: Ctx): Response {
213266 ${issueList(base, p.kept)}
214267 </section>`,
215268 )}
216 <section class="ms-section" id="limb-rows">
217 <h2>What is written</h2>
218 ${p.rows.length === 0
219 ? html`<p class="muted small">Nothing: no open issue is the limb's alone.</p>`
220 : rowList(ctx, base, p.rows)}
221 </section>
269 ${moving
270 ? null
271 : html`<section class="ms-section" id="limb-rows">
272 <h2>What is written</h2>
273 ${p.rows.length === 0
274 ? html`<p class="muted small">Nothing: no open issue is the limb's alone.</p>`
275 : rowList(ctx, base, p.rows)}
276 </section>`}
222277 ${willWrite
223278 ? html`<form
224279 method="post"
@@ -268,7 +323,9 @@ export function limbPreviewPage(ctx: Ctx): Response {
268323 </div>
269324 </form>`
270325 : html`<p class="mt">
271 Nothing here is yours to change.
326 ${moving && p.counts.unchanged > 0
327 ? "It is already there."
328 : "Nothing here is yours to change."}
272329 <a href="${milestoneHref(base, number)}">Back</a>
273330 </p>`}`;
274331 return page({
@@ -313,6 +370,7 @@ export async function limbSubmit(ctx: Ctx): Promise<Response> {
313370 function done(op: Operation): string {
314371 if (op.undoOf !== null) return "Undone";
315372 if (op.verb === "drop") return "Closed as not doing";
373 if (op.verb === "place") return op.value === "raise" ? "Raised" : "Lowered";
316374 return op.value === "later" ? "Deferred" : "Resumed";
317375 }
318376
src/web/pages/milestones.ts +44 −8
@@ -101,7 +101,12 @@ function weightWords(limb: Limb): Html {
101101 }
102102
103103 /** One limb as one line: a link to it, how far it is, and its weight. */
104 function limbLine(base: string, limb: Limb): Html {
104 function limbLine(
105 base: string,
106 limb: Limb,
107 /** For whoever administers: which way it can move among its siblings. */
108 move?: { readonly up: boolean; readonly down: boolean },
109 ): Html {
105110 const w = limb.weight;
106111 return html`<li class="ms-limb" data-trim="${limb.trim === undefined ? "no" : "yes"}">
107112 <a class="ms-name" href="${milestoneHref(base, limb.issue.number)}"
@@ -120,9 +125,38 @@ function limbLine(base: string, limb: Limb): Html {
120125 (why) =>
121126 html`<span class="ms-trim small">A candidate to trim: ${why}.</span>`,
122127 )}
128 ${when(
129 move && (move.up || move.down),
130 () =>
131 html`<span class="ms-move small">
132 ${move!.up
133 ? html`<a href="${limbHref(base, limb.issue.number, "raise")}"
134 >Raise</a
135 >`
136 : null}
137 ${move!.down
138 ? html`<a href="${limbHref(base, limb.issue.number, "lower")}"
139 >Lower</a
140 >`
141 : null}
142 </span>`,
143 )}
123144 </li>`;
124145 }
125146
147 /** The limbs as lines, in the order they stand; a limb that can move says so. */
148 function limbLines(base: string, limbs: readonly Limb[], admin: boolean): Html[] {
149 return limbs.map((limb, n) =>
150 limbLine(
151 base,
152 limb,
153 admin && limbs.length > 1
154 ? { up: n > 0, down: n < limbs.length - 1 }
155 : undefined,
156 ),
157 );
158 }
159
126160 /** GET /:owner/:name/milestones — the plan, collapsed to its limbs. */
127161 export function milestonesPage(ctx: Ctx): Response {
128162 const repo = loadRepo(ctx);
@@ -144,9 +178,9 @@ export function milestonesPage(ctx: Ctx): Response {
144178 Nothing here waits for anything yet, so there is no milestone to
145179 show. <a href="${base}/map">See the map</a>.
146180 </p>`
147 : html`<ul class="ms-limbs" id="ms-limbs">
148 ${plan.limbs.map((limb) => limbLine(base, limb))}
149 </ul>`}`;
181 : html`<ol class="ms-limbs" id="ms-limbs">
182 ${limbLines(base, plan.limbs, canAdmin(ctx.app.db, repo, ctx.auth.user))}
183 </ol>`}`;
150184 return page({
151185 ctx,
152186 title: `Milestones · ${repo.name}`,
@@ -208,6 +242,7 @@ function milestoneBody(
208242 m: Milestone,
209243 names: boolean,
210244 actions: Html | null,
245 admin: boolean,
211246 ): Html {
212247 const base = repoBase(repo);
213248 const issue = (number: number, title: string): Html =>
@@ -256,9 +291,9 @@ function milestoneBody(
256291 () =>
257292 html`<section class="ms-section" id="ms-limbs">
258293 <h2>Limbs</h2>
259 <ul class="ms-limbs">
260 ${m.limbs.map((limb) => limbLine(base, limb))}
261 </ul>
294 <ol class="ms-limbs">
295 ${limbLines(base, m.limbs, admin)}
296 </ol>
262297 </section>`,
263298 )}
264299 ${when(
@@ -409,7 +444,7 @@ export function milestonePage(ctx: Ctx): Response {
409444 crumbs: crumbsFor(repo),
410445 palette: repoPalette(ctx, repo),
411446 body: html`${repoHeader(ctx, repo, "map")}
412 ${milestoneBody(repo, milestone, owner, actions)}`,
447 ${milestoneBody(repo, milestone, owner, actions, canAdmin(ctx.app.db, repo, ctx.auth.user))}`,
413448 styleCss: milestonesCss,
414449 });
415450 }
@@ -487,6 +522,7 @@ export const milestonesCss = /* css */ `
487522 .ms-bar::-webkit-progress-value { background: var(--success); }
488523 .ms-bar::-moz-progress-bar { background: var(--success); }
489524 .ms-weight, .ms-trim { grid-column: 1 / -1; }
525 .ms-move { grid-column: 1 / -1; display: flex; gap: 16px; padding-top: 2px; }
490526 .ms-trim { color: var(--attn); margin: 0; }
491527 .ms-top { display: grid; gap: 8px; max-width: 640px; }
492528 .ms-top h1, .ms-top p { margin: 0; }
test/limb_order.test.ts added +309
@@ -0,0 +1,309 @@
1 /**
2 * Raising and lowering a limb among its siblings (#760): the place is
3 * stored and survives a restart, the crew's ready order follows it, the
4 * move is one fleet operation with a preview, a receipt and an undo, and
5 * a reader, a crew agent and a read token cannot make it.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { linkIssue } from "../src/actions/dependencies.ts";
14 import { undoFleetOp } from "../src/actions/fleet.ts";
15 import { openIssue } from "../src/actions/issues.ts";
16 import { applyLimb, previewLimb } from "../src/actions/limbs.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { readyNow, repoGraph, type Graph } from "../src/core/dependencies.ts";
19 import { getIssueById, type Issue } from "../src/core/issues.ts";
20 import { readPlan } from "../src/core/milestones.ts";
21 import { getRepoById, type Repo } from "../src/core/repos.ts";
22 import { createToken } from "../src/core/tokens.ts";
23 import { createUser, getUserByName, type User } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25
26 describe("limb order", () => {
27 let dataDir: string;
28 let app: App;
29 let servers: Servers;
30 let base: string;
31 let alice: User;
32 let bob: User;
33 let mason: User;
34 let repo: Repo;
35 let milestone: Issue;
36 let a: Issue;
37 let b: Issue;
38 let c: Issue;
39 let a1: Issue;
40 let b1: Issue;
41 let c1: Issue;
42 let both: Issue;
43 const cookies: Record<string, string> = {};
44
45 const fresh = () => getRepoById(app.db, repo.id)!;
46 const current = (i: Issue) => getIssueById(app.db, i.id)!;
47 const open = (title: string): Issue => {
48 const opened = openIssue(app, alice, fresh(), { title });
49 if (!opened.ok) throw new Error(String(opened.error));
50 return opened.value;
51 };
52 const link = (waiter: Issue, on: Issue): void => {
53 const linked = linkIssue(app, alice, fresh(), current(waiter), current(on));
54 if (!linked.ok) throw new Error(String(linked.error));
55 };
56 const order = (): number[] =>
57 readPlan(app.db, fresh())
58 .milestone(milestone.number)!
59 .limbs.map((l) => l.issue.number);
60 const ready = (): number[] =>
61 readyNow(repoGraph(app.db, repo.id)).map((r) => r.issue.number);
62 const tokenOf = (user: User, scope: "ro" | "rw" | "admin"): string =>
63 createToken(app.db, user.id, scope, scope).token;
64 const post = (token: string, path: string, body: unknown) =>
65 fetch(`${base}${path}`, {
66 method: "POST",
67 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
68 body: JSON.stringify(body),
69 });
70 let nextId = 1;
71 const tool = async (token: string, args: unknown) => {
72 const res = await post(token, "/mcp", {
73 jsonrpc: "2.0",
74 id: nextId++,
75 method: "tools/call",
76 params: { name: "limb", arguments: args },
77 });
78 const body = (await res.json()) as any;
79 const text: string = body.result.content[0].text;
80 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
81 };
82 const raise = (who: User, issue: Issue, action: "raise" | "lower" = "raise") =>
83 applyLimb(app, who, fresh(), issue.number, { action });
84
85 beforeAll(async () => {
86 dataDir = await mkdtemp(join(tmpdir(), "forge-limb-order-"));
87 app = createApp({ dataDir, port: 0 });
88 servers = await serve(app);
89 base = servers.url;
90 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
91 const made = await createUser(app.db, {
92 trusted: true,
93 username,
94 email: `${username}@forge.local`,
95 password: "a-good-passphrase",
96 adminIfFirst,
97 });
98 if (!made.ok) throw new Error(made.error);
99 }
100 alice = getUserByName(app.db, "alice")!;
101 bob = getUserByName(app.db, "bob")!;
102 for (const name of ["alice", "bob"])
103 cookies[name] = (
104 (
105 await fetch(`${base}/signin`, {
106 method: "POST",
107 body: new URLSearchParams({ username: name, password: "a-good-passphrase" }),
108 redirect: "manual",
109 })
110 ).headers.get("set-cookie") ?? ""
111 ).split(";")[0]!;
112 const made = await createRepo(app, alice, { name: "engine", visibility: "public" });
113 if (!made.ok) throw new Error(String(made.error));
114 repo = made.value;
115 const seeded = await commitToBranch(app, alice, repo, {
116 message: "Start",
117 files: [{ path: "README.md", content: "# engine\n" }],
118 });
119 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
120 const agent = await createAgent(app, alice, { username: "mason" });
121 if (!agent.ok) throw new Error(String(agent.error));
122 expect(addToCrew(app, alice, repo, "mason").ok).toBe(true);
123 mason = getUserByName(app.db, "mason")!;
124
125 milestone = open("The milestone");
126 a = open("Limb A");
127 b = open("Limb B");
128 c = open("Limb C");
129 a1 = open("A's work");
130 b1 = open("B's work");
131 c1 = open("C's work");
132 both = open("Work for A and C");
133 for (const limb of [a, b, c]) link(milestone, limb);
134 link(a, a1);
135 link(b, b1);
136 link(c, c1);
137 link(a, both);
138 link(c, both);
139 }, 60_000);
140
141 afterAll(async () => {
142 servers.stop();
143 app.close();
144 await rm(dataDir, { recursive: true, force: true });
145 });
146
147 test("refused first: a reader, a crew agent and a read token cannot reorder", async () => {
148 const before = order();
149 const readyBefore = ready();
150 // A reader may look, and every row comes back refused.
151 const looked = previewLimb(app, bob, fresh(), c.number, { action: "raise" });
152 expect(looked.ok && looked.value.rows[0]?.outcome).toBe("refused");
153 const tried = await raise(bob, c);
154 expect(tried.ok && tried.value.rows[0]?.outcome).toBe("refused");
155 // An agent never applies; nobody signed in does not either.
156 const agent = await raise(mason, c);
157 expect(agent.ok ? "applied" : agent.error.code).toBe("forbidden");
158 const nobody = await applyLimb(app, undefined, fresh(), c.number, { action: "raise" });
159 expect(nobody.ok ? "applied" : nobody.error.code).toBe("unauthorized");
160 // The API and MCP: read and write tokens plan, only an admin token applies.
161 const path = `/api/v1/repos/alice/engine/milestones/${c.number}/limb`;
162 const apply = { action: "raise", dryRun: false };
163 expect((await post(tokenOf(alice, "ro"), path, apply)).status).toBe(403);
164 expect((await post(tokenOf(alice, "rw"), path, apply)).status).toBe(403);
165 expect((await post(tokenOf(mason, "admin"), path, apply)).status).toBe(403);
166 const reader = await post(tokenOf(bob, "admin"), path, apply);
167 expect(((await reader.json()) as any).rows[0].outcome).toBe("refused");
168 const args = { app: "alice/engine", issue: c.number, action: "raise", dryRun: false };
169 for (const token of [tokenOf(alice, "ro"), tokenOf(alice, "rw"), tokenOf(mason, "rw")])
170 expect((await tool(token, args)).error).toContain("forbidden");
171 expect((await tool(tokenOf(mason, "admin"), args)).error).toContain("forbidden");
172 // Nothing moved.
173 expect(order()).toEqual(before);
174 expect(ready()).toEqual(readyBefore);
175 expect(app.db.query("SELECT COUNT(*) AS n FROM limb_place").get()).toEqual({ n: 0 });
176 });
177
178 test("with no place set the ready order is what it was", () => {
179 expect(order()).toEqual([a.number, b.number, c.number]);
180 // `both` holds up two limbs, so it leads while nothing is placed.
181 expect(ready()).toEqual([both.number, a1.number, b1.number, c1.number]);
182 });
183
184 test("the dry run shows the new order and the top of the ready list, and writes nothing", async () => {
185 const plan = previewLimb(app, alice, fresh(), c.number, { action: "raise" });
186 if (!plan.ok) throw new Error(plan.error.message);
187 expect(plan.value.order?.before.map((i) => i.number)).toEqual([a.number, b.number, c.number]);
188 expect(plan.value.order?.after.map((i) => i.number)).toEqual([a.number, c.number, b.number]);
189 expect(plan.value.ready?.before.map((i) => i.number)).toEqual(ready().slice(0, 4));
190 expect(plan.value.ready?.after.map((i) => i.number)).toEqual([
191 both.number, a1.number, c1.number, b1.number,
192 ]);
193 expect(plan.value.rows.map((r) => [r.before, r.after])).toEqual([[3, 2]]);
194 expect(order()).toEqual([a.number, b.number, c.number]);
195 const api = await post(tokenOf(alice, "ro"), `/api/v1/repos/alice/engine/milestones/${c.number}/limb`, {
196 action: "raise",
197 });
198 expect(((await api.json()) as any).dryRun).toBe(true);
199 const mcp = await tool(tokenOf(alice, "ro"), { app: "alice/engine", issue: c.number, action: "raise" });
200 expect(mcp.value.dryRun).toBe(true);
201 expect(mcp.value.order.after.map((i: any) => i.number)).toEqual([a.number, c.number, b.number]);
202 expect(order()).toEqual([a.number, b.number, c.number]);
203 });
204
205 test("a raise is stored, the crew's ready order follows it, and an undo puts it back", async () => {
206 const raised = await raise(alice, c);
207 if (!raised.ok) throw new Error(raised.error.message);
208 expect(raised.value.rows.map((r) => r.outcome)).toEqual(["ok"]);
209 expect(order()).toEqual([a.number, c.number, b.number]);
210 // c1 comes before b1; `both` is under A and C and takes the higher (A).
211 expect(ready()).toEqual([both.number, a1.number, c1.number, b1.number]);
212 expect(await raise(alice, c)).toMatchObject({ ok: true });
213 expect(order()).toEqual([c.number, a.number, b.number]);
214 // Now C is first: its work leads A's, and `both` takes C's place.
215 expect(ready()).toEqual([both.number, c1.number, a1.number, b1.number]);
216 // The first limb cannot go higher: nothing to do, and it says so.
217 const top = await raise(alice, c);
218 expect(top.ok && top.value.rows[0]?.outcome).toBe("unchanged");
219 // Lower, then undo each: the order and the ready list are as they were.
220 const lowered = await raise(alice, c, "lower");
221 if (!lowered.ok) throw new Error(lowered.error.message);
222 expect(order()).toEqual([a.number, c.number, b.number]);
223 const undone = await undoFleetOp(app, alice, lowered.value.id);
224 expect(undone.ok && undone.value.rows[0]?.outcome).toBe("ok");
225 expect(order()).toEqual([c.number, a.number, b.number]);
226 const again = await undoFleetOp(app, alice, lowered.value.id);
227 expect(again.ok ? "undone" : again.error.code).toBe("already_undone");
228 // Undo the raises too, last first.
229 const ops = app.db
230 .query<{ id: string }, []>(
231 `SELECT id FROM fleet_operation WHERE verb = 'place' AND undo_of IS NULL AND undone_by IS NULL ORDER BY id DESC`,
232 )
233 .all();
234 for (const op of ops) await undoFleetOp(app, alice, op.id);
235 expect(order()).toEqual([a.number, b.number, c.number]);
236 });
237
238 test("within a limb the order is as today", async () => {
239 const a2 = open("A's second");
240 link(a, a2);
241 await raise(alice, c);
242 await raise(alice, c);
243 const inA = ready().filter((n) => [a1.number, a2.number].includes(n));
244 expect(inA).toEqual([a1.number, a2.number]);
245 expect(ready().indexOf(c1.number)).toBeLessThan(ready().indexOf(a1.number));
246 });
247
248 test("the place survives a restart", async () => {
249 const before = order();
250 expect(before[0]).toBe(c.number);
251 servers.stop();
252 app.close();
253 app = createApp({ dataDir, port: 0 });
254 servers = await serve(app);
255 base = servers.url;
256 expect(order()).toEqual(before);
257 expect(ready().indexOf(c1.number)).toBeLessThan(ready().indexOf(b1.number));
258 });
259
260 test("a leaf is not a limb; the page offers Raise and Lower to an admin only", async () => {
261 const leaf = previewLimb(app, alice, fresh(), a1.number, { action: "raise" });
262 expect(leaf.ok ? "planned" : leaf.error.code).toBe("bad_action");
263 const get = (who: string, path: string) =>
264 fetch(`${base}${path}`, { headers: { cookie: cookies[who]! }, redirect: "manual" });
265 const mine = await (await get("alice", `/alice/engine/milestones/${milestone.number}`)).text();
266 // The limbs stand in their order (C, A, B); the first has no Raise, the last no Lower.
267 expect(mine).toContain(`milestones/${a.number}/limb?action=raise`);
268 expect(mine).toContain(`milestones/${c.number}/limb?action=lower`);
269 expect(mine).not.toContain(`milestones/${c.number}/limb?action=raise`);
270 expect(mine).not.toContain(`milestones/${b.number}/limb?action=lower`);
271 expect(mine.indexOf("Limb C")).toBeLessThan(mine.indexOf("Limb A"));
272 expect(mine.indexOf("Limb A")).toBeLessThan(mine.indexOf("Limb B"));
273 const theirs = await (await get("bob", `/alice/engine/milestones/${milestone.number}`)).text();
274 expect(theirs).not.toContain("limb?action=raise");
275 // The preview page, then the form: the receipt is the fleet's.
276 const preview = await get("alice", `/alice/engine/milestones/${b.number}/limb?action=raise`);
277 expect(preview.status).toBe(200);
278 expect(await preview.text()).toContain("The new order");
279 const submitted = await fetch(`${base}/alice/engine/milestones/${b.number}/limb`, {
280 method: "POST",
281 headers: { cookie: cookies["alice"]!, origin: base },
282 body: new URLSearchParams({ action: "raise" }),
283 redirect: "manual",
284 });
285 expect(submitted.status).toBe(303);
286 expect(order()).toEqual([c.number, b.number, a.number]);
287 });
288 });
289
290 describe("readyNow", () => {
291 test("follows the places of the limbs above, in one pass over the graph", () => {
292 const issue = (n: number): Issue =>
293 ({ id: `i${n}`, number: n, state: "open", createdAt: `2026-01-0${n}`, sealed: false }) as unknown as Issue;
294 const graph: Graph = {
295 issues: [1, 2, 3, 4, 5].map(issue),
296 // 1 is the milestone over limbs 2 and 3; 2 waits for 4, 3 for 5.
297 edges: [
298 ["i1", "i2"], ["i1", "i3"], ["i2", "i4"], ["i3", "i5"],
299 ].map(([issueId, blockedById]) => ({ issueId: issueId!, blockedById: blockedById! })),
300 held: [],
301 deferred: new Map(),
302 unadopted: new Set(),
303 structural: new Set(),
304 places: new Map([["i3", 1], ["i2", 2]]),
305 };
306 expect(readyNow(graph).map((r) => r.issue.number)).toEqual([5, 4]);
307 expect(readyNow({ ...graph, places: new Map() }).map((r) => r.issue.number)).toEqual([4, 5]);
308 });
309 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs