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

Plans need a nod: with the setting on, POST …/plan stores one wave proposal and opens no issues #1743

Closed opened this
Closed without merging

scout/forge:scout/1621-plans-need-a-nod-with-the-setting-on-pos → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +309 −4
scripts/gate.ts +1
@@ -34,6 +34,7 @@ export const GATE: readonly string[] = [
3434 "test/apps-idle.test.ts",
3535 "test/body-limits.test.ts",
3636 "test/boards-query.test.ts",
37 "test/plan-nod.test.ts",
3738 "test/turnstile.test.ts",
3839 "test/thoughts.test.ts",
3940 "test/passkeys.test.ts",
src/actions/plan.ts +52 −1
@@ -25,6 +25,7 @@ import {
2525 import { canRead, canWrite, type Repo } from "../core/repos.ts";
2626 import type { User } from "../core/users.ts";
2727 import { transact } from "../kernel/db.ts";
28 import { storeProposal } from "../core/proposals.ts";
2829 import { err, ok, type Result } from "../kernel/result.ts";
2930 import { isMirror } from "../origins/write-through.ts";
3031 import { followLink } from "./pillars.ts";
@@ -186,12 +187,47 @@ function loopAt(items: readonly PlanItem[]): string | undefined {
186187 return undefined;
187188 }
188189
190 /** A plan held for a nod: stored whole, no issue opened. */
191 export interface Proposed {
192 readonly proposed: true;
193 readonly proposal: string;
194 }
195
196 /** What the sender may say about a plan: a title and a one-line why. */
197 export interface PlanPitch {
198 readonly title?: unknown;
199 readonly why?: unknown;
200 }
201
202 function pitchOf(
203 items: readonly PlanItem[],
204 pitch: PlanPitch,
205 ): Result<{ title: string; why: string }, PlanError> {
206 const text = (v: unknown) => (typeof v === "string" ? v : undefined);
207 if (
208 (pitch.title !== undefined && text(pitch.title) === undefined) ||
209 (pitch.why !== undefined && text(pitch.why) === undefined)
210 )
211 return refuse("invalid", "title and why must be text");
212 const why = (text(pitch.why) ?? "").trim().replace(/\s+/g, " ");
213 if (why.length > WHY_MAX)
214 return refuse(
215 "why_too_long",
216 `why is one sentence, at most ${WHY_MAX} characters`,
217 );
218 const title = (text(pitch.title) ?? "").trim().replace(/\s+/g, " ");
219 if (title.length > MAX_TITLE)
220 return refuse("title_too_long", `title is over ${MAX_TITLE} characters`);
221 return ok({ title: title || items[0]!.title, why });
222 }
223
189224 export function openPlan(
190225 app: App,
191226 actor: User | undefined,
192227 repo: Repo,
193228 items: readonly PlanItem[],
194 ): Result<Planned, PlanError> {
229 pitch: PlanPitch = {},
230 ): Result<Planned | Proposed, PlanError> {
195231 if (!actor || !canRead(app.db, repo, actor))
196232 return refuse("not_found", "no such app or repository (owner/name)");
197233 if (!canWrite(app.db, repo, actor) && !isCrew(app.db, repo.id, actor.id))
@@ -259,6 +295,21 @@ export function openPlan(
259295 );
260296 }
261297
298 // With "plans need a nod" on, the plan is good and is kept as it is: one
299 // proposal, for a person to approve. No issue exists until then.
300 if (repo.plansNeedNod) {
301 const said = pitchOf(items, pitch);
302 if (!said.ok) return err(said.error);
303 const proposal = storeProposal(app.db, {
304 repoId: repo.id,
305 authorId: actor.id,
306 title: said.value.title,
307 why: said.value.why,
308 items,
309 });
310 return ok({ proposed: true, proposal });
311 }
312
262313 const opened: { key: string; number: number }[] = [];
263314 /** The links an item's purpose adds: [the issue that waits, what it waits for]. */
264315 const purpose: [Issue, Issue][] = [];
src/actions/repos.ts +1
@@ -270,6 +270,7 @@ export async function updateRepoSettings(
270270 "requireReview",
271271 "requireChecks",
272272 "crewOutsiders",
273 "plansNeedNod",
273274 ] as const
274275 ).filter((k) => settings[k] !== undefined && settings[k] !== repo[k]);
275276 app.bus.append({
src/core/proposals.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * A plan held for a nod: the validated wave kept as one row, with a title,
3 * a one-line why, its issues in order and their blockedBy links. Plain data
4 * in, plain data out; opening the issues is a later step.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { id } from "../kernel/id.ts";
9
10 export interface ProposedItem {
11 readonly key: string;
12 readonly title: string;
13 readonly body: string;
14 readonly blockedBy: readonly (string | number)[];
15 readonly pillar?: string;
16 readonly later?: string;
17 }
18
19 export interface Proposal {
20 readonly id: string;
21 readonly repoId: string;
22 readonly authorId: string;
23 readonly title: string;
24 readonly why: string;
25 readonly items: readonly ProposedItem[];
26 readonly createdAt: string;
27 }
28
29 export function storeProposal(
30 db: Database,
31 p: Omit<Proposal, "id" | "createdAt">,
32 ): string {
33 const newId = id();
34 db.query(
35 `INSERT INTO plan_proposal (id, repo_id, author_id, title, why, items, created_at)
36 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
37 ).run(
38 newId,
39 p.repoId,
40 p.authorId,
41 p.title,
42 p.why,
43 JSON.stringify(p.items),
44 new Date().toISOString(),
45 );
46 return newId;
47 }
48
49 interface Row {
50 id: string;
51 repo_id: string;
52 author_id: string;
53 title: string;
54 why: string;
55 items: string;
56 created_at: string;
57 }
58
59 export function proposalsOf(db: Database, repoId: string): Proposal[] {
60 return db
61 .query<Row, [string]>(
62 "SELECT * FROM plan_proposal WHERE repo_id = ?1 ORDER BY created_at, id",
63 )
64 .all(repoId)
65 .map((r) => ({
66 id: r.id,
67 repoId: r.repo_id,
68 authorId: r.author_id,
69 title: r.title,
70 why: r.why,
71 items: JSON.parse(r.items) as ProposedItem[],
72 createdAt: r.created_at,
73 }));
74 }
src/core/repos.ts +12 −1
@@ -116,6 +116,12 @@ 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": a plan sent to `…/plan` is stored as one proposal
121 * (`core/proposals.ts`) for a person to approve, and opens no issues.
122 * On by default.
123 */
124 readonly plansNeedNod: boolean;
119125 /** The issue the planner is given, when the map has run dry. */
120126 readonly directionIssueId: string | null;
121127 /** The repo this was forked from, or null. */
@@ -160,6 +166,7 @@ interface RepoRow {
160166 autonomy_slots: number;
161167 autonomy_by: string | null;
162168 crew_outsiders: number;
169 plans_need_nod: number;
163170 direction_issue_id: string | null;
164171 fork_parent_id: string | null;
165172 sealed_for: string | null;
@@ -197,6 +204,7 @@ function toRepo(row: RepoRow): Repo {
197204 autonomySlots: row.autonomy_slots,
198205 autonomyBy: row.autonomy_by,
199206 crewOutsiders: row.crew_outsiders === 1,
207 plansNeedNod: row.plans_need_nod === 1,
200208 directionIssueId: row.direction_issue_id,
201209 forkParentId: row.fork_parent_id,
202210 sealedFor: row.sealed_for,
@@ -1025,6 +1033,8 @@ export interface RepoSettings {
10251033 autonomyBy?: string | null;
10261034 /** Whether someone who cannot write here may start or steer a run. */
10271035 crewOutsiders?: boolean;
1036 /** Whether a plan is stored as a proposal instead of opening issues. */
1037 plansNeedNod?: boolean;
10281038 }
10291039
10301040 /** Update the mutable repo fields, leaving unspecified ones untouched. */
@@ -1037,7 +1047,7 @@ export function updateRepoSettings(
10371047 `UPDATE repo SET visibility = ?1, description = ?2, protect_default = ?3,
10381048 default_branch = ?4, require_review = ?5, require_checks = ?7,
10391049 autonomy = ?8, autonomy_direction = ?9, autonomy_ceiling_usd = ?10,
1040 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13
1050 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13, 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 +16
@@ -1721,6 +1721,22 @@ export const migrations: readonly string[] = [
17211721 );
17221722 CREATE INDEX release_created ON release(created_at);
17231723 `,
1724 // 84 — plans need a nod (#1621): with the setting on (the default), a plan
1725 // is stored as one proposal for a person to approve, and opens no issues.
1726 // `items` is the validated plan as JSON; the proposal is plain data.
1727 `
1728 ALTER TABLE repo ADD COLUMN plans_need_nod INTEGER NOT NULL DEFAULT 1;
1729 CREATE TABLE plan_proposal (
1730 id TEXT PRIMARY KEY,
1731 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1732 author_id TEXT NOT NULL,
1733 title TEXT NOT NULL,
1734 why TEXT NOT NULL,
1735 items TEXT NOT NULL,
1736 created_at TEXT NOT NULL
1737 );
1738 CREATE INDEX plan_proposal_repo ON plan_proposal(repo_id, created_at);
1739 `,
17241740 ];
17251741
17261742 /**
src/http/api.ts +7 −1
@@ -1753,6 +1753,9 @@ export function apiRoutes(router: Router<Handler>): void {
17531753 ...(typeof input.crewOutsiders === "boolean"
17541754 ? { crewOutsiders: input.crewOutsiders }
17551755 : {}),
1756 ...(typeof input.plansNeedNod === "boolean"
1757 ? { plansNeedNod: input.plansNeedNod }
1758 : {}),
17561759 });
17571760 if (!updated.ok) return respondAccess(updated.error, 422);
17581761 return json(repoJson(ctx, updated.value));
@@ -2516,7 +2519,10 @@ export function apiRoutes(router: Router<Handler>): void {
25162519 const items = parsePlan(input.issues);
25172520 if (!items.ok)
25182521 return apiError(items.error.error, 422, items.error.message);
2519 const planned = openPlan(ctx.app, ctx.auth.user, repo, items.value);
2522 const planned = openPlan(ctx.app, ctx.auth.user, repo, items.value, {
2523 title: input.title,
2524 why: input.why,
2525 });
25202526 if (!planned.ok) {
25212527 const { error, message } = planned.error;
25222528 return apiError(
src/http/mcp.ts +19 −1
@@ -1733,6 +1733,15 @@ const TOOLS: readonly Tool[] = [
17331733 type: "object",
17341734 properties: {
17351735 app: APP_ARG,
1736 title: {
1737 type: "string",
1738 description:
1739 "With plans-need-a-nod on: the proposal's title (defaults to the first issue's).",
1740 },
1741 why: {
1742 type: "string",
1743 description: "With plans-need-a-nod on: one line saying why this wave.",
1744 },
17361745 issues: {
17371746 type: "array",
17381747 minItems: 1,
@@ -1779,8 +1788,17 @@ const TOOLS: readonly Tool[] = [
17791788 if (isAnswer(repo)) return repo;
17801789 const items = parsePlan(args["issues"]);
17811790 if (!items.ok) return bad(items.error.error, items.error.message);
1782 const planned = openPlan(ctx.app, user, repo, items.value);
1791 const planned = openPlan(ctx.app, user, repo, items.value, {
1792 title: args["title"],
1793 why: args["why"],
1794 });
17831795 if (!planned.ok) return bad(planned.error.error, planned.error.message);
1796 if ("proposed" in planned.value)
1797 return good({
1798 says: `Proposed ${items.value.length} issue${items.value.length === 1 ? "" : "s"} as proposal ${planned.value.proposal}; nothing is opened until a person nods.`,
1799 proposed: true,
1800 proposal: planned.value.proposal,
1801 });
17841802 const { opened, ready, later, gate } = planned.value;
17851803 const waits =
17861804 gate === undefined
src/web/pages/settings.ts +17
@@ -284,6 +284,20 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
284284 >
285285 </label>
286286 </div>
287 <div class="field">
288 <input type="hidden" name="plansNeedNodShown" value="1" />
289 <label class="check">
290 <input
291 type="checkbox"
292 name="plansNeedNod"
293 ${repo.plansNeedNod ? html`checked` : null}
294 />
295 <span
296 >Plans need a nod — a plan sent to this repository is kept as one
297 proposal for you to approve, and opens no issues until then.</span
298 >
299 </label>
300 </div>
287301 <div class="field">
288302 <input type="hidden" name="crewOutsidersShown" value="1" />
289303 <label class="check">
@@ -349,6 +363,9 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
349363 ...(form.get("crewOutsidersShown") !== null
350364 ? { crewOutsiders: form.get("crewOutsiders") !== null }
351365 : {}),
366 ...(form.get("plansNeedNodShown") !== null
367 ? { plansNeedNod: form.get("plansNeedNod") !== null }
368 : {}),
352369 ...(branch !== "" ? { defaultBranch: branch } : {}),
353370 };
354371 const updated = await updateRepoSettings(
test/plan-nod.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Invariant: with "plans need a nod" on (the default), `POST …/plan` stores a
3 * valid plan as one proposal and opens no issue; off, it opens issues as
4 * before; an invalid plan is refused either way.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { listIssues } from "../src/core/issues.ts";
14 import { proposalsOf } from "../src/core/proposals.ts";
15 import { getRepoById, updateRepoSettings, type Repo } from "../src/core/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19
20 describe("plans need a nod", () => {
21 let dataDir = "";
22 let app: App;
23 let servers: Servers;
24 let alice: User;
25 let repo: Repo;
26 let rw = "";
27
28 const count = () => listIssues(app.db, repo.id, {}).length;
29 const post = (body: unknown) =>
30 fetch(`${servers.url}/api/v1/repos/alice/nod/plan`, {
31 method: "POST",
32 headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" },
33 body: JSON.stringify(body),
34 });
35 const wave = [
36 { key: "a", title: "Water the beds", pillar: "P0" },
37 { key: "b", title: "Buy a hose", pillar: "P0", blockedBy: ["a"] },
38 ];
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-plannod-"));
42 app = createApp({ dataDir, port: 0 });
43 servers = await serve(app);
44 const a = await createUser(app.db, {
45 trusted: true,
46 username: "alice",
47 email: "[email protected]",
48 password: "a-good-passphrase",
49 adminIfFirst: true,
50 });
51 if (!a.ok) throw new Error(a.error);
52 alice = a.value;
53 rw = createToken(app.db, alice.id, "rw", "rw").token;
54 const made = await createRepo(app, alice, { name: "nod", visibility: "private" });
55 if (!made.ok) throw new Error(String(made.error));
56 repo = made.value;
57 const u = openIssue(app, alice, repo, { title: "P0 Trust: be trusted", body: "" });
58 if (!u.ok) throw new Error(String(u.error));
59 });
60
61 afterAll(async () => {
62 servers.stop();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66
67 test("the setting is on by default", () => {
68 expect(repo.plansNeedNod).toBe(true);
69 });
70
71 test("on: the plan is stored as one proposal and opens no issues", async () => {
72 const before = count();
73 const res = await post({ title: "Garden wave", why: " Beds first,\n then hose. ", issues: wave });
74 expect(res.status).toBe(201);
75 const body = (await res.json()) as { proposed: boolean; proposal: string };
76 expect(body.proposed).toBe(true);
77 expect(count()).toBe(before);
78 const stored = proposalsOf(app.db, repo.id);
79 expect(stored.length).toBe(1);
80 expect(stored[0]!.id).toBe(body.proposal);
81 expect(stored[0]!.title).toBe("Garden wave");
82 expect(stored[0]!.why).toBe("Beds first, then hose.");
83 expect(stored[0]!.items.map((i) => i.key)).toEqual(["a", "b"]);
84 expect(stored[0]!.items[1]!.blockedBy).toEqual(["a"]);
85 });
86
87 test("on: an invalid plan is still refused with no_pillar, and stores nothing", async () => {
88 const res = await post({ issues: [{ key: "a", title: "No pillar" }] });
89 expect(res.status).toBe(422);
90 expect(((await res.json()) as { error: string }).error).toBe("no_pillar");
91 expect(proposalsOf(app.db, repo.id).length).toBe(1);
92 });
93
94 test("off: the plan opens issues as before and stores no proposal", async () => {
95 await updateRepoSettings(app.db, getRepoById(app.db, repo.id)!, { plansNeedNod: false });
96 const before = count();
97 const res = await post({ issues: wave });
98 expect(res.status).toBe(201);
99 const body = (await res.json()) as { opened: unknown[]; proposed?: boolean };
100 expect(body.opened.length).toBe(2);
101 expect(body.proposed).toBeUndefined();
102 expect(count()).toBe(before + 2);
103 expect(proposalsOf(app.db, repo.id).length).toBe(1);
104 });
105 });
test/plan-pillars.test.ts +3
@@ -81,6 +81,8 @@ describe("a plan says what each issue is for", () => {
8181 const repo = async (name: string): Promise<Repo> => {
8282 const made = await createRepo(app, alice, { name, visibility: "private" });
8383 if (!made.ok) throw new Error(String(made.error));
84 // These tests open issues; the nod has its own (plan-nod.test.ts).
85 app.db.run("UPDATE repo SET plans_need_nod = 0 WHERE id = ?1", [made.value.id]);
8486 return made.value;
8587 };
8688
@@ -405,6 +407,7 @@ describe("whose issue stands for a pillar", () => {
405407 });
406408 if (!made.ok) throw new Error(String(made.error));
407409 open = made.value;
410 app.db.run("UPDATE repo SET plans_need_nod = 0 WHERE id = ?1", [open.id]);
408411 }, 30_000);
409412
410413 afterAll(async () => {
test/plan-route.test.ts +2
@@ -50,6 +50,8 @@ describe("POST …/plan", () => {
5050 const created = await createRepo(app, alice, { name: "garden", visibility: "private" });
5151 if (!created.ok) throw new Error(String(created.error));
5252 repo = created.value;
53 // These tests open issues; the nod has its own (plan-nod.test.ts).
54 app.db.run("UPDATE repo SET plans_need_nod = 0 WHERE id = ?1", [repo.id]);
5355 const seeded = await commitToBranch(app, alice, repo, {
5456 message: "Start",
5557 files: [{ path: "README.md", content: "# garden\n" }],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs