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

The owner approves the plan: the planner proposes a wave, the owner nods or redirects in one tap #1503

Closed opened this in answer to
Closed without merging

scout/forge:scout/1114-the-owner-approves-the-plan-the-planner → main 11 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
28 files changed +1633 −35
README.md +6
@@ -80,6 +80,12 @@ sees `Reduced protection: …` in one line, under the filter on the terminal's
8080 first screen and in the web footer; nobody else does, and a fully protected
8181 forge shows nothing.
8282
83 Where a repository asks for the owner's nod (`plansNeedNod`), the crew's planner
84 proposes a wave instead of opening issues. Decide it in the inbox card, on
85 `/:owner/:name/map` (a wave set aside stays there), in the terminal with `M` in
86 the repository, or over MCP (`plan` lists the waves, `decide` approves,
87 redirects or sets one aside).
88
8389 Your SSH key is your identity. A key the forge knows signs you straight in; any
8490 other key browses public repos as a guest and can press `s` to sign in with a
8591 username and password — which links that key to your account, so the next
docs/MCP.md +2 −1
@@ -58,7 +58,8 @@ for a tunnel and a forge that sleeps.
5858 | `link` | `{ app, issue, blockedBy }`: the issue waits for another; loops and cross-repository are refused | yes |
5959 | `unlink` | `{ app, issue, blockedBy }`: the issue stops waiting for it | yes |
6060 | `hold` | `{ app, pull, why?, release?, dryRun? }`: hold a pull so no rule reviews or lands it, or let it go; a person who can write, never an agent; plans unless `dryRun: false` | yes |
61 | `plan` | `{ app, issues }`: open up to 12 linked issues, all or none (see below) | yes |
61 | `plan` | `{ app, issues, title?, why?, milestone? }`: open up to 12 linked issues, all or none (see below); on the crew, where the app's plans need a nod, it proposes a wave (3–6 issues) and opens nothing; without `issues`, the waves waiting | yes |
62 | `decide` | `{ app, wave, decision, words? }`: approve a proposed wave (its issues open, linked), redirect it (`words`; the planner re-plans from them) or set it aside (`later`); a person who can write, never an agent | yes |
6263
6364 Answers are JSON in a text block; most carry a `says` sentence short enough
6465 to relay as it is.
docs/PLANNING.md +14
@@ -565,3 +565,17 @@ not confirm its own plan. Split also moves the parent's blocked-by edges to
565565 the issues named in `into` (a child that would make a loop is skipped), and
566566 the parent waits for nothing. Reopening clears the reason. Closes that
567567 predate reasons count as done.
568
569 ## The owner's nod (#1114)
570
571 Beside autonomy, a repository setting — *Plans need a nod*, on by default —
572 changes what the crew's planner may do. With it on, the planner opens no issues:
573 `POST /api/v1/repos/:owner/:name/plan` (or the MCP `plan`) keeps a **wave** — a
574 title, a one-line why, the milestone it moves, three to six issues in order —
575 and the owner's inbox shows it as one card. **Approve** opens the issues, linked
576 as the proposal named, ready; **Redirect** (a text box) puts the words on the
577 direction issue and hands it back to the planner; **Later** sets it aside.
578 `decide` (MCP) and `POST …/waves/:id/decide` do the same. A person's own plan
579 opens at once; an agent never decides a wave. While a wave waits, the planner is
580 not asked for another. The map reads as waves under their milestones (what
581 landed, what is left); `?graph=1` is the whole graph.
scripts/gate.ts +2
@@ -141,6 +141,7 @@ export const GATE: readonly string[] = [
141141 "test/asks-expiry.test.ts",
142142 "test/asks-rank.test.ts",
143143 "test/plan-pillars.test.ts",
144 "test/plan-nod.test.ts",
144145 "test/plan-route.test.ts",
145146 "test/planner-declined.test.ts",
146147 "test/feed.test.ts",
@@ -346,6 +347,7 @@ export const EXCLUDED: readonly Exclusion[] = [
346347 { file: "test/tui-size.test.ts", reason: "not yet admitted", issue: 261 },
347348 { file: "test/tui-widgets.test.ts", reason: "not yet admitted", issue: 261 },
348349 { file: "test/tui-width.test.ts", reason: "not yet admitted", issue: 261 },
350 { file: "test/tui-waves.test.ts", reason: "not yet admitted", issue: 261 },
349351 {
350352 file: "test/tui-workflows.test.ts",
351353 reason: "not yet admitted",
src/actions/plan.ts +24 −2
@@ -186,12 +186,21 @@ function loopAt(items: readonly PlanItem[]): string | undefined {
186186 return undefined;
187187 }
188188
189 export function openPlan(
189 /** What a good plan was checked against: the issues it waits for and the pillars it serves. */
190 interface Vetted {
191 readonly existing: Map<number, Issue>;
192 readonly serves: Map<string, Pillar>;
193 readonly gate: Issue | undefined;
194 readonly later: Issue | undefined;
195 }
196
197 /** Every refusal a plan can earn, found before anything is written. */
198 export function vetPlan(
190199 app: App,
191200 actor: User | undefined,
192201 repo: Repo,
193202 items: readonly PlanItem[],
194 ): Result<Planned, PlanError> {
203 ): Result<Vetted, PlanError> {
195204 if (!actor || !canRead(app.db, repo, actor))
196205 return refuse("not_found", "no such app or repository (owner/name)");
197206 if (!canWrite(app.db, repo, actor) && !isCrew(app.db, repo.id, actor.id))
@@ -258,6 +267,19 @@ export function openPlan(
258267 `"${item.key}" names no pillar: give it ${namesOf(pillars)}, or later: true and why`,
259268 );
260269 }
270 return ok({ existing, serves, gate, later });
271 }
272
273 export function openPlan(
274 app: App,
275 actor: User | undefined,
276 repo: Repo,
277 items: readonly PlanItem[],
278 ): Result<Planned, PlanError> {
279 const vetted = vetPlan(app, actor, repo, items);
280 if (!vetted.ok) return vetted;
281 const { existing, serves, gate, later } = vetted.value;
282 if (!actor) return refuse("not_found", "no such app or repository (owner/name)");
261283
262284 const opened: { key: string; number: number }[] = [];
263285 /** The links an item's purpose adds: [the issue that waits, what it waits for]. */
src/actions/repos.ts +6 −1
@@ -246,7 +246,11 @@ export async function updateRepoSettings(
246246 if (!admin.ok) return admin;
247247 // Who the crew obeys is a person's call: an agent never widens it, even
248248 // one on a team that administers the repository (`crew/direct.ts`).
249 if (settings.crewOutsiders !== undefined && admin.value.kind === "agent")
249 if (
250 (settings.crewOutsiders !== undefined ||
251 settings.plansNeedNod !== undefined) &&
252 admin.value.kind === "agent"
253 )
250254 return err("not_found");
251255 // The work on a sealed report stays private until it merges into its
252256 // base, whoever owns it (`core/sealed.ts`).
@@ -270,6 +274,7 @@ export async function updateRepoSettings(
270274 "requireReview",
271275 "requireChecks",
272276 "crewOutsiders",
277 "plansNeedNod",
273278 ] as const
274279 ).filter((k) => settings[k] !== undefined && settings[k] !== repo[k]);
275280 app.bus.append({
src/actions/waves.ts added +276
@@ -0,0 +1,276 @@
1 /**
2 * The owner approves the plan (#1114). Where a repository's plans need a
3 * nod, the crew's planner does not open issues: it proposes a wave — a
4 * title, a one-line why, the milestone it moves, three to six issues in
5 * order — and a person approves it (the issues open, linked, ready),
6 * redirects it (the planner re-plans from their words), or sets it aside
7 * for later. A person who writes here is the owner of their own plan: what
8 * they open themselves opens at once.
9 */
10
11 import type { App } from "../app.ts";
12 import { isCrew, listCrewRoles } from "../core/agents.ts";
13 import { canRead, canWrite, type Repo } from "../core/repos.ts";
14 import { MAX_BODY, getIssueById, type Issue } from "../core/issues.ts";
15 import type { User } from "../core/users.ts";
16 import {
17 createWave,
18 decideWave as writeDecision,
19 getWave,
20 listWaves,
21 type Wave,
22 } from "../core/waves.ts";
23 import { ensureDirectionIssue } from "../crew/autonomy.ts";
24 import { err, ok, type Result } from "../kernel/result.ts";
25 import { addComment, assignIssue } from "./issues.ts";
26 import {
27 openPlan,
28 parsePlan,
29 vetPlan,
30 WHY_MAX,
31 type PlanError,
32 type Planned,
33 } from "./plan.ts";
34
35 export const WAVE_MIN = 3;
36 export const WAVE_MAX = 6;
37 export const WAVE_TITLE_MAX = 120;
38 export const MILESTONE_MAX = 80;
39 export const WORDS_MAX = 2000;
40
41 const refuse = (error: string, message: string) => err({ error, message });
42
43 /** Whether this actor's plan waits for a nod: the crew's, where the repository asks for one. */
44 export const needsNod = (app: App, repo: Repo, actor: User): boolean =>
45 repo.plansNeedNod && actor.kind === "agent" && isCrew(app.db, repo.id, actor.id);
46
47 /** One line of text, bounded: the boundary for a title, a why, a milestone. */
48 function line(raw: unknown, what: string, max: number): Result<string, PlanError> {
49 if (typeof raw !== "string" || raw.trim() === "")
50 return refuse("invalid", `a wave needs a ${what}`);
51 const flat = raw.trim().replace(/\s+/g, " ");
52 if (flat.length > max)
53 return refuse("invalid", `the ${what} is at most ${max} characters`);
54 return ok(flat);
55 }
56
57 /** A wave as the wire gave it, checked, vetted against the repository, and kept. */
58 export function proposeWave(
59 app: App,
60 actor: User | undefined,
61 repo: Repo,
62 raw: {
63 title: unknown;
64 why: unknown;
65 milestone: unknown;
66 issues: unknown;
67 },
68 ): Result<Wave, PlanError> {
69 const title = line(raw.title, "title", WAVE_TITLE_MAX);
70 if (!title.ok) return title;
71 const why = line(raw.why, "why (one line)", WHY_MAX);
72 if (!why.ok) return why;
73 const milestone = line(raw.milestone, "milestone", MILESTONE_MAX);
74 if (!milestone.ok) return milestone;
75 const items = parsePlan(raw.issues);
76 if (!items.ok) return items;
77 if (items.value.length < WAVE_MIN || items.value.length > WAVE_MAX)
78 return refuse(
79 "wave_size",
80 `a wave is ${WAVE_MIN} to ${WAVE_MAX} issues, in order; this has ${items.value.length}`,
81 );
82 // Refused now, with the item named, rather than when the owner nods.
83 const vetted = vetPlan(app, actor, repo, items.value);
84 if (!vetted.ok) return vetted;
85 const wave = createWave(app.db, {
86 repoId: repo.id,
87 authorId: actor!.id,
88 title: title.value,
89 why: why.value,
90 milestone: milestone.value,
91 items: items.value,
92 });
93 app.bus.append({
94 kind: "wave.proposed",
95 repoId: repo.id,
96 actorId: actor!.id,
97 payload: { wave: wave.id, title: wave.title },
98 });
99 return ok(wave);
100 }
101
102 export type Decision = "approve" | "redirect" | "later";
103
104 export interface Decided {
105 readonly wave: Wave;
106 readonly planned?: Planned;
107 }
108
109 /** A wave of a repository the actor writes, or the refusal that does not say which. */
110 function waveOf(
111 app: App,
112 actor: User | undefined,
113 repo: Repo,
114 waveId: string,
115 ): Result<Wave, PlanError> {
116 const wave = getWave(app.db, waveId);
117 if (!actor || !canRead(app.db, repo, actor) || wave?.repoId !== repo.id)
118 return refuse("not_found", "no such wave here");
119 // The nod is a person's: an agent proposes and never decides.
120 if (actor.kind === "agent" || !canWrite(app.db, repo, actor))
121 return refuse("forbidden", "only a person who writes here decides a wave");
122 return ok(wave);
123 }
124
125 /** Approve, redirect or set a wave aside. Each is one call; nothing half-happens. */
126 export function decideWave(
127 app: App,
128 actor: User | undefined,
129 repo: Repo,
130 waveId: string,
131 decision: unknown,
132 words: unknown = "",
133 ): Result<Decided, PlanError> {
134 const found = waveOf(app, actor, repo, waveId);
135 if (!found.ok) return found;
136 const wave = found.value;
137 const by = actor!;
138 if (wave.state === "approved" || wave.state === "redirected")
139 return refuse("decided", `this wave was already ${wave.state}`);
140 if (decision === "approve") {
141 const planned = openPlan(app, by, repo, wave.items);
142 if (!planned.ok) return planned;
143 const numbers = Object.fromEntries(
144 planned.value.opened.map((o) => [o.key, o.number]),
145 );
146 writeDecision(app.db, wave.id, "approved", by.id, { numbers });
147 app.bus.append({
148 kind: "wave.approved",
149 repoId: repo.id,
150 actorId: by.id,
151 payload: { wave: wave.id, numbers: planned.value.opened.map((o) => o.number) },
152 });
153 return ok({ wave: getWave(app.db, wave.id)!, planned: planned.value });
154 }
155 if (decision === "later") {

later appends no bus event, unlike approve and redirect. A wave set aside from the terminal or MCP never refreshes a web viewer. Append wave.later here.

156 writeDecision(app.db, wave.id, "later", by.id);
157 app.bus.append({
158 kind: "wave.later",
159 repoId: repo.id,
160 actorId: by.id,
161 payload: { wave: wave.id },
162 });
163 return ok({ wave: getWave(app.db, wave.id)! });
164 }
165 if (decision !== "redirect")
166 return refuse("invalid", "decision is approve, redirect or later");
167 if (typeof words !== "string" || words.trim() === "")
168 return refuse("empty_words", "say where the plan should go instead (words)");
169 if (words.length > WORDS_MAX || words.length > MAX_BODY)
170 return refuse("invalid", `words are at most ${WORDS_MAX} characters`);
171 const sent = replanFrom(app, by, repo, wave, words.trim());
172 if (!sent.ok) return sent;
173 writeDecision(app.db, wave.id, "redirected", by.id, { words: words.trim() });
174 app.bus.append({
175 kind: "wave.redirected",
176 repoId: repo.id,
177 actorId: by.id,
178 payload: { wave: wave.id },
179 });
180 return ok({ wave: getWave(app.db, wave.id)! });
181 }
182
183 /**
184 * The planner, asked again with the owner's words: they go on the direction
185 * issue as a comment — which is where the planner's task is read from, so
186 * the words are in its prompt — and the planner is handed the issue, or
187 * woken on it when it already holds it (`crew/dispatch.ts`).
188 */
189 function replanFrom(
190 app: App,
191 by: User,
192 repo: Repo,
193 wave: Wave,
194 words: string,
195 ): Result<Issue, PlanError> {
196 const planner = listCrewRoles(app.db, repo.id).find((c) => c.role === "planner");
197 if (planner === undefined)
198 return refuse("no_planner", "there is no planner on this crew to re-plan");
199 const direction = ensureDirectionIssue(app, by, repo);
200 if (direction === undefined)
201 return refuse("no_direction", "this repository has no direction to plan from");
202 const said = addComment(
203 app,
204 by,
205 repo,
206 direction,
207 `Redirect — you proposed the wave “${wave.title}”. Do not open it. Plan again from these words:\n\n${words}`,
208 );
209 if (!said.ok) return refuse("invalid", `could not send the words: ${String(said.error)}`);
210 if (direction.assigneeId !== planner.agent.user.id) {
211 if (direction.assigneeId !== null) {
212 const cleared = assignIssue(app, by, repo, direction, null);
213 if (!cleared.ok)
214 return refuse("invalid", `could not hand it back: ${String(cleared.error)}`);
215 }
216 const current = getIssueById(app.db, direction.id) ?? direction;
217 const assigned = assignIssue(app, by, repo, current, planner.agent.user);
218 if (!assigned.ok)
219 return refuse("invalid", `could not hand it back: ${String(assigned.error)}`);
220 }
221 return ok(direction);
222 }
223
224 /** The waves still waiting for a nod (or set aside for later), oldest first. */
225 export const waitingWaves = (app: App, repo: Repo): Wave[] =>
226 listWaves(app.db, repo.id, ["pending", "later"]);
227
228 /** What a plan call came to: a wave waiting for a nod, or issues opened. */
229 export type Submitted =
230 | { readonly proposed: Wave }
231 | { readonly opened: Planned };
232
233 /**
234 * One door for a plan. The crew's plan, where plans need a nod, becomes a
235 * wave and opens nothing; anyone else who writes here opens it at once.
236 */
237 export function submitPlan(
238 app: App,
239 actor: User | undefined,
240 repo: Repo,
241 raw: { title?: unknown; why?: unknown; milestone?: unknown; issues: unknown },
242 ): Result<Submitted, PlanError> {
243 if (actor !== undefined && needsNod(app, repo, actor)) {
244 const wave = proposeWave(app, actor, repo, {
245 title: raw.title,
246 why: raw.why,
247 milestone: raw.milestone,
248 issues: raw.issues,
249 });
250 return wave.ok ? ok({ proposed: wave.value }) : wave;
251 }
252 const items = parsePlan(raw.issues);
253 if (!items.ok) return items;
254 const planned = openPlan(app, actor, repo, items.value);
255 return planned.ok ? ok({ opened: planned.value }) : planned;
256 }
257
258 /** A wave as data, for the API and the MCP: what a person (or Grok in the car) reads before saying yes. */
259 export function waveJson(wave: Wave) {
260 return {
261 id: wave.id,
262 title: wave.title,
263 why: wave.why,
264 milestone: wave.milestone,
265 state: wave.state,
266 issues: wave.items.map((item, i) => ({
267 order: i + 1,
268 key: item.key,
269 title: item.title,
270 blockedBy: item.blockedBy,
271 ...(wave.numbers[item.key] === undefined ? {} : { number: wave.numbers[item.key] }),
272 })),
273 ...(wave.words === "" ? {} : { words: wave.words }),
274 proposedAt: wave.createdAt,
275 };
276 }
src/core/repos.ts +12 −1
@@ -116,6 +116,11 @@ export interface Repo {
116116 * default; on a public repository it hands strangers the owner's budget.
117117 */
118118 readonly crewOutsiders: boolean;
119 /**
120 * "Plans need a nod": the planner's wave is a proposal the owner approves,
121 * redirects or sets aside, not issues opened on the map (`actions/waves.ts`).
122 */
123 readonly plansNeedNod: boolean;
119124 /** The issue the planner is given, when the map has run dry. */
120125 readonly directionIssueId: string | null;
121126 /** The repo this was forked from, or null. */
@@ -160,6 +165,7 @@ interface RepoRow {
160165 autonomy_slots: number;
161166 autonomy_by: string | null;
162167 crew_outsiders: number;
168 plans_need_nod: number;
163169 direction_issue_id: string | null;
164170 fork_parent_id: string | null;
165171 sealed_for: string | null;
@@ -197,6 +203,7 @@ function toRepo(row: RepoRow): Repo {
197203 autonomySlots: row.autonomy_slots,
198204 autonomyBy: row.autonomy_by,
199205 crewOutsiders: row.crew_outsiders === 1,
206 plansNeedNod: row.plans_need_nod !== 0,
200207 directionIssueId: row.direction_issue_id,
201208 forkParentId: row.fork_parent_id,
202209 sealedFor: row.sealed_for,
@@ -1025,6 +1032,8 @@ export interface RepoSettings {
10251032 autonomyBy?: string | null;
10261033 /** Whether someone who cannot write here may start or steer a run. */
10271034 crewOutsiders?: boolean;
1035 /** Whether the planner's waves wait for the owner's nod. */
1036 plansNeedNod?: boolean;
10281037 }
10291038
10301039 /** Update the mutable repo fields, leaving unspecified ones untouched. */
@@ -1037,7 +1046,8 @@ export function updateRepoSettings(
10371046 `UPDATE repo SET visibility = ?1, description = ?2, protect_default = ?3,
10381047 default_branch = ?4, require_review = ?5, require_checks = ?7,
10391048 autonomy = ?8, autonomy_direction = ?9, autonomy_ceiling_usd = ?10,
1040 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13
1049 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13,
1050 plans_need_nod = ?14
10411051 WHERE id = ?6`,
10421052 ).run(
10431053 settings.visibility ?? repo.visibility,
@@ -1053,6 +1063,7 @@ export function updateRepoSettings(
10531063 settings.autonomySlots ?? repo.autonomySlots,
10541064 settings.autonomyBy === undefined ? repo.autonomyBy : settings.autonomyBy,
10551065 (settings.crewOutsiders ?? repo.crewOutsiders) ? 1 : 0,
1066 (settings.plansNeedNod ?? repo.plansNeedNod) ? 1 : 0,
10561067 );
10571068 return getRepoById(db, repo.id)!;
10581069 }
src/core/schema.ts +23
@@ -1614,6 +1614,29 @@ export const migrations: readonly string[] = [
16141614 PRIMARY KEY (key, issue_id)
16151615 );
16161616 `,
1617 // 77 — plans need a nod (#1114): beside autonomy, a repository setting
1618 // (default on). With it the planner's wave is a proposal the owner
1619 // approves, redirects or sets aside, not a hundred open issues. The wave
1620 // keeps the issues it opened, so the map can read it as a row.
1621 `
1622 ALTER TABLE repo ADD COLUMN plans_need_nod INTEGER NOT NULL DEFAULT 1;
1623 CREATE TABLE wave (
1624 id TEXT PRIMARY KEY,
1625 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1626 author_id TEXT NOT NULL REFERENCES user(id),
1627 title TEXT NOT NULL,
1628 why TEXT NOT NULL,
1629 milestone TEXT NOT NULL,
1630 items TEXT NOT NULL,
1631 state TEXT NOT NULL CHECK (state IN ('pending','later','approved','redirected')),
1632 words TEXT NOT NULL DEFAULT '',
1633 numbers TEXT NOT NULL DEFAULT '{}',
1634 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1635 decided_at TEXT,
1636 decided_by TEXT REFERENCES user(id)
1637 );
1638 CREATE INDEX wave_repo ON wave(repo_id, created_at);
1639 `,
16171640 ];
16181641
16191642 /**
src/core/waves.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * A wave: the planner's next step as one proposal (#1114) — a title, a
3 * one-line why, the milestone it moves, and three to six issues in order.
4 * It is kept until a person decides: approved (the issues opened, and their
5 * numbers kept so the map can read the wave as a row), redirected (with the
6 * words that sent the planner back), or set aside for later.
7 *
8 * Pure data, no authz, no events (`actions/waves.ts`).
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { id } from "../kernel/id.ts";
13 import type { PlanItem } from "../actions/plan.ts";
14
15 export type WaveState = "pending" | "later" | "approved" | "redirected";
16
17 export interface Wave {
18 readonly id: string;
19 readonly repoId: string;
20 readonly authorId: string;
21 readonly title: string;
22 readonly why: string;
23 /** The named milestone this wave moves. */
24 readonly milestone: string;
25 /** The issues to open, in order. */
26 readonly items: readonly PlanItem[];
27 readonly state: WaveState;
28 /** For a redirect: the words the planner re-plans from. */
29 readonly words: string;
30 /** Once approved: the number each item's key opened as. */
31 readonly numbers: Readonly<Record<string, number>>;
32 readonly createdAt: string;
33 readonly decidedAt: string | null;
34 }
35
36 interface Row {
37 id: string;
38 repo_id: string;
39 author_id: string;
40 title: string;
41 why: string;
42 milestone: string;
43 items: string;
44 state: WaveState;
45 words: string;
46 numbers: string;
47 created_at: string;
48 decided_at: string | null;
49 }
50
51 const fromRow = (r: Row): Wave => ({
52 id: r.id,
53 repoId: r.repo_id,
54 authorId: r.author_id,
55 title: r.title,
56 why: r.why,
57 milestone: r.milestone,
58 items: JSON.parse(r.items) as PlanItem[],
59 state: r.state,
60 words: r.words,
61 numbers: JSON.parse(r.numbers) as Record<string, number>,
62 createdAt: r.created_at,
63 decidedAt: r.decided_at,
64 });
65
66 export function createWave(
67 db: Database,
68 wave: {
69 repoId: string;
70 authorId: string;
71 title: string;
72 why: string;
73 milestone: string;
74 items: readonly PlanItem[];
75 },
76 ): Wave {
77 const key = id();
78 db.query(
79 `INSERT INTO wave (id, repo_id, author_id, title, why, milestone, items, state)
80 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'pending')`,
81 ).run(
82 key,
83 wave.repoId,
84 wave.authorId,
85 wave.title,
86 wave.why,
87 wave.milestone,
88 JSON.stringify(wave.items),
89 );
90 return getWave(db, key)!;
91 }
92
93 export function getWave(db: Database, waveId: string): Wave | undefined {
94 const row = db.query<Row, [string]>("SELECT * FROM wave WHERE id = ?1").get(waveId);
95 return row ? fromRow(row) : undefined;
96 }
97
98 /** A repository's waves, oldest first (the order they were proposed in). */
99 export function listWaves(
100 db: Database,
101 repoId: string,
102 states?: readonly WaveState[],
103 ): Wave[] {
104 return db
105 .query<Row, [string]>(
106 "SELECT * FROM wave WHERE repo_id = ?1 ORDER BY created_at, id",
107 )
108 .all(repoId)
109 .map(fromRow)
110 .filter((w) => states === undefined || states.includes(w.state));
111 }
112
113 /** Waves awaiting a nod in these repositories: the inbox's cards. */
114 export function pendingWaves(db: Database, repoIds: readonly string[]): Wave[] {
115 if (repoIds.length === 0) return [];
116 const marks = repoIds.map(() => "?").join(",");
117 return db
118 .query<Row, string[]>(
119 `SELECT * FROM wave WHERE state = 'pending' AND repo_id IN (${marks})
120 ORDER BY created_at, id`,
121 )
122 .all(...repoIds)
123 .map(fromRow);
124 }
125
126 export function decideWave(
127 db: Database,
128 waveId: string,
129 state: WaveState,
130 by: string,
131 extra: { words?: string; numbers?: Record<string, number> } = {},
132 ): void {
133 db.query(
134 `UPDATE wave SET state = ?2, words = ?3, numbers = ?4, decided_by = ?5,
135 decided_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
136 WHERE id = ?1`,
137 ).run(waveId, state, extra.words ?? "", JSON.stringify(extra.numbers ?? {}), by);
138 }
src/crew/autonomy.ts +5
@@ -12,6 +12,7 @@
1212 * repository's origin.
1313 */
1414
15 import { pendingWaves } from "../core/waves.ts";
1516 import type { Database } from "bun:sqlite";
1617 import type { App } from "../app.ts";
1718 import {
@@ -554,6 +555,10 @@ async function planIfThin(
554555 if (ready >= THIN_MAP && handed.length === 0) return false;
555556 const planner = crew.find((c) => c.role === "planner")?.agent;
556557 if (planner === undefined) return notPlanned(repo, "no planner on the crew");
558 // A wave waiting for the owner's nod is the plan: the planner is not asked
559 // for another until it is approved or redirected (#1114).
560 if (pendingWaves(app.db, [repo.id]).length > 0)
561 return notPlanned(repo, "a wave waits for the owner's nod");
557562 if (repo.autonomyDirection.trim() === "")
558563 return notPlanned(repo, "no direction written");
559564 const direction = ensureDirectionIssue(app, by, repo);
src/crew/brief.ts +7
@@ -110,6 +110,13 @@ export function systemPrompt(input: BriefInput): string {
110110 " It answers with what it opened (key and number), the numbers now ready, and those deferred.",
111111 "- The direction is never finished. When what it names is built, propose its next increment in the same spirit: what a demanding user would want next, what is fragile, slow, ugly, untested or undocumented, what the pictures and the previews show is off. Leave the map with at least three ready issues, every time.",
112112 '- An issue with a comment that starts "Parked by the crew" was tried and could not be finished as written. Split it into smaller issues, or rewrite what done looks like, or close it with a word if the direction no longer needs it — never leave it as it was. One the crew parked twice is yours: your task lists it, with what you may do with it.',
113 ...(repo.plansNeedNod
114 ? [
115 `- Plans need the owner's nod here. Do NOT open issues or link them yourself: propose one wave, and the owner approves it (the issues then open, linked, in your order) or redirects you with words on the direction issue. Propose it in one call:`,
116 ` curl -sH "authorization: Bearer $FORGE_TOKEN" -H "content-type: application/json" -X POST "$FORGE_URL/api/v1/repos/${repo.ownerName}/${repo.name}/plan" -d '{"title":"…","why":"one line","milestone":"the named milestone it moves","issues":[{"key":"a","title":"…","body":"…","blockedBy":[],"pillar":"P0"},{"key":"b","title":"…","body":"…","blockedBy":["a"],"pillar":"P0"},{"key":"c","title":"…","body":"…","blockedBy":["b"],"later":true,"why":"…"}]}'`,
outdated

This example wave has two issues, but WAVE_MIN is 3, so proposeWave answers wave_size. The planner copies this example, so give it three items.

117 " A wave is three to six issues in order; blockedBy names the keys (or open issue numbers) each waits for. A comment on the direction issue that starts \"Redirect\" is the owner sending you back: plan the next wave from those words, not the one you proposed before. Your final message names the wave you proposed.",
118 ]
119 : []),
113120 "- Assign nobody and push nothing: the map is the result. The direction issue stays open.",
114121 "- The forge's API works; open no issue to try it. Every issue you open is work a builder is given.",
115122 "- Finish with a short message that lists what you opened, in order, and what is ready now.",
src/http/api.ts +50 −16
@@ -259,8 +259,13 @@ import {
259259 unlinkIssue,
260260 confirmIssue,
261261 } from "../actions/dependencies.ts";
262 import { openPlan, parsePlan } from "../actions/plan.ts";
263262 import { dependenciesOf, repoGraph } from "../core/dependencies.ts";
263 import {
264 decideWave,
265 submitPlan,
266 waitingWaves,
267 waveJson,
268 } from "../actions/waves.ts";
264269 import { pillarView } from "../core/pillars.ts";
265270 import { askToLiveFor } from "../web/ask_to_live.ts";
266271 import { decisionStats, listDecisions } from "../core/decisions.ts";
@@ -2414,27 +2419,56 @@ export function apiRoutes(router: Router<Handler>): void {
24142419 );
24152420 },
24162421 );
2417 // A plan, all or nothing: the same action as the MCP `plan` tool, so the
2418 // same items and the same refusals (docs/PLANNING.md).
2422 // A plan: issues opened all at once, or, where plans need a nod and the
2423 // caller is the crew, a wave proposed (nothing opened). Then the waves
2424 // waiting, and the nod, the redirect or the later that settles one.
2425 const planFailed = (e: { error: string; message: string }) =>
2426 e.error === "not_found"
2427 ? notFound()
2428 : apiError(e.error, e.error === "forbidden" ? 403 : 422, e.message);
24192429 router.add("POST", "/api/v1/repos/:owner/:name/plan", async (ctx) => {
24202430 const denied = requireScope(ctx, "rw");
24212431 if (denied) return denied;
24222432 const repo = loadRepo(ctx);
24232433 if (!repo) return notFound();
24242434 const input = await body(ctx.request);
2425 const items = parsePlan(input.issues);
2426 if (!items.ok)
2427 return apiError(items.error.error, 422, items.error.message);
2428 const planned = openPlan(ctx.app, ctx.auth.user, repo, items.value);
2429 if (!planned.ok) {
2430 const { error, message } = planned.error;
2431 return apiError(
2432 error,
2433 error === "not_found" ? 404 : error === "forbidden" ? 403 : 422,
2434 message,
2435 );
2436 }
2437 return json(planned.value, 201);
2435 const made = submitPlan(ctx.app, ctx.auth.user, repo, {
2436 title: input.title,
2437 why: input.why,
2438 milestone: input.milestone,
2439 issues: input.issues,
2440 });
2441 if (!made.ok) return planFailed(made.error);
2442 return "proposed" in made.value
2443 ? json({ proposed: waveJson(made.value.proposed) }, 202)
2444 : json(made.value.opened, 201);
2445 });
2446 router.add("GET", "/api/v1/repos/:owner/:name/waves", (ctx) => {
2447 const denied = requireScope(ctx, "ro");
2448 if (denied) return denied;
2449 const repo = loadRepo(ctx);
2450 if (!repo) return notFound();
2451 return json({ waves: waitingWaves(ctx.app, repo).map(waveJson) });
2452 });
2453 router.add("POST", "/api/v1/repos/:owner/:name/waves/:wave/decide", async (ctx) => {
2454 const denied = requireScope(ctx, "rw");
2455 if (denied) return denied;
2456 const repo = loadRepo(ctx);
2457 if (!repo) return notFound();
2458 const input = await body(ctx.request);
2459 const done = decideWave(
2460 ctx.app,
2461 ctx.auth.user,
2462 repo,
2463 ctx.params.wave!,
2464 input.decision,
2465 input.words,
2466 );
2467 if (!done.ok) return planFailed(done.error);
2468 return json({
2469 wave: waveJson(done.value.wave),
2470 ...(done.value.planned ? { opened: done.value.planned.opened } : {}),
2471 });
24382472 });
24392473 router.add(
24402474 "DELETE",
src/http/mcp.ts +80 −8
@@ -33,7 +33,15 @@ import {
3333 unlinkIssue,
3434 } from "../actions/dependencies.ts";
3535 import { holdPull, releasePull } from "../actions/holds.ts";
36 import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
36 import { PLAN_MAX } from "../actions/plan.ts";
37 import {
38 decideWave,
39 submitPlan,
40 waitingWaves,
41 waveJson,
42 WAVE_MAX,
43 WAVE_MIN,
44 } from "../actions/waves.ts";
3745 import { cancelRepoRun } from "../actions/runs.ts";
3846 import { clientRows } from "../spawn/clients.ts";
3947 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
@@ -1685,11 +1693,14 @@ const TOOLS: readonly Tool[] = [
16851693 },
16861694 {
16871695 name: "plan",
1688 description: `Open several small issues and link them in one call: all of them or none. Each item has a key, a title, a body and optionally blockedBy, a list of keys of this plan or numbers of issues already open. Where the app has pillars (umbrella issues titled like "P0 Trust: …"), each item also says what it is for: pillar, the one it serves, or later: true with why, one sentence, which puts it behind the Later gate instead of on the ready list; an item that says neither is refused. A bad link (loop, unknown key) refuses the whole plan and names the item. At most ${PLAN_MAX} issues. Answers with the numbers opened, by key, what is ready now, and what waits for later.`,
1696 description: `Open several small issues and link them in one call: all of them or none. Each item has a key, a title, a body and optionally blockedBy, a list of keys of this plan or numbers of issues already open. Where the app has pillars (umbrella issues titled like "P0 Trust: …"), each item also says what it is for: pillar, the one it serves, or later: true with why, one sentence, which puts it behind the Later gate instead of on the ready list; an item that says neither is refused. A bad link (loop, unknown key) refuses the whole plan and names the item. At most ${PLAN_MAX} issues. Answers with the numbers opened, by key, what is ready now, and what waits for later. Where the app's plans need a nod (Settings → On its own) and you are on its crew, nothing is opened: give a title, why (one line), milestone (the one it moves) and ${WAVE_MIN} to ${WAVE_MAX} issues in order, and the answer is the proposed wave, which the owner approves or redirects (decide). Without issues, answers with the waves waiting for a nod, to read aloud.`,
16891697 inputSchema: {
16901698 type: "object",
16911699 properties: {
16921700 app: APP_ARG,
1701 title: { type: "string", description: "A wave's title (when plans need a nod)." },
1702 why: { type: "string", description: "A wave's why, in one line." },
1703 milestone: { type: "string", description: "The named milestone the wave moves." },
16931704 issues: {
16941705 type: "array",
16951706 minItems: 1,
@@ -1728,17 +1739,37 @@ const TOOLS: readonly Tool[] = [
17281739 },
17291740 },
17301741 },
1731 required: ["app", "issues"],
1742 required: ["app"],
17321743 },
17331744 writes: true,
17341745 run(ctx, user, args) {
17351746 const repo = planRepo(ctx, user, args);
17361747 if (isAnswer(repo)) return repo;
1737 const items = parsePlan(args["issues"]);
1738 if (!items.ok) return bad(items.error.error, items.error.message);
1739 const planned = openPlan(ctx.app, user, repo, items.value);
1740 if (!planned.ok) return bad(planned.error.error, planned.error.message);
1741 const { opened, ready, later, gate } = planned.value;
1748 if (args["issues"] === undefined) {
1749 const waves = waitingWaves(ctx.app, repo).map(waveJson);
1750 return good({
1751 says:
1752 waves.length === 0
1753 ? "No wave waits for a nod."
1754 : `${waves.length} wave${waves.length === 1 ? "" : "s"} wait${waves.length === 1 ? "s" : ""} for a nod: ${waves.map((w) => `“${w.title}” (${w.milestone})`).join("; ")}. Approve or redirect with decide.`,
1755 waves,
1756 });
1757 }
1758 const made = submitPlan(ctx.app, user, repo, {
1759 title: args["title"],
1760 why: args["why"],
1761 milestone: args["milestone"],
1762 issues: args["issues"],
1763 });
1764 if (!made.ok) return bad(made.error.error, made.error.message);
1765 if ("proposed" in made.value) {
1766 const wave = waveJson(made.value.proposed);
1767 return good({
1768 says: `Proposed the wave “${wave.title}” toward ${wave.milestone}: ${wave.why} Nothing is opened until the owner approves it or redirects you.`,
1769 wave,
1770 });
1771 }
1772 const { opened, ready, later, gate } = made.value.opened;
17421773 const waits =
17431774 gate === undefined
17441775 ? ""
@@ -1751,6 +1782,47 @@ const TOOLS: readonly Tool[] = [
17511782 });
17521783 },
17531784 },
1785 {
1786 name: "decide",
1787 description:
1788 "Settle a proposed wave (see plan, without issues, for the waves waiting): approve opens its issues, linked in the order proposed and ready; redirect sends the planner back with your words (words) and opens nothing; later sets it aside. Only a person who writes the app decides. Answers with the wave and, on approve, the issue numbers opened.",
1789 inputSchema: {
1790 type: "object",
1791 properties: {
1792 app: APP_ARG,
1793 wave: { type: "string", description: "The wave's id." },
1794 decision: { type: "string", enum: ["approve", "redirect", "later"] },
1795 words: { type: "string", maxLength: 2000, description: "With redirect: where the plan should go instead." },
1796 },
1797 required: ["app", "wave", "decision"],
1798 },
1799 writes: true,
1800 run(ctx, user, args) {
1801 const repo = planRepo(ctx, user, args);
1802 if (isAnswer(repo)) return repo;
1803 const done = decideWave(
1804 ctx.app,
1805 user,
1806 repo,
1807 str(args["wave"]),
1808 args["decision"],
1809 args["words"],
1810 );
1811 if (!done.ok) return bad(done.error.error, done.error.message);
1812 const wave = waveJson(done.value.wave);
1813 const opened = done.value.planned?.opened;
1814 return good({
1815 says:
1816 opened !== undefined
1817 ? `Approved “${wave.title}”: opened ${opened.map((o) => `#${o.number}`).join(", ")}.`
1818 : wave.state === "redirected"
1819 ? `Redirected “${wave.title}”: the planner plans again from your words.`
1820 : `Set “${wave.title}” aside for later.`,
1821 wave,
1822 ...(opened === undefined ? {} : { opened }),
1823 });
1824 },
1825 },
17541826 {
17551827 name: "capacity",
17561828 description:
src/http/server.ts +2
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { waveDecide } from "../web/pages/waves.ts";
89 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
910 import { unsealReleased } from "../actions/sealed.ts";
1011 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
@@ -1115,6 +1116,7 @@ export function buildRouter(): Router<Handler> {
11151116 );
11161117 router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage);
11171118 router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate);
1119 router.add("POST", "/:owner/:name/waves/:wave/decide", waveDecide);
11181120 router.add("GET", "/:owner/:name/settings/labels", labelsPage);
11191121 router.add("POST", "/:owner/:name/settings/labels", labelCreate);
11201122 router.add("POST", "/:owner/:name/settings/labels/:id", labelUpdate);
src/tui/screens/waves.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * `M` on a repository: the waves the planner proposed that still wait for a
3 * nod (#1114) — pick one, then approve it, redirect it with words, or set it
4 * aside. The terminal's door to the same action the page, the API and the
5 * MCP call (`actions/waves.ts`), which decides who may.
6 */
7
8 import { decideWave, waitingWaves } from "../../actions/waves.ts";
9 import type { Repo } from "../../core/repos.ts";
10 import type { Wave } from "../../core/waves.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import type { Session } from "../session.ts";
13 import { metaOf, pickerScreen, plural, promptScreen, type PickItem } from "./common.ts";
14
15 const DECISIONS: readonly PickItem[] = [
16 { id: "approve", label: "Approve", hint: "open its issues, linked, ready" },
17 { id: "redirect", label: "Redirect", hint: "send the planner back with words" },
18 { id: "later", label: "Later", hint: "set it aside; it stays here" },
19 ];
20
21 /** What the decision came to, said in a line. */
22 function decide(
23 f: Session,
24 ctx: Ctx,
25 repo: Repo,
26 wave: Wave,
27 decision: string,
28 words = "",
29 ): string | undefined {
30 const done = decideWave(f.app, f.user, repo, wave.id, decision, words);
31 if (!done.ok) return done.error.message;
32 ctx.toast(
33 decision === "approve"
34 ? `approved: ${plural(done.value.planned?.opened.length ?? 0, "issue")} opened`
35 : decision === "redirect"
36 ? "redirected: the planner plans again"
37 : "set aside for later",
38 "success",
39 );
40 return undefined;
41 }
42
43 export function wavesScreen(f: Session, ctx: Ctx, parent: Screen, repo: Repo): void {

No test covers this screen. Add one that drives M → wave → Approve and sees the issues open, and one where a reader without write access is refused and nothing opens.

44 const waves = waitingWaves(f.app, repo);
45 if (waves.length === 0) {
46 ctx.toast("no wave is waiting for a nod", "attn");
47 return;
48 }
49 ctx.push(
50 pickerScreen(ctx, parent, {
51 title: "Waves waiting for a nod",
52 items: waves.map((w) => ({
53 id: w.id,
54 label: w.title,
55 hint: metaOf(w.milestone, plural(w.items.length, "issue"), w.state === "later" ? "later" : ""),
56 })),
57 onPick: ([chosen]) => {
58 const wave = waves.find((w) => w.id === chosen);
59 if (wave === undefined) return;
60 ctx.push(
61 pickerScreen(ctx, parent, {
62 title: `${wave.title} — ${wave.why}`,
63 items: DECISIONS,
64 onPick: ([what]) => {
65 if (what === "redirect") {
66 ctx.push(
67 promptScreen(ctx, parent, {
68 title: "Redirect the planner",
69 label: "Where should the plan go instead?",
70 onSubmit: (words) =>
71 words.trim() === ""
72 ? "say where the plan should go"
73 : decide(f, ctx, repo, wave, "redirect", words),
74 }),
75 );
76 } else if (what !== undefined) {
77 const failed = decide(f, ctx, repo, wave, what);
78 if (failed !== undefined) ctx.toast(failed, "danger");
79 }
80 },
81 }),
82 );
83 },
84 }),
85 );
86 }
src/tui/screens/workspace.ts +6
@@ -114,6 +114,7 @@ import { issuesScreen } from "./issues.ts";
114114 import { liveBindings, liveKey } from "./mirror.ts";
115115 import { forkScreen } from "./newrepo.ts";
116116 import { pullScreen } from "./pull.ts";
117 import { wavesScreen } from "./waves.ts";
117118 import { branchesScreen } from "./refs.ts";
118119 import {
119120 hostOf,
@@ -1282,6 +1283,7 @@ export function workspaceScreen(
12821283 binding(["t", "ctrl+p"], "find file"),
12831284 binding(["y"], "copy path"),
12841285 binding(["i", "p", "C"], "issues / pulls / commits"),
1286 ...(repo === undefined ? [] : [binding(["M"], "waves waiting for a nod")]),
12851287 binding(["I"], "about this repository"),
12861288 ...liveBindings(src),
12871289 ...(liveSide?.mirroredAs === undefined
@@ -1594,6 +1596,10 @@ export function workspaceScreen(
15941596 ctx.push(issuesScreen(f, ctx, src, "pull"));
15951597 return true;
15961598 }
1599 if (plain && e.key === "M" && repo !== undefined) {
1600 wavesScreen(f, ctx, screen, repo);
1601 return true;
1602 }
15971603 if (plain && e.key === "C") {
15981604 ctx.push(commitsScreen(f, ctx, src, ref));
15991605 return true;
src/web/pages/map.ts +58
@@ -38,6 +38,7 @@ import {
3838 import type { Issue } from "../../core/issues.ts";
3939 import { holdsFor } from "../../core/holds.ts";
4040 import {
41 canWrite,
4142 getRepoById,
4243 listReposVisibleTo,
4344 type Repo,
@@ -57,6 +58,8 @@ import {
5758 } from "../chrome.ts";
5859 import { liveRegionsJs } from "../client.ts";
5960 import { html, type Html } from "../html.ts";
61 import { listWaves } from "../../core/waves.ts";
62 import { wavesSection } from "./waves_view.ts";
6063 import { page } from "../layout.ts";
6164 import { avatar, hueOf, icon } from "../ui.ts";
6265 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy.ts";
@@ -1391,6 +1394,8 @@ function autonomyLine(ctx: Ctx, repo: Repo): Html | null {
13911394 }
13921395
13931396 const LIVE_KINDS = "run.*,issue.*,pull.*";
1397 /** What can change the waves view: a decision, or the issues a wave opened. */
1398 const WAVES_LIVE = "wave.*,issue.*,pull.*";
13941399
13951400 /** The empty state in the studio's own words, pointing at the app page's
13961401 * own box for telling the crew (`#tell`, `src/web/studio/app.ts`). */
@@ -1420,6 +1425,56 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14201425 );
14211426 const pillars = pillarView(db, repo);
14221427 const ask = await askToLiveFor(ctx.app, repo, pillars, ctx.auth.user);
outdated

Filtering out later here, together with pendingWaves (pending only) in the inbox, means a wave set aside for later appears on no page at all. Show it here with its buttons, or keep it in the inbox. Separately, showWaves on the next line hides every issue that is not in a wave once any wave exists, including redirected ones: give issues outside any wave a section of their own.

1428 // With waves on record the map reads as waves toward milestones; the
1429 // whole graph is one click away (?graph=1).
1430 const allWaves = listWaves(db, repo.id);
1431 const inWave = new Set(
1432 allWaves.flatMap((w) => (w.state === "approved" ? Object.values(w.numbers) : [])),
1433 );
1434 const outside = graph.issues
1435 .filter((i) => i.state === "open" && !inWave.has(i.number))
1436 .map((i) => ({ number: i.number, title: i.title }));
1437 // Redirected waves were never opened: they are history, not the plan.
1438 const waves = allWaves.filter((w) => w.state !== "redirected");
1439 // Waves lead while one waits for a decision or an approved one has issues
1440 // open; otherwise the graph is the map.
1441 const live = waves.some(
1442 (w) =>
1443 w.state === "pending" ||
1444 w.state === "later" ||
1445 Object.values(w.numbers).some((n) =>
1446 graph.issues.some((i) => i.number === n && i.state === "open"),
1447 ),
1448 );
1449 const showWaves = live && ctx.url.searchParams.get("graph") !== "1";
outdated

This early return drops the graph view's data-live region and liveRegionsJs, so the waves view never updates live. Wrap wavesSection in a live region listening to wave.,issue.,pull. (and include wave. in the inbox's ON_YOU_LIVE).

1450 const decidable = ctx.auth.user !== undefined && canWrite(db, repo, ctx.auth.user);
1451 if (showWaves)
1452 return page({
1453 ctx,
1454 title: `Map · ${repo.name}`,
1455 crumbs: crumbsFor(repo),
1456 palette: repoPalette(ctx, repo),
1457 body: html`${repoHeader(ctx, repo, "map")}
1458 <div class="page-head mt">
1459 <h1>Map</h1>
1460 <p class="muted">
1461 The plan as waves toward milestones: what each wave is for, what
1462 landed in it, what is left.
1463 <a href="${repoBase(repo)}/map?graph=1">Show the whole graph</a> ·
1464 <a href="${repoBase(repo)}/milestones">How far each milestone is</a>.
1465 </p>
1466 ${autonomyLine(ctx, repo)}
1467 </div>
1468 <div
1469 id="map-waves"
1470 data-live="${WAVES_LIVE}"
1471 data-live-repo="${repo.ownerName}/${repo.name}"
1472 >
1473 ${wavesSection(db, repo, waves, issueHref, repoBase(repo), decidable, outside)}
1474 </div>`,
1475 styleCss: mapCss,
1476 scriptJs: liveRegionsJs,
1477 });
14231478 const body = html`${repoHeader(ctx, repo, "map")}
14241479 <div class="page-head mt">
14251480 <h1>Map</h1>
@@ -1427,6 +1482,9 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14271482 What waits for what. The top edge is ready now; the chain in the accent
14281483 is the least work that still has to happen in order.
14291484 <a href="${repoBase(repo)}/milestones">How far each milestone is</a>.
1485 ${live
1486 ? html`<a href="${repoBase(repo)}/map">Back to the waves</a>.`
1487 : null}
14301488 </p>
14311489 ${autonomyLine(ctx, repo)}
14321490 </div>
src/web/pages/settings.ts +1
@@ -1764,6 +1764,7 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
17641764 autonomyDirection: field(form, "direction").trim().slice(0, 2000),
17651765 autonomyCeilingUsd: ceiling,
17661766 autonomySlots: slots,
1767 plansNeedNod: form.get("plansNeedNod") !== null,
17671768 autonomyBy: mode === "off" ? null : (ctx.auth.user?.id ?? null),
17681769 });
17691770 return flashTo(ctx, `${base}/settings#autonomy`, {
src/web/pages/waves.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * The nod, as a form post (#1114): the inbox card's Approve, Redirect and
3 * Later. One route; the decision itself is `actions/waves.ts`, the same
4 * one the API and the MCP's `decide` call.
5 */
6
7 import { decideWave } from "../../actions/waves.ts";
8 import type { Ctx } from "../../http/context.ts";
9 import { notFoundPage, repoBase, loadRepo, signInFirst } from "../chrome.ts";
10 import { field, readForm } from "../form.ts";
11 import { flashTo } from "../layout.ts";
12
13 // POST /:owner/:name/waves/:wave/decide
14 export async function waveDecide(ctx: Ctx): Promise<Response> {
15 if (!ctx.auth.user) return signInFirst(ctx);
16 const repo = loadRepo(ctx);
17 if (!repo) return notFoundPage(ctx);
18 const form = await readForm(ctx, "rw");
19 if (form instanceof Response) return form;
20 const done = decideWave(
21 ctx.app,
22 ctx.auth.user,
23 repo,
24 ctx.params.wave ?? "",
25 field(form, "decision"),
26 field(form, "words"),
27 );
28 if (!done.ok)
29 return done.error.error === "not_found"
30 ? notFoundPage(ctx)
31 : flashTo(ctx, "/", { tone: "danger", message: done.error.message });
32 const { wave, planned } = done.value;
33 return flashTo(ctx, wave.state === "approved" ? `${repoBase(repo)}/map` : "/", {
34 message:
35 wave.state === "approved"
36 ? `Approved: ${planned!.opened.length} issues opened, linked and ready.`
37 : wave.state === "redirected"
38 ? "Redirected: the planner plans again from your words."
39 : "Set aside for later.",
40 });
41 }
src/web/pages/waves_view.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * The map read as waves toward named milestones (#1114): each wave a row —
3 * its title and why — its issues beneath, what landed in it and what is
4 * left. A wave waiting for a nod shows its issues as proposed. The full
5 * graph stays one click away (`?graph=1`, `map.ts`).
6 */
7
8 import { getIssue } from "../../core/issues.ts";
9 import type { Repo } from "../../core/repos.ts";
10 import type { Wave } from "../../core/waves.ts";
11 import type { Database } from "bun:sqlite";
12 import { html, type Html } from "../html.ts";
13 import { btn } from "../ui.ts";
14
15 const STATE_WORDS: Readonly<Record<Wave["state"], string>> = {
16 pending: "waiting for a nod",
17 later: "set aside for later",
18 approved: "approved",
19 redirected: "redirected",
20 };
21
22 /** One wave: its row, its issues in order, and the tally. */
23 function waveRow(
24 db: Database,
25 repo: Repo,
26 wave: Wave,
27 issueHref: (base: string, number: number) => string,
28 base: string,
29 decidable: boolean,
30 ): Html {
31 const issues = wave.items.map((item) => {
32 const number = wave.numbers[item.key];
33 const found = number === undefined ? undefined : getIssue(db, repo.id, number);
34 return { item, number, state: found?.state };
35 });
36 const landed = issues.filter((i) => i.state !== undefined && i.state !== "open").length;
37 const left = wave.state === "approved" ? issues.length - landed : issues.length;
38 return html`<li class="wave" id="wave-${wave.id}" data-state="${wave.state}">
39 <h3>${wave.title} <span class="muted small">${STATE_WORDS[wave.state]}</span></h3>
40 <p class="muted small">${wave.why}</p>
41 <ol class="small">
42 ${issues.map((i) =>
43 i.number === undefined
44 ? html`<li>${i.item.title}</li>`
45 : html`<li data-landed="${i.state === "open" ? "no" : "yes"}">
46 <a href="${issueHref(base, i.number)}">${i.item.title}</a>
47 ${i.state === "open" ? null : html`<span class="muted">landed</span>`}
48 </li>`,
49 )}
50 </ol>
51 <p class="small muted">
52 ${wave.state === "approved"
53 ? `${landed} landed, ${left} left`
54 : wave.state === "redirected"
55 ? `not opened; redirected${wave.words === "" ? "" : `: ${wave.words}`}`
56 : `${issues.length} proposed, none opened`}
57 </p>
58 ${decidable && (wave.state === "pending" || wave.state === "later")
59 ? html`<form
60 class="row small"
61 method="post"
62 action="${base}/waves/${wave.id}/decide"
63 >
64 ${btn("Approve", { name: "decision", value: "approve", size: "sm", variant: "primary" })}
65 <input
66 class="input"
67 type="text"
68 name="words"
69 maxlength="2000"
70 placeholder="Or say where the plan should go instead"
71 aria-label="Redirect the plan: say where it should go"
72 />
73 ${btn("Redirect", { name: "decision", value: "redirect", size: "sm" })}
74 ${wave.state === "pending"
75 ? btn("Later", { name: "decision", value: "later", size: "sm" })
76 : null}
77 </form>`
78 : null}
79 </li>`;
80 }
81
82 /** The waves, grouped under the milestone each moves, newest wave last. */
83 export function wavesSection(
84 db: Database,
85 repo: Repo,
86 waves: readonly Wave[],
87 issueHref: (base: string, number: number) => string,
88 base: string,
89 decidable: boolean,
90 /** Open issues that belong to no wave: the work a person opened themselves. */
91 outside: readonly { number: number; title: string }[] = [],
92 ): Html {
93 const byMilestone = new Map<string, Wave[]>();
94 for (const w of waves) byMilestone.set(w.milestone, [...(byMilestone.get(w.milestone) ?? []), w]);
95 return html`<section class="waves" id="waves">
96 ${[...byMilestone].map(
97 ([milestone, rows]) => html`<div class="wave-milestone">
98 <h2>${milestone}</h2>
99 <ul class="list">
100 ${rows.map((w) => waveRow(db, repo, w, issueHref, base, decidable))}
101 </ul>
102 </div>`,
103 )}
104 ${outside.length === 0
105 ? null
106 : html`<div class="wave-milestone" id="outside-waves">
107 <h2>Outside the waves</h2>
108 <p class="muted small">Open issues that belong to no wave.</p>
109 <ul class="list small">
110 ${outside.map(
111 (i) => html`<li><a href="${issueHref(base, i.number)}">#${i.number} ${i.title}</a></li>`,
112 )}
113 </ul>
114 </div>`}
115 </section>`;
116 }
src/web/studio/asks.ts +70 −1
@@ -14,6 +14,7 @@ import { appsRuntime } from "../../apps/runtime.ts";
1414 import { appsForRepos, getAppByRepo, listApps } from "../../core/apps.ts";
1515 import { latestDecision, stopStands } from "../../core/decisions.ts";
1616 import { getHold, holdsFor } from "../../core/holds.ts";
17 import { pendingWaves, type Wave } from "../../core/waves.ts";
1718 import { askDismissals } from "../../core/interactions.ts";
1819 import { askMeasure, syncAskLedger, type AskEnd } from "../../core/ask_ledger.ts";
1920 import {
@@ -94,7 +95,7 @@ export function writableAppsOf(ctx: Ctx, user: User | undefined) {
9495 );
9596 }
9697
97 export type DecisionKind = "stopped" | "look" | "review" | "paused" | "parked" | "declined";
98 export type DecisionKind = "stopped" | "look" | "review" | "paused" | "parked" | "declined" | "proposed";
9899
99100 /** Dollars as a person reads them: cents when small, whole when not. */
100101 const dollars = (n: number): string => (n < 10 ? n.toFixed(2) : n.toFixed(0));
@@ -109,6 +110,8 @@ export interface Decision {
109110 /** For "parked": the issue the breaker stopped; for "declined": the
110111 * direction issue the planner declined. */
111112 readonly issue?: Issue | undefined;
113 /** For "proposed": the wave waiting for a nod. */
114 readonly wave?: Wave | undefined;
112115 readonly who: string;
113116 /** Three sentences at most: what, why, what happens next. */
114117 readonly says: string;
@@ -155,6 +158,11 @@ export const ASK_WORDS: Readonly<Record<DecisionKind, AskWords>> = {
155158 options: ["Answer the planner"],
156159 ifNothing: "the planner plans nothing more for this app",
157160 },
161 proposed: {
162 decision: "The planner proposes a wave: open its issues?",
163 options: ["Approve", "Redirect", "Later"],
164 ifNothing: "it waits; no issue opens and the planner plans nothing more",
165 },
158166 paused: {
159167 decision: "Raise today's ceiling?",
160168 options: ["Raise it in settings"],
@@ -177,6 +185,7 @@ export interface Consequence {
177185 export const KIND_TIER: Readonly<Record<DecisionKind, Consequence>> = {
178186 paused: { score: 80, why: "money: the crew is stopped at its ceiling" },
179187 declined: { score: 70, why: "the planner has stopped for this app" },
188 proposed: { score: 60, why: "the plan waits for your nod" },
180189 stopped: { score: 50, why: "red, and the crew stopped" },
181190 review: { score: 45, why: "an agent's change waits for a review" },
182191 parked: { score: 40, why: "parked by the crew" },
@@ -209,6 +218,7 @@ interface AskCandidate {
209218 readonly repo: Repo;
210219 readonly pull?: Pull;
211220 readonly issue?: Issue;
221 readonly wave?: Wave;
212222 readonly who: string;
213223 /** Whether the author is a crew member — a "look" card words itself
214224 * differently for a person's own change than for the crew's (below).
@@ -390,6 +400,19 @@ function askCandidatesFor(
390400 who: "the planner",
391401 decline: { runId: d.runId, words: d.words },
392402 });
403 // A wave the planner proposed waits for the owner's nod: one card.
404 for (const wave of pendingWaves(db, repos.map((r) => r.id))) {
405 const repo = byId.get(wave.repoId);
406 if (repo)
407 out.push({
408 kind: "proposed",
409 id: `proposed:${wave.id}`,
410 since: wave.createdAt,
411 repo,
412 wave,
413 who: "the planner",
414 });
415 }
393416 return out;
394417 }
395418
@@ -638,6 +661,8 @@ function lineOf(c: AskCandidate): string {
638661 return `the crew parked #${c.issue!.number} after three failed runs`;
639662 if (c.kind === "declined")
640663 return "the planner declined the direction and waits for you";
664 if (c.kind === "proposed")
665 return `the planner proposes the wave \u201c${c.wave!.title}\u201d toward ${c.wave!.milestone}`;
641666 const title = c.pull?.title ?? "";
642667 if (c.kind === "review")
643668 return `"${title}" waits for your review: ${reviewWhy(c.reviewWait)}`;
@@ -663,6 +688,7 @@ export const ROW_PLURAL: Readonly<Record<DecisionKind, (n: number) => string>> =
663688 stopped: (n) => `the crew stopped on ${n} changes`,
664689 parked: (n) => `the crew parked ${n} issues after three failed runs`,
665690 declined: (n) => `the planner declined ${n} times and waits for you`,
691 proposed: (n) => `the planner proposes ${n} waves and waits for your nod`,
666692 paused: (n) => `${n} pauses at the ceiling`,
667693 };
668694
@@ -718,6 +744,7 @@ export function askLinesFor(
718744 const line = `${row.repo.name}${only.kind === "paused" ? " " : ": "}${lineOf(only)}`;
719745 if (only.kind === "paused")
720746 return { ...about, line, link: `${base}/settings/autonomy` };
747 if (only.kind === "proposed") return { ...about, line, link: `${base}/map` };
721748 if (only.kind === "parked" || only.kind === "declined")
722749 return {
723750 ...about,
@@ -790,6 +817,16 @@ export function decisionsFor(
790817 says: `The planner declined the direction: \u201c${c.decline.words}\u201d. It plans nothing more until you answer on #${c.issue.number}.`,
791818 short: `the planner declined the direction: \u201c${c.decline.words}\u201d`,
792819 };
820 if (c.kind === "proposed" && c.wave)
821 return {
822 kind: "proposed",
823 id: `proposed:${c.wave.id}`,
824 repo: c.repo,
825 wave: c.wave,
826 who: c.who,
827 says: `${c.who} proposes the wave \u201c${c.wave.title}\u201d toward ${c.wave.milestone}: ${c.wave.why}`,
828 short: `a wave toward ${c.wave.milestone}: \u201c${c.wave.title}\u201d`,
829 };
793830 if (c.kind === "stopped" && c.pull) {
794831 const tries = c.tries ?? 0;
795832 const stopped = c.stoppedByDecider ?? false;
@@ -857,6 +894,13 @@ const askFormId = (d: Decision): string => `ask-${d.id}`;
857894 * HTML; the button reaches it by id.
858895 */
859896 export function decisionForm(d: Decision): Html | null {
897 if (d.kind === "proposed" && d.wave)
898 return html`<form
899 id="${askFormId(d)}"
900 method="post"
901 hidden
902 action="${repoBase(d.repo)}/waves/${d.wave.id}/decide"
903 ></form>`;
860904 const pull = d.pull;
861905 if (pull === undefined) return null;
862906 const base = repoBase(d.repo);
@@ -916,6 +960,29 @@ export function decisionButtons(ctx: Ctx, d: Decision): { primary: Html; others:
916960 }),
917961 ],
918962 };
963 if (d.kind === "proposed" && d.wave)
964 return {
965 primary: btn("Approve", {
966 name: "decision",
967 value: "approve",
968 form: askFormId(d),
969 size: "sm",
970 variant: "primary",
971 }),
972 others: [
973 html`<input
974 class="input"
975 type="text"
976 name="words"
977 form="${askFormId(d)}"
978 maxlength="2000"
979 placeholder="Or say where the plan should go instead"
980 aria-label="Redirect the plan: say where it should go"
981 />`,
982 btn("Redirect", { name: "decision", value: "redirect", form: askFormId(d), size: "sm" }),
983 btn("Later", { name: "decision", value: "later", form: askFormId(d), size: "sm" }),

Tapping Later takes the card out of the inbox for good (pendingWaves filters on state = 'pending'), and the map hides later waves as well. Nothing on the page leads back to the wave.

984 ],
985 };
919986 if (d.kind === "declined" && d.issue)
920987 return {
921988 primary: btn("Answer", {
@@ -1065,6 +1132,8 @@ export function askTargetsFor(
10651132 else if (ask === undefined) refused.push({ item, reason: "it no longer asks you" });
10661133 else if (ask.kind === "paused")
10671134 refused.push({ item, reason: "a ceiling is raised in the app's settings" });
1135 else if (ask.kind === "proposed")
1136 refused.push({ item, reason: "a planner's wave is approved or redirected on its card" });
10681137 else if (ask.kind === "declined")
10691138 refused.push({ item, reason: "a planner's decline is answered on its issue" });
10701139 else issueIds.push((ask.pull ?? ask.issue)!.id);
src/web/studio/asks_page.ts +17 −4
@@ -148,6 +148,14 @@ const clause = (
148148 >
149149 </p>`;
150150
151 /** A proposed wave's issues, in the order they would open, so the nod is an informed one. */
152 const waveIssues = (d: Decision): Html | null =>
153 d.wave === undefined
154 ? null
155 : html`<ol class="small wave-issues">
156 ${d.wave.items.map((item) => html`<li>${item.title}</li>`)}
157 </ol>`;
158
151159 /** The kind, in two words: what a phone's row says in place of the sentence under it. */
152160 const KIND_LABEL: Readonly<Record<Decision["kind"], string>> = {
153161 look: "Ready to ship",
@@ -156,6 +164,7 @@ const KIND_LABEL: Readonly<Record<Decision["kind"], string>> = {
156164 parked: "Parked",
157165 declined: "Declined",
158166 paused: "Paused",
167 proposed: "Plan to approve",
159168 };
160169
161170 /**
@@ -178,13 +187,15 @@ function acts(ctx: Ctx, d: Decision): Html {
178187
179188 function decisionCard(ctx: Ctx, d: Decision, picked: ReadonlySet<string>): Html {
180189 const base = repoBase(d.repo);
181 const title = d.pull
190 const title = d.wave
191 ? html`<a href="${base}/map#wave-${d.wave.id}">${d.wave.title}</a>`
192 : d.pull
182193 ? html`<a href="${changeHref(base, d.pull.number)}">${d.pull.title}</a>`
183194 : d.issue
184195 ? html`<a href="${base}/issues/${d.issue.number}">${d.issue.title}</a>`
185196 : html`<a href="${base}/settings/autonomy">Paused</a>`;
186197 return card(
187 html`${clause(d, d.kind, d.consequence)}
198 html`${clause(d, d.kind, d.consequence)}${waveIssues(d)}
188199 ${acts(ctx, d)}`,
189200 {
190201 id: askAnchor(d.id),
@@ -211,13 +222,15 @@ function rowCard(ctx: Ctx, r: AskRow<Decision>, picked: ReadonlySet<string>): Ht
211222 const base = repoBase(r.repo);
212223 const lines = r.items.map((d) => {
213224 const number = d.pull?.number ?? d.issue?.number;
214 const href = d.pull
225 const href = d.wave
226 ? `${base}/map#wave-${d.wave.id}`
227 : d.pull
215228 ? changeHref(base, d.pull.number)
216229 : `${base}/issues/${String(number)}`;
217230 const box = pick(d, picked);
218231 return row({
219232 ...(box === null ? {} : { lead: box }),
220 title: html`<a href="${href}">${d.pull?.title ?? d.issue?.title ?? ""}</a>`,
233 title: html`<a href="${href}">${d.wave?.title ?? d.pull?.title ?? d.issue?.title ?? ""}</a>`,
221234 meta: acts(ctx, d),
222235 });
223236 });
src/web/studio/crew.ts +15
@@ -340,6 +340,21 @@ ${repo.autonomyDirection}</textarea
340340 type: "number",
341341 hint: "Agent runs at once here. This is the WIP limit.",
342342 })}
343 <div class="field">
344 <label class="check">
345 <input
346 type="checkbox"
347 name="plansNeedNod"
348 ${repo.plansNeedNod ? html`checked` : null}
349 />
350 <span
351 >Plans need a nod — the planner proposes a wave (a title, why,
352 three to six issues in order) as one card in your inbox. Approve
353 opens the issues, linked and ready; Redirect re-plans from your
354 words. Off, the planner opens issues on the map itself.</span
355 >
356 </label>
357 </div>
343358 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
344359 </form>`;
345360 // An autonomous repository with no reviewer lands nothing an agent wrote
src/web/studio/home.ts +1 −1
@@ -55,7 +55,7 @@ import { spawnedOrg } from "../../spawn/claim.ts";
5555
5656 /** The events that can change what is on you. */
5757 const ON_YOU_LIVE =
58 "issue.assigned,pull.assigned,issue.closed,pull.closed,issue.reopened,pull.reopened,pull.merged,fleet.operated";
58 "issue.assigned,pull.assigned,issue.closed,pull.closed,issue.reopened,pull.reopened,pull.merged,wave.*,fleet.operated";
5959 /** The events that can change how an app on the rail is. */
6060 const APPS_LIVE = "app.serving,app.stopped,run.finished";
6161 /** How many of your apps the rail names before "All apps". */
test/mcp.test.ts +1
@@ -196,6 +196,7 @@ describe("the forge over MCP", () => {
196196 "attach_look",
197197 "hold",
198198 "plan",
199 "decide",
199200 "capacity",
200201 "report",
201202 ]);
test/plan-nod.test.ts added +425
@@ -0,0 +1,425 @@
1 /**
2 * The owner approves the plan (#1114). Where plans need a nod, the crew's
3 * planner opens no issues: it proposes a wave. Approving opens the issues
4 * with the links the proposal named; redirecting sends the planner back with
5 * the owner's words in its prompt; the inbox shows one card; the map reads
6 * as waves; and the MCP says the same.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { addToCrew, createAgent } from "../src/actions/crew.ts";
15 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
16 import { decideWave, submitPlan } from "../src/actions/waves.ts";
17 import { setCrewRole } from "../src/core/agents.ts";
18 import { dependenciesOf } from "../src/core/dependencies.ts";
19 import { getIssue, listIssues, setIssueState } from "../src/core/issues.ts";
20 import { listComments } from "../src/core/issues.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 { listWaves } from "../src/core/waves.ts";
25 import { systemPrompt, taskPrompt } from "../src/crew/brief.ts";
26 import { getAgent } from "../src/core/agents.ts";
27 import { serve, type Servers } from "../src/http/server.ts";
28 import { askLinesFor } from "../src/web/studio/asks.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30
31 quietLogs();
32
33 const ISSUES = [
34 { key: "a", title: "Cut the engine out", body: "move it" },
35 { key: "b", title: "Give it a test", blockedBy: ["a"] },
36 { key: "c", title: "Document it", blockedBy: ["a", "b"] },
37 ];
38 const WAVE = {
39 title: "Engine out",
40 why: "A second game needs the engine.",
41 milestone: "Two games",
42 issues: ISSUES,
43 };
44
45 describe("plans need a nod", () => {
46 let dataDir = "";
47 let app: App;
48 let servers: Servers;
49 let alice: User;
50 let chart: User;
51 let repo: Repo;
52 let rw = "";
53 let nextId = 1;
54
55 const getWaveState = (id: string) => listWaves(app.db, repo.id).find((w) => w.id === id)?.state;
56 const fresh = (): Repo => getRepoById(app.db, repo.id)!;
57 const issueCount = (): number => listIssues(app.db, repo.id, {}).length;
58
59 const tool = async (name: string, args: unknown) => {
60 const res = await fetch(`${servers.url}/mcp`, {
61 method: "POST",
62 headers: {
63 "content-type": "application/json",
64 accept: "application/json, text/event-stream",
65 authorization: `Bearer ${rw}`,
66 },
67 body: JSON.stringify({
68 jsonrpc: "2.0",
69 id: nextId++,
70 method: "tools/call",
71 params: { name, arguments: args },
72 }),
73 });
74 const body = (await res.json()) as any;
75 const text: string = body.result.content[0].text;
76 return body.result.isError === true
77 ? { error: text, value: undefined }
78 : { error: undefined, value: JSON.parse(text) };
79 };
80
81 beforeAll(async () => {
82 dataDir = await mkdtemp(join(tmpdir(), "forge-nod-"));
83 app = createApp({ dataDir, port: 0 });
84 servers = await serve(app);
85 const a = await createUser(app.db, {
86 trusted: true,
87 username: "alice",
88 email: "[email protected]",
89 password: "a-good-passphrase",
90 adminIfFirst: true,
91 });
92 if (!a.ok) throw new Error(a.error);
93 alice = a.value;
94 rw = createToken(app.db, alice.id, "rw", "rw").token;
95 const made = await createRepo(app, alice, { name: "garden", visibility: "private" });
96 if (!made.ok) throw new Error(String(made.error));
97 repo = made.value;
98 const agent = await createAgent(app, alice, { username: "chart" });
99 if (!agent.ok) throw new Error(String(agent.error));
100 expect(addToCrew(app, alice, repo, "chart").ok).toBe(true);
101 chart = getUserByName(app.db, "chart")!;
102 setCrewRole(app.db, repo.id, chart.id, "planner");
103 const set = await updateRepoSettings(app, alice, repo, {
104 autonomy: "assisted",
105 autonomyDirection: "Pull the engine out so a second game can use it.",
106 } as never);
107 if (!set.ok) throw new Error(String(set.error));
108 repo = fresh();
109 }, 30_000);
110
111 afterAll(async () => {
112 servers.stop();
113 app.close();
114 await rm(dataDir, { recursive: true, force: true });
115 });
116
117 test("the setting is on by default", () => {
118 expect(repo.plansNeedNod).toBe(true);
119 });
120
121 test("with it on, the planner's plan opens no issues: it is a wave", () => {
122 const before = issueCount();
123 const made = submitPlan(app, chart, repo, WAVE);
124 expect(made.ok).toBe(true);
125 if (!made.ok || !("proposed" in made.value)) throw new Error("not proposed");
126 expect(issueCount()).toBe(before);
127 const wave = made.value.proposed;
128 expect(wave.state).toBe("pending");
129 expect(wave.milestone).toBe("Two games");
130 expect(wave.items.map((i) => i.key)).toEqual(["a", "b", "c"]);
131 });
132
133 test("a wave is three to six issues, with a title, a why and a milestone", () => {
134 const two = submitPlan(app, chart, repo, { ...WAVE, issues: ISSUES.slice(0, 2) });
135 expect(two.ok ? "" : two.error.error).toBe("wave_size");
136 const seven = submitPlan(app, chart, repo, {
137 ...WAVE,
138 issues: Array.from({ length: 7 }, (_, i) => ({ key: `k${i}`, title: `t${i}` })),
139 });
140 expect(seven.ok ? "" : seven.error.error).toBe("wave_size");
141 for (const missing of ["title", "why", "milestone"] as const) {
142 const bad = submitPlan(app, chart, repo, { ...WAVE, [missing]: " " });
143 expect(bad.ok).toBe(false);
144 }
145 const loop = submitPlan(app, chart, repo, {
146 ...WAVE,
147 issues: [
148 { key: "a", title: "A", blockedBy: ["c"] },
149 { key: "b", title: "B", blockedBy: ["a"] },
150 { key: "c", title: "C", blockedBy: ["b"] },
151 ],
152 });
153 expect(loop.ok ? "" : loop.error.error).toBe("cycle");
154 });
155
156 test("the proposal is one card in the owner's inbox, with its issues and three answers", () => {
157 const lines = askLinesFor(app.db, alice).filter((l) => l.kind === "proposed");
158 expect(lines.length).toBe(1);
159 expect(lines[0]!.line).toContain("Engine out");
160 expect(lines[0]!.words.options).toEqual(["Approve", "Redirect", "Later"]);
161 });
162
163 test("an agent never decides a wave", () => {
164 const wave = listWaves(app.db, repo.id)[0]!;
165 const refused = decideWave(app, chart, repo, wave.id, "approve");
166 expect(refused.ok ? "" : refused.error.error).toBe("forbidden");
167 expect(issueCount()).toBe(0);
168 });
169
170 test("approval opens the issues with the dependencies the proposal named", () => {
171 const wave = listWaves(app.db, repo.id)[0]!;
172 const done = decideWave(app, alice, repo, wave.id, "approve");
173 expect(done.ok).toBe(true);
174 if (!done.ok) return;
175 const n = done.value.wave.numbers;
176 expect(Object.keys(n).sort()).toEqual(["a", "b", "c"]);
177 const waits = (key: string): number[] =>
178 dependenciesOf(app.db, getIssue(app.db, repo.id, n[key]!)!.id)
179 .blockedBy.map((i: { number: number }) => i.number)
180 .sort();
181 expect(waits("a")).toEqual([]);
182 expect(waits("b")).toEqual([n.a!]);
183 expect(waits("c")).toEqual([n.a!, n.b!].sort());
184 expect(done.value.planned!.ready).toEqual([n.a!]);
185 // Decided once.
186 const again = decideWave(app, alice, repo, wave.id, "approve");
187 expect(again.ok ? "" : again.error.error).toBe("decided");
188 // No longer asks.
189 expect(askLinesFor(app.db, alice).some((l) => l.kind === "proposed")).toBe(false);
190 });
191
192 test("the map reads as waves, with what landed and what is left", async () => {
193 const wave = listWaves(app.db, repo.id)[0]!;
194 setIssueState(app.db, getIssue(app.db, repo.id, wave.numbers.a!)!.id, "closed");
195 const res = await fetch(`${servers.url}/alice/garden/map`, {
196 headers: { authorization: `Bearer ${rw}` },
197 });
198 const text = await res.text();
199 // The wave's row, under its milestone, with the tally.
200 expect(text).toContain("Two games");
201 expect(text).toContain("Engine out");
202 expect(text).toContain("1 landed, 2 left");
203 expect(text).toContain("?graph=1");
204 const graph = await fetch(`${servers.url}/alice/garden/map?graph=1`, {
205 headers: { authorization: `Bearer ${rw}` },
206 });
207 expect(await graph.text()).toContain("Back to the waves");
208 });
209
210 test("redirect re-runs the planner with the words, and opens nothing", () => {
211 const made = submitPlan(app, chart, repo, { ...WAVE, title: "Engine again" });
212 if (!made.ok || !("proposed" in made.value)) throw new Error("not proposed");
213 const before = issueCount();
214 const words = "Start with the save format, not the engine.";
215 const done = decideWave(app, alice, repo, made.value.proposed.id, "redirect", words);
216 expect(done.ok).toBe(true);
217 expect(issueCount()).toBe(before + 1); // the direction issue, nothing else
218 expect(done.ok && done.value.wave.state).toBe("redirected");
219 const dir = listIssues(app.db, repo.id, {}).find((i) => i.title.startsWith("Direction"))!;
220 expect(dir.assigneeId).toBe(chart.id);
221 const comments = listComments(app.db, dir.id);
222 expect(comments.some((c) => c.body.includes(words))).toBe(true);
223 // And it is in the planner's prompt.
224 const prompt = taskPrompt({
225 agent: getAgent(app.db, chart.id)!,
226 repo: fresh(),
227 issue: dir,
228 branch: "x",
229 forgeUrl: "http://forge.test",
230 isApp: false,
231 resuming: false,
232 role: "planner",
233 reason: "assigned",
234 comments,
235 reviews: [],
236 reviewComments: [],
237 since: "",
238 } as never);
239 expect(prompt).toContain(words);
240 // A redirect with no words is refused.
241 const other = submitPlan(app, chart, repo, { ...WAVE, title: "Third" });
242 if (!other.ok || !("proposed" in other.value)) throw new Error("not proposed");
243 const empty = decideWave(app, alice, repo, other.value.proposed.id, "redirect", " ");
244 expect(empty.ok ? "" : empty.error.error).toBe("empty_words");
245 });
246
247 test("every decision says so on the bus, so open pages repaint", () => {
248 const kinds = new Set(
249 (app.db.query("SELECT kind FROM event WHERE kind LIKE 'wave.%'").all() as { kind: string }[]).map(
250 (e) => e.kind,
251 ),
252 );
253 expect(kinds.has("wave.approved")).toBe(true);
254 expect(kinds.has("wave.redirected")).toBe(true);
255 });
256
257 test("later sets a wave aside without opening it; the planner is told how to propose", () => {
258 const wave = listWaves(app.db, repo.id).find((w) => w.title === "Third")!;
259 const before = issueCount();
260 const done = decideWave(app, alice, repo, wave.id, "later");
261 expect(done.ok && done.value.wave.state).toBe("later");
262 expect(
263 (app.db.query("SELECT COUNT(*) AS n FROM event WHERE kind = 'wave.later'").get() as { n: number }).n,
264 ).toBe(1);
265 expect(issueCount()).toBe(before);
266 const prompt = systemPrompt({
267 agent: getAgent(app.db, chart.id)!,
268 repo: fresh(),
269 issue: listIssues(app.db, repo.id, {})[0]!,
270 branch: "x",
271 forgeUrl: "http://forge.test",
272 isApp: false,
273 resuming: false,
274 role: "planner",
275 });
276 expect(prompt).toContain("Plans need the owner's nod");
277 expect(prompt).toContain("/plan");
278 });
279
280 test("a person's own plan opens at once; with the setting off, so does the planner's", async () => {
281 const mine = submitPlan(app, alice, repo, { issues: ISSUES });
282 expect(mine.ok && "opened" in mine.value).toBe(true);
283 const off = await updateRepoSettings(app, alice, repo, { plansNeedNod: false } as never);
284 if (!off.ok) throw new Error(String(off.error));
285 const theirs = submitPlan(app, chart, fresh(), { issues: ISSUES });
286 expect(theirs.ok && "opened" in theirs.value).toBe(true);
287 const back = await updateRepoSettings(app, alice, fresh(), { plansNeedNod: true } as never);
288 if (!back.ok) throw new Error(String(back.error));
289 });
290
291 test("an agent cannot turn the nod off", async () => {
292 const off = await updateRepoSettings(app, chart, fresh(), { plansNeedNod: false } as never);
293 expect(off.ok).toBe(false);
294 });
295
296 test("MCP: plan returns the proposal, reads the waves; decide approves", async () => {
297 const proposed = submitPlan(app, chart, fresh(), { ...WAVE, title: "Via MCP" });
298 if (!proposed.ok || !("proposed" in proposed.value)) throw new Error("not proposed");
299 const read = await tool("plan", { app: "alice/garden" });
300 expect(read.value.waves.map((w: any) => w.title)).toContain("Via MCP");
301 expect(read.value.says).toContain("Via MCP");
302 const before = issueCount();
303 const bad = await tool("decide", { app: "alice/garden", wave: proposed.value.proposed.id, decision: "maybe" });
304 expect(bad.error).toContain("invalid");
305 const yes = await tool("decide", { app: "alice/garden", wave: proposed.value.proposed.id, decision: "approve" });
306 expect(yes.value.opened.length).toBe(3);
307 expect(issueCount()).toBe(before + 3);
308 });
309
310 test("API: the crew's POST /plan proposes; the decide route redirects", async () => {
311 const agentToken = createToken(app.db, chart.id, "run", "rw").token;
312 const before = issueCount();
313 const res = await fetch(`${servers.url}/api/v1/repos/alice/garden/plan`, {
314 method: "POST",
315 headers: { authorization: `Bearer ${agentToken}`, "content-type": "application/json" },
316 body: JSON.stringify(WAVE),
317 });
318 expect(res.status).toBe(202);
319 const { proposed } = (await res.json()) as any;
320 expect(issueCount()).toBe(before);
321 // The agent cannot decide its own wave.
322 const no = await fetch(`${servers.url}/api/v1/repos/alice/garden/waves/${proposed.id}/decide`, {
323 method: "POST",
324 headers: { authorization: `Bearer ${agentToken}`, "content-type": "application/json" },
325 body: JSON.stringify({ decision: "approve" }),
326 });
327 expect(no.status).toBe(403);
328 const yes = await fetch(`${servers.url}/api/v1/repos/alice/garden/waves/${proposed.id}/decide`, {
329 method: "POST",
330 headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" },
331 body: JSON.stringify({ decision: "redirect", words: "smaller, please" }),
332 });
333 expect(yes.status).toBe(200);
334 expect(issueCount()).toBe(before);
335 });
336
337 test("the inbox card is one tap: Approve posts to the wave's own route", async () => {
338 const proposed = submitPlan(app, chart, fresh(), { ...WAVE, title: "From the card" });
339 if (!proposed.ok || !("proposed" in proposed.value)) throw new Error("not proposed");
340 const wave = proposed.value.proposed;
341 const signin = await fetch(`${servers.url}/signin`, {
342 method: "POST",
343 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
344 redirect: "manual",
345 });
346 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
347 const home = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
348 expect(home).toContain("From the card");
349 expect(home).toContain(`/alice/garden/waves/${wave.id}/decide`);
350 expect(home).toContain('value="approve"');
351 expect(home).toContain('value="redirect"');
352 expect(home).toContain('value="later"');
353 const before = issueCount();
354 const post = await fetch(`${servers.url}/alice/garden/waves/${wave.id}/decide`, {
355 method: "POST",
356 headers: { cookie, origin: servers.url },
357 body: new URLSearchParams({ decision: "approve" }),
358 redirect: "manual",
359 });
360 expect(post.status).toBe(303);
361 expect(issueCount()).toBe(before + 3);
362 });
363
364 test("a wave set aside stays on the map with its buttons, and is approved from there", async () => {
365 const proposed = submitPlan(app, chart, fresh(), { ...WAVE, title: "Set aside, then back" });
366 if (!proposed.ok || !("proposed" in proposed.value)) throw new Error("not proposed");
367 const wave = proposed.value.proposed;
368 const signin = await fetch(`${servers.url}/signin`, {
369 method: "POST",
370 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
371 redirect: "manual",
372 });
373 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
374 const later = await fetch(`${servers.url}/alice/garden/waves/${wave.id}/decide`, {
375 method: "POST",
376 headers: { cookie, origin: servers.url },
377 body: new URLSearchParams({ decision: "later" }),
378 redirect: "manual",
379 });
380 expect(later.status).toBe(303);
381 const inbox = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
382 expect(inbox).not.toContain(`/waves/${wave.id}/decide`);
383 // An issue a person opened by hand is on the map too, under its own heading.
384 const own = submitPlan(app, alice, fresh(), {
385 issues: [{ key: "z", title: "Opened by hand zzz" }],
386 });
387 expect(own.ok).toBe(true);
388 const map = await (await fetch(`${servers.url}/alice/garden/map`, { headers: { cookie } })).text();
389 expect(map).toContain("Set aside, then back");
390 // The waves view is a live region: a decision made elsewhere repaints it.
391 expect(map).toMatch(/id="map-waves"\s+data-live="wave\.\*,issue\.\*,pull\.\*"/);
392 expect(map).toContain("data-live-repo");
393 expect(inbox).toContain("wave.*");
394 expect(map).toContain("set aside for later");
395 expect(map).toContain(`/alice/garden/waves/${wave.id}/decide`);
396 expect(map).toContain("Outside the waves");
397 expect(map).toContain("Opened by hand zzz");
398 const before = issueCount();
399 const post = await fetch(`${servers.url}/alice/garden/waves/${wave.id}/decide`, {
400 method: "POST",
401 headers: { cookie, origin: servers.url },
402 body: new URLSearchParams({ decision: "approve" }),
403 redirect: "manual",
404 });
405 expect(post.status).toBe(303);
406 expect(issueCount()).toBe(before + 3);
407 expect(getWaveState(wave.id)).toBe("approved");
408 });
409
410 test("the planner's worked example is a wave the forge accepts", () => {
411 const prompt = systemPrompt({
412 agent: getAgent(app.db, chart.id)!,
413 repo: fresh(),
414 issue: listIssues(app.db, repo.id, {})[0]!,
415 branch: "x",
416 forgeUrl: "http://forge.test",
417 isApp: false,
418 resuming: false,
419 role: "planner",
420 });
421 const line = prompt.split("\n").find((l) => l.includes('"milestone"'))!;
422 const body = JSON.parse(line.slice(line.indexOf("-d '") + 4, line.lastIndexOf("'")));
423 expect(body.issues.length).toBeGreaterThanOrEqual(3);
424 });
425 });
test/tui-waves.test.ts added +149
@@ -0,0 +1,149 @@
1 /**
2 * `M` in the terminal (#1114): pick a wave, then approve it, redirect it, or
3 * set it aside — through the same action the page and the MCP call, so a
4 * reader who cannot write is refused and nothing opens.
5 */
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 { addTeamMember, createOrg, createTeam } from "../src/actions/orgs.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { signUp } from "../src/actions/users.ts";
14 import { createApp, type App as Forge } from "../src/app.ts";
15 import { listIssues } from "../src/core/issues.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import type { User } from "../src/core/users.ts";
18 import { createWave, decideWave as writeDecision, listWaves } from "../src/core/waves.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import type { TuiIdentity } from "../src/tui/session.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 quietLogs();
26
27 const ITEMS = [
28 { key: "a", title: "Cut the engine out", body: "move it", blockedBy: [] },
29 { key: "b", title: "Give it a test", body: "", blockedBy: ["a"] },
30 { key: "c", title: "Document it", body: "", blockedBy: ["a", "b"] },
31 ];
32
33 describe("M: waves in the terminal", () => {
34 let dataDir = "";
35 let forge: Forge;
36 let alice: User;
37 let bob: User;
38 let repo: Repo;
39
40 const wave = (title: string) =>
41 createWave(forge.db, {
42 repoId: repo.id,
43 authorId: alice.id,
44 title,
45 why: "A second game needs it.",
46 milestone: "Two games",
47 items: ITEMS,
48 });
49 const issues = () => listIssues(forge.db, repo.id, {}).length;
50 const stateOf = (id: string) => listWaves(forge.db, repo.id).find((w) => w.id === id)?.state;
51
52 /** Sign in as `user`, open the repository, press M, pick the wave, press `then`. */
53 async function drive(user: User, ...then: string[]): Promise<string> {
54 const identity: TuiIdentity = {
55 sshUsername: user.username,
56 remoteAddress: "127.0.0.1",
57 fingerprint: `SHA256:${user.username}`,
58 user,
59 };
60 const terminal = headlessTerminal(140, 44);
61 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
62 app.start();
63 const press = async (key: string) => {
64 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: key === "M" });
65 await settleApp(app);
66 };
67 const until = async (what: string) => {
68 for (let i = 0; i < 500 && !app.screen.toText().includes(what); i++) {
69 await settleApp(app);
70 await new Promise((r) => setTimeout(r, 10));
71 }
72 if (!app.screen.toText().includes(what))
73 throw new Error(`never saw ${what}:\n${app.screen.toText()}`);
74 };
75 try {
76 await until("acme/lighthouse");
77 await press("enter");
78 await until("README");
79 await press("M");
80 await until("Waves waiting for a nod");
81 await press("enter");
82 for (const key of then) await press(key);
83 return app.screen.toText();
84 } finally {
85 app.stop();
86 }
87 }
88
89 beforeAll(async () => {
90 dataDir = await mkdtemp(join(tmpdir(), "forge-tuiwaves-"));
91 forge = createApp({ dataDir, port: 0 });
92 const one = await signUp(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
93 const two = await signUp(forge, { username: "bob", email: "[email protected]", password: "another-long-passphrase" });
94 if (!one.ok || !two.ok) throw new Error("signup failed");
95 alice = one.value;
96 bob = two.value;
97 // Bob is on a team that reads: he sees the repository and cannot decide.
98 const org = createOrg(forge, alice, "acme");
99 if (!org.ok) throw new Error("org failed");
100 const team = createTeam(forge, alice, org.value, "Readers", "read");
101 if (!team.ok) throw new Error("team failed");
102 addTeamMember(forge, alice, org.value, team.value, "bob");
103 const made = await createRepo(forge, alice, { owner: "acme", name: "lighthouse", visibility: "private" });
104 if (!made.ok) throw new Error("repo failed");
105 repo = made.value;
106 await commitToBranch(forge, alice, repo, {
107 message: "seed",
108 files: [{ path: "README.md", content: "# Lighthouse\n" }],
109 });
110 }, 60_000);
111
112 afterAll(async () => {
113 forge.close();
114 await rm(dataDir, { recursive: true, force: true });
115 });
116
117 /** Clear the board between tests: a decided wave is no longer waiting. */
118 const clear = (id: string) => writeDecision(forge.db, id, "redirected", alice.id);
119 const events = (kind: string) =>
120 (forge.db.query("SELECT COUNT(*) AS n FROM event WHERE kind = ?1").get(kind) as { n: number }).n;
121
122 test("a reader who cannot write is refused and nothing opens", async () => {
123 const w = wave("Refused");
124 const screen = await drive(bob, "enter");
125 expect(screen).toContain("only a person who writes here decides a wave");
126 expect(issues()).toBe(0);
127 expect(stateOf(w.id)).toBe("pending");
128 clear(w.id);
129 });
130
131 test("Later sets the wave aside and says so on the bus", async () => {
132 const w = wave("Later");
133 const before = events("wave.later");
134 await drive(alice, "j", "j", "enter");
135 expect(stateOf(w.id)).toBe("later");
136 expect(issues()).toBe(0);
137 expect(events("wave.later")).toBe(before + 1);
138 clear(w.id);
139 });
140
141 test("Approve opens the issues, linked", async () => {
142 const w = wave("Approved");
143 const before = events("wave.approved");
144 await drive(alice, "enter");
145 expect(stateOf(w.id)).toBe("approved");
146 expect(issues()).toBe(3);
147 expect(events("wave.approved")).toBe(before + 1);
148 });
149 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs