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 #984
scout/forge:scout/760-raise-or-lower-a-limb-against-its-siblin → main 1 commit fork
14 files
changed +679
−28
docs/MCP.md +1 −1
| @@ -51,7 +51,7 @@ for a tunnel and a forge that sleeps. | ||
| 51 | 51 | | `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 | |
| 52 | 52 | | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`) | | |
| 53 | 53 | | `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 | | |
| 55 | 55 | | `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 | |
| 56 | 56 | | `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 | | |
| 57 | 57 | | `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. | ||
| 293 | 293 | - **Close as not doing** closes every open issue that is the limb's own, |
| 294 | 294 | the limb included, as `dropped`, with the reason said on each. What other |
| 295 | 295 | 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. | |
| 296 | 307 | |
| 297 | 308 | An umbrella or the gate is the plan's own and is not filed. A leaf beneath |
| 298 | 309 | 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. | |
| 301 | 311 | |
| 302 | 312 | 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"? }` | |
| 304 | 314 | and the MCP's `limb`, both a dry run unless `dryRun` is false. Applying and |
| 305 | 315 | undoing take an admin token of a person who administers the repository; an |
| 306 | 316 | agent may look and never apply. |
src/actions/fleet.ts +17 −1
| @@ -34,6 +34,7 @@ import { | ||
| 34 | 34 | } from "../core/issues.ts"; |
| 35 | 35 | import { listCrewRoles } from "../core/agents.ts"; |
| 36 | 36 | import { joinMany } from "../core/pulls.ts"; |
| 37 | import { readPlan } from "../core/milestones.ts"; | |
| 37 | 38 | import { pillarsOf, type Pillars } from "../core/pillars.ts"; |
| 38 | 39 | import { |
| 39 | 40 | canAdmin, |
| @@ -127,6 +128,7 @@ function loadTargets( | ||
| 127 | 128 | kind: FleetKind, |
| 128 | 129 | ids: readonly string[], |
| 129 | 130 | viewer?: User, |
| 131 | withSiblings = false, | |
| 130 | 132 | ): Target[] { |
| 131 | 133 | if (kind === "repo") { |
| 132 | 134 | const repos = getReposByIds(app.db, ids); |
| @@ -179,6 +181,18 @@ function loadTargets( | ||
| 179 | 181 | for (const [repoId, repo] of repos) pillars.set(repoId, pillarsOf(app.db, repo)); |
| 180 | 182 | const under = umbrellasOver(app, ids, [...pillars.values()]); |
| 181 | 183 | 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 | }; | |
| 182 | 196 | const pull = (id: string) => { |
| 183 | 197 | const p = pulls.get(id); |
| 184 | 198 | return p === undefined |
| @@ -208,6 +222,7 @@ function loadTargets( | ||
| 208 | 222 | pillars: pillars.get(repo.id)!, |
| 209 | 223 | under: under.get(id) ?? [], |
| 210 | 224 | peers, |
| 225 | ...siblingsOf(repo, issue), | |
| 211 | 226 | ...(viewer === undefined |
| 212 | 227 | ? {} |
| 213 | 228 | : { |
| @@ -355,7 +370,7 @@ function planOver( | ||
| 355 | 370 | query: string, |
| 356 | 371 | act: { name: string; verb: Verb; value: FleetValue }, |
| 357 | 372 | ): 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); | |
| 359 | 374 | const authority = authorityOf(app, actor, act.verb); |
| 360 | 375 | const { verb, value } = act; |
| 361 | 376 | const rows = targets.map((t) => |
| @@ -575,6 +590,7 @@ export async function undoFleetOp( | ||
| 575 | 590 | op.kind, |
| 576 | 591 | changed.map((r) => r.targetId), |
| 577 | 592 | person.value, |
| 593 | verb.siblings === true, | |
| 578 | 594 | ); |
| 579 | 595 | const byId = new Map(targets.map((t) => [t.id, t])); |
| 580 | 596 | const authority = authorityOf(app, person.value, verb); |
src/actions/limbs.ts +46 −1
| @@ -16,6 +16,11 @@ | ||
| 16 | 16 | * one reason said on each — and never what something outside the limb |
| 17 | 17 | * also waits for. |
| 18 | 18 | * |
| 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 | * | |
| 19 | 24 | * Who may is the fleet's rule, unchanged: a person who administers the |
| 20 | 25 | * repository; an agent may preview and never apply. |
| 21 | 26 | */ |
| @@ -23,9 +28,11 @@ | ||
| 23 | 28 | import type { App } from "../app.ts"; |
| 24 | 29 | import type { FleetValue, Operation } from "../core/fleet_ops.ts"; |
| 25 | 30 | import type { Issue } from "../core/issues.ts"; |
| 31 | import { readyNow, repoGraph } from "../core/dependencies.ts"; | |
| 26 | 32 | import { readPlan } from "../core/milestones.ts"; |
| 27 | 33 | import { isStructural, pillarsOf } from "../core/pillars.ts"; |
| 28 | 34 | import { canRead, type Repo } from "../core/repos.ts"; |
| 35 | import { sealedScope } from "../core/sealed.ts"; | |
| 29 | 36 | import type { User } from "../core/users.ts"; |
| 30 | 37 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 31 | 38 | import { |
| @@ -35,7 +42,7 @@ import { | ||
| 35 | 42 | type Plan, |
| 36 | 43 | } from "./fleet.ts"; |
| 37 | 44 | |
| 38 | export const LIMB_ACTIONS = ["defer", "resume", "close"] as const; | |
| 45 | export const LIMB_ACTIONS = ["defer", "resume", "close", "raise", "lower"] as const; | |
| 39 | 46 | export type LimbAction = (typeof LIMB_ACTIONS)[number]; |
| 40 | 47 | |
| 41 | 48 | export const isLimbAction = (value: unknown): value is LimbAction => |
| @@ -62,8 +69,15 @@ export interface LimbReach { | ||
| 62 | 69 | readonly taken: readonly LimbIssue[]; |
| 63 | 70 | /** For `defer` and `close`: what beneath it stays, because something outside the limb still waits for it. */ |
| 64 | 71 | 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[] }; | |
| 65 | 76 | } |
| 66 | 77 | |
| 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 | ||
| 67 | 81 | const brief = (issue: Issue): LimbIssue => ({ |
| 68 | 82 | number: issue.number, |
| 69 | 83 | title: issue.title, |
| @@ -93,6 +107,37 @@ function shape( | ||
| 93 | 107 | return fail("not_found", "no such milestone here"); |
| 94 | 108 | const limb = brief(rows.own[0]); |
| 95 | 109 | 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 | } | |
| 96 | 141 | if (request.action === "close") { |
| 97 | 142 | const reason = (request.reason ?? "").trim(); |
| 98 | 143 | if (reason === "") |
src/core/dependencies.ts +9 −1
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import type { Database } from "bun:sqlite"; |
| 12 | 12 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 13 | 13 | import { getIssuesByIds, type CloseReason, type Issue } from "./issues.ts"; |
| 14 | import { chainsOf, compareChains, loadPlaces } from "./limb_places.ts"; | |
| 14 | 15 | import { pillarsOf, structuralIds } from "./pillars.ts"; |
| 15 | 16 | import { getRepoById } from "./repos.ts"; |
| 16 | 17 | import { unadoptedAmong } from "../crew/direct.ts"; |
| @@ -215,6 +216,8 @@ export interface Graph { | ||
| 215 | 216 | * words, as every surface says it (`deferredWhy`). |
| 216 | 217 | */ |
| 217 | 218 | 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>; | |
| 218 | 221 | } |
| 219 | 222 | |
| 220 | 223 | /** |
| @@ -323,6 +326,7 @@ export function repoGraph( | ||
| 323 | 326 | unadopted: |
| 324 | 327 | repo === undefined ? new Set() : unadoptedAmong(db, repo, issues), |
| 325 | 328 | structural: set === undefined ? new Set() : structuralIds(set), |
| 329 | places: loadPlaces(db, repoId), | |
| 326 | 330 | edges: kept, |
| 327 | 331 | held: heldRows |
| 328 | 332 | .filter((r) => present.has(r.issue_id) && present.has(r.blocked_by_id)) |
| @@ -484,6 +488,8 @@ function clearNow(graph: Graph): Ranked[] { | ||
| 484 | 488 | const holds = holdsUpMap(graph, open); |
| 485 | 489 | const waits = waitsForMap(graph, open); |
| 486 | 490 | 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) ?? []; | |
| 487 | 493 | return graph.issues |
| 488 | 494 | .filter( |
| 489 | 495 | (i) => |
| @@ -498,6 +504,7 @@ function clearNow(graph: Graph): Ranked[] { | ||
| 498 | 504 | })) |
| 499 | 505 | .sort( |
| 500 | 506 | (a, b) => |
| 507 | compareChains(chain(a.issue.id), chain(b.issue.id)) || | |
| 501 | 508 | b.holdsUp - a.holdsUp || |
| 502 | 509 | a.issue.createdAt.localeCompare(b.issue.createdAt), |
| 503 | 510 | ); |
| @@ -505,7 +512,8 @@ function clearNow(graph: Graph): Ranked[] { | ||
| 505 | 512 | |
| 506 | 513 | /** |
| 507 | 514 | * 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 | |
| 509 | 517 | * reader's suggestion only once someone who writes here adopted it, and |
| 510 | 518 | * never the plan's own furniture: an umbrella or the Later gate is not |
| 511 | 519 | * 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 @@ | ||
| 16 | 16 | import type { Database } from "bun:sqlite"; |
| 17 | 17 | import { deferredIn, repoGraph, type Graph } from "./dependencies.ts"; |
| 18 | 18 | import type { Issue } from "./issues.ts"; |
| 19 | import { UNPLACED } from "./limb_places.ts"; | |
| 19 | 20 | import { |
| 20 | 21 | isStructural, |
| 21 | 22 | LATER, |
| @@ -122,6 +123,12 @@ export interface Plan { | ||
| 122 | 123 | * Nothing for a number that is no issue here. |
| 123 | 124 | */ |
| 124 | 125 | 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; | |
| 125 | 132 | /** |
| 126 | 133 | * What deferring this issue would take with it: the open issues that |
| 127 | 134 | * would stop being ready, itself included, and, beneath it, the ones that |
| @@ -355,6 +362,9 @@ export function readPlan( | ||
| 355 | 362 | }; |
| 356 | 363 | |
| 357 | 364 | 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); | |
| 358 | 368 | |
| 359 | 369 | const top: Issue[] = |
| 360 | 370 | set.pillars.length > 0 |
| @@ -371,8 +381,25 @@ export function readPlan( | ||
| 371 | 381 | ), |
| 372 | 382 | ); |
| 373 | 383 | |
| 384 | top.sort(placed); | |
| 385 | ||
| 374 | 386 | return { |
| 375 | 387 | 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 | }, | |
| 376 | 403 | limb(number: number): { own: Issue[]; shared: Issue[] } | undefined { |
| 377 | 404 | const issue = byNumber.get(number); |
| 378 | 405 | if (issue === undefined) return undefined; |
| @@ -534,7 +561,7 @@ export function readPlan( | ||
| 534 | 561 | .filter((pull) => pull.closes.some((n) => numbers.has(n))) |
| 535 | 562 | .map(({ number: n, title, at }) => ({ number: n, title, at })), |
| 536 | 563 | estimate, |
| 537 | limbs: children.filter(isLimb).map(limbOf), | |
| 564 | limbs: children.filter(isLimb).sort(placed).map(limbOf), | |
| 538 | 565 | leaves: children |
| 539 | 566 | .filter((c) => !isLimb(c)) |
| 540 | 567 | .map((c) => { |
src/core/schema.ts +8
| @@ -1540,4 +1540,12 @@ export const migrations: readonly string[] = [ | ||
| 1540 | 1540 | SELECT RAISE(ABORT, 'a sealed repository is never public'); |
| 1541 | 1541 | END; |
| 1542 | 1542 | `, |
| 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 | `, | |
| 1543 | 1551 | ]; |
src/fleet/verbs.ts +46
| @@ -23,6 +23,7 @@ import { cancelRepoRun, requeueRepoRun } from "../actions/runs.ts"; | ||
| 23 | 23 | import { isCrew } from "../core/agents.ts"; |
| 24 | 24 | import { mergePull } from "../actions/pulls.ts"; |
| 25 | 25 | import { bringUpToDate } from "../crew/autonomy.ts"; |
| 26 | import { placeLimbs } from "../core/limb_places.ts"; | |
| 26 | 27 | import { getHold } from "../core/holds.ts"; |
| 27 | 28 | import { recordInteraction, removeDismissals } from "../core/interactions.ts"; |
| 28 | 29 | import { getPull } from "../core/pulls.ts"; |
| @@ -69,6 +70,9 @@ export interface Target { | ||
| 69 | 70 | readonly pillars?: Pillars; |
| 70 | 71 | /** For an issue: the numbers of the umbrellas that wait for it directly, ascending. */ |
| 71 | 72 | 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[]; | |
| 72 | 76 | /** For an issue: the ids of every row this operation is over, itself included. */ |
| 73 | 77 | readonly peers?: ReadonlySet<string>; |
| 74 | 78 | } |
| @@ -80,6 +84,8 @@ export interface Verb { | ||
| 80 | 84 | parse(app: App, value: unknown): Result<FleetValue, string>; |
| 81 | 85 | /** True when the verb changes the actor's own state, not the repository's: only they undo it. */ |
| 82 | 86 | readonly personal?: boolean; |
| 87 | /** True when the verb reads a limb's siblings (`Target.place`): loaded only for it. */ | |
| 88 | readonly siblings?: boolean; | |
| 83 | 89 | read(target: Target): FleetValue; |
| 84 | 90 | next(before: FleetValue, value: FleetValue): FleetValue; |
| 85 | 91 | /** 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> = { | ||
| 676 | 682 | ); |
| 677 | 683 | }, |
| 678 | 684 | }, |
| 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 | }, | |
| 679 | 725 | }; |
src/http/api.ts +2 −2
| @@ -2442,7 +2442,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2442 | 2442 | }, |
| 2443 | 2443 | ); |
| 2444 | 2444 | // 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 | |
| 2446 | 2446 | // read credential, an admin token to apply, the receipt in |
| 2447 | 2447 | // /api/v1/fleet/ops/:id and its undo at …/undo. |
| 2448 | 2448 | router.add( |
| @@ -2457,7 +2457,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2457 | 2457 | const number = positiveInt(ctx.params.number); |
| 2458 | 2458 | if (!repo || number === undefined) return notFound(); |
| 2459 | 2459 | 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"); | |
| 2461 | 2461 | const request = { |
| 2462 | 2462 | action: input.action, |
| 2463 | 2463 | ...(typeof input.reason === "string" ? { reason: input.reason } : {}), |
src/http/mcp.ts +3 −3
| @@ -1236,7 +1236,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1236 | 1236 | { |
| 1237 | 1237 | name: "limb", |
| 1238 | 1238 | 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.", | |
| 1240 | 1240 | inputSchema: { |
| 1241 | 1241 | type: "object", |
| 1242 | 1242 | properties: { |
| @@ -1246,7 +1246,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1246 | 1246 | minimum: 1, |
| 1247 | 1247 | description: "The limb: the number of its issue.", |
| 1248 | 1248 | }, |
| 1249 | action: { type: "string", enum: ["defer", "resume", "close", "undo"] }, | |
| 1249 | action: { type: "string", enum: ["defer", "resume", "close", "raise", "lower", "undo"] }, | |
| 1250 | 1250 | reason: { |
| 1251 | 1251 | type: "string", |
| 1252 | 1252 | description: "For close: why it is not being done, in one sentence.", |
| @@ -1290,7 +1290,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 1290 | 1290 | !Number.isInteger(number) || |
| 1291 | 1291 | number < 1 |
| 1292 | 1292 | ) |
| 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"); | |
| 1294 | 1294 | const request = { |
| 1295 | 1295 | action: args["action"], |
| 1296 | 1296 | ...(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 }> = { | ||
| 50 | 50 | does: "Every open issue that only this limb needs closes as not doing, with your reason said on each.", |
| 51 | 51 | go: "Close as not doing", |
| 52 | 52 | }, |
| 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 | }, | |
| 53 | 63 | }; |
| 54 | 64 | |
| 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 | ||
| 55 | 68 | const shown = (value: FleetValue): string => |
| 56 | 69 | value === null |
| 57 | 70 | ? "nothing" |
| @@ -128,6 +141,21 @@ function rowList( | ||
| 128 | 141 | </ul>`; |
| 129 | 142 | } |
| 130 | 143 | |
| 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 | ||
| 131 | 159 | function requestOf( |
| 132 | 160 | action: LimbAction, |
| 133 | 161 | get: (name: string) => string, |
| @@ -179,6 +207,7 @@ export function limbPreviewPage(ctx: Ctx): Response { | ||
| 179 | 207 | } |
| 180 | 208 | const p = plan.value; |
| 181 | 209 | const willWrite = p.counts.change > 0; |
| 210 | const moving = action === "raise" || action === "lower"; | |
| 182 | 211 | const pillars = |
| 183 | 212 | action === "resume" ? pillarsOf(ctx.app.db, repo).pillars : []; |
| 184 | 213 | const body = html`${repoHeader(ctx, repo, "map")} |
| @@ -189,6 +218,30 @@ export function limbPreviewPage(ctx: Ctx): Response { | ||
| 189 | 218 | <h1>${words.ask} “${p.limb.title}”?</h1> |
| 190 | 219 | <p>${words.does}</p> |
| 191 | 220 | </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 | )} | |
| 192 | 245 | ${when( |
| 193 | 246 | p.taken.length > 0, |
| 194 | 247 | () => |
| @@ -213,12 +266,14 @@ export function limbPreviewPage(ctx: Ctx): Response { | ||
| 213 | 266 | ${issueList(base, p.kept)} |
| 214 | 267 | </section>`, |
| 215 | 268 | )} |
| 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>`} | |
| 222 | 277 | ${willWrite |
| 223 | 278 | ? html`<form |
| 224 | 279 | method="post" |
| @@ -268,7 +323,9 @@ export function limbPreviewPage(ctx: Ctx): Response { | ||
| 268 | 323 | </div> |
| 269 | 324 | </form>` |
| 270 | 325 | : 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."} | |
| 272 | 329 | <a href="${milestoneHref(base, number)}">Back</a> |
| 273 | 330 | </p>`}`; |
| 274 | 331 | return page({ |
| @@ -313,6 +370,7 @@ export async function limbSubmit(ctx: Ctx): Promise<Response> { | ||
| 313 | 370 | function done(op: Operation): string { |
| 314 | 371 | if (op.undoOf !== null) return "Undone"; |
| 315 | 372 | if (op.verb === "drop") return "Closed as not doing"; |
| 373 | if (op.verb === "place") return op.value === "raise" ? "Raised" : "Lowered"; | |
| 316 | 374 | return op.value === "later" ? "Deferred" : "Resumed"; |
| 317 | 375 | } |
| 318 | 376 |
src/web/pages/milestones.ts +44 −8
| @@ -101,7 +101,12 @@ function weightWords(limb: Limb): Html { | ||
| 101 | 101 | } |
| 102 | 102 | |
| 103 | 103 | /** 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 { | |
| 105 | 110 | const w = limb.weight; |
| 106 | 111 | return html`<li class="ms-limb" data-trim="${limb.trim === undefined ? "no" : "yes"}"> |
| 107 | 112 | <a class="ms-name" href="${milestoneHref(base, limb.issue.number)}" |
| @@ -120,9 +125,38 @@ function limbLine(base: string, limb: Limb): Html { | ||
| 120 | 125 | (why) => |
| 121 | 126 | html`<span class="ms-trim small">A candidate to trim: ${why}.</span>`, |
| 122 | 127 | )} |
| 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 | )} | |
| 123 | 144 | </li>`; |
| 124 | 145 | } |
| 125 | 146 | |
| 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 | ||
| 126 | 160 | /** GET /:owner/:name/milestones — the plan, collapsed to its limbs. */ |
| 127 | 161 | export function milestonesPage(ctx: Ctx): Response { |
| 128 | 162 | const repo = loadRepo(ctx); |
| @@ -144,9 +178,9 @@ export function milestonesPage(ctx: Ctx): Response { | ||
| 144 | 178 | Nothing here waits for anything yet, so there is no milestone to |
| 145 | 179 | show. <a href="${base}/map">See the map</a>. |
| 146 | 180 | </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>`}`; | |
| 150 | 184 | return page({ |
| 151 | 185 | ctx, |
| 152 | 186 | title: `Milestones · ${repo.name}`, |
| @@ -208,6 +242,7 @@ function milestoneBody( | ||
| 208 | 242 | m: Milestone, |
| 209 | 243 | names: boolean, |
| 210 | 244 | actions: Html | null, |
| 245 | admin: boolean, | |
| 211 | 246 | ): Html { |
| 212 | 247 | const base = repoBase(repo); |
| 213 | 248 | const issue = (number: number, title: string): Html => |
| @@ -256,9 +291,9 @@ function milestoneBody( | ||
| 256 | 291 | () => |
| 257 | 292 | html`<section class="ms-section" id="ms-limbs"> |
| 258 | 293 | <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> | |
| 262 | 297 | </section>`, |
| 263 | 298 | )} |
| 264 | 299 | ${when( |
| @@ -409,7 +444,7 @@ export function milestonePage(ctx: Ctx): Response { | ||
| 409 | 444 | crumbs: crumbsFor(repo), |
| 410 | 445 | palette: repoPalette(ctx, repo), |
| 411 | 446 | 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))}`, | |
| 413 | 448 | styleCss: milestonesCss, |
| 414 | 449 | }); |
| 415 | 450 | } |
| @@ -487,6 +522,7 @@ export const milestonesCss = /* css */ ` | ||
| 487 | 522 | .ms-bar::-webkit-progress-value { background: var(--success); } |
| 488 | 523 | .ms-bar::-moz-progress-bar { background: var(--success); } |
| 489 | 524 | .ms-weight, .ms-trim { grid-column: 1 / -1; } |
| 525 | .ms-move { grid-column: 1 / -1; display: flex; gap: 16px; padding-top: 2px; } | |
| 490 | 526 | .ms-trim { color: var(--attn); margin: 0; } |
| 491 | 527 | .ms-top { display: grid; gap: 8px; max-width: 640px; } |
| 492 | 528 | .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 | }); |
new above
offline