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

v1.0.0 is the first chapter: its issues are recorded in it, and it closes only when the proof script passes on production #12507

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/12298-v1-0-0-is-the-first-chapter-its-issues-a → main 15 commits fork 2 threads · 2 unresolved

  • Merged. torque/12298-v1-0-0-is-the-first-chapter-its-issues-a was merged into main as 04724f6.

Review

Sign in to review this change.
14 files changed +538 −253
docs/features/chapters.md +4
@@ -18,3 +18,7 @@ The same tool acts, for the owner: `action` is `open`, `add`, `remove` or `close
1818 A closed chapter's list is frozen, so `itemsOf` keeps it in process memory (at most 200, `forgetFrozenItems` drops them); an open chapter's list is one pass over the repository's pulls and one grouped read of its runs, however many items it holds, so the anonymous page and API read stay cheap.
1919
2020 - **On /next (#12288).** `/:owner/:name/next` has a Chapters section: each chapter with issues closed against its list, and, for the repository's owner, **Close chapter** on the open one (`POST …/chapters/:chapter/close`, same-origin, nothing moves). A chapter with issues still open says which ones are in its way and refuses the close with the same sentence. A close shows its receipt (name, tag) and an **Undo** for 60 seconds (`…/undo`: the tag goes, the chapter is open again); a close that moved items to the next chapter (Ship it) has no undo. The terminal does the same on `src/tui/screens/chapters.ts` (`c`, `u`); its acts append the same events, so an open web page follows.
21
22 ## The first chapter: v1.0.0
23
24 Drafting a chapter named `v1.0.0` records the v1 list's issues in it (the issue of every probe in `scripts/v1-proven.ts`, those that exist in the repository). Closing it (Ship it or Close) runs those read-only probes against the forge's public origin and is refused, naming each probe that does not pass, until every one passes; `unproven` is not a pass. The close tags the default branch's tip and nothing more: a person cuts the release with `scripts/cut-release.ts`.
scripts/unused-exports-allow.json +1
@@ -59,6 +59,7 @@
5959 "src/core/transfer.ts transfersOf",
6060 "src/core/usage.ts USAGE_BY",
6161 "src/core/usage.ts USAGE_OUTCOMES",
62 "src/core/v1_proof.ts useProof",
6263 "src/core/webhooks.ts deliveryBusy",
6364 "src/crew/agent_runner.ts useRunner",
6465 "src/crew/ceiling_stagger.ts forgetStagger",
scripts/v1-proven.ts +2 −237
@@ -9,243 +9,8 @@
99 * A probe is the strongest evidence a stranger's request can read; what only
1010 * a signed-in owner can see is probed as "the page exists and is gated".
1111 */
12
13 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
14 export interface Probe {
15 readonly issue: number;
16 readonly item: string;
17 /** A string is a pass; `unproven(why)` is "seen what a stranger can, not the claim". */
18 readonly run: (get: Get) => Promise<string | Unproven>;
19 }
20 export class Unproven {
21 constructor(readonly why: string) {}
22 }
23 export const unproven = (why: string): Unproven => new Unproven(why);
24 export type Status = "pass" | "fail" | "unproven";
25 export interface Result {
26 readonly issue: number;
27 readonly item: string;
28 readonly status: Status;
29 readonly detail: string;
30 }
31 interface Got {
32 readonly status: number;
33 readonly headers: Headers;
34 readonly text: string;
35 readonly location: string | null;
36 }
37 type Get = (path: string) => Promise<Got>;
38
39 class Fail extends Error {}
40 const fail = (why: string): never => {
41 throw new Fail(why);
42 };
43 const expect = (cond: boolean, why: string): void => {
44 if (!cond) fail(why);
45 };
46
47 async function bodyOk(get: Get, path: string, status = 200): Promise<Got> {
48 const got = await get(path);
49 expect(got.status === status, `${path} answers ${got.status}, not ${status}`);
50 return got;
51 }
52
53 /** The page exists and is gated: a redirect to sign-in, never a 404 or a 5xx. */
54 async function gated(get: Get, path: string): Promise<string> {
55 const got = await get(path);
56 expect(got.status === 303 || got.status === 302, `${path} answers ${got.status}, not a redirect to sign-in`);
57 expect((got.location ?? "").includes("/signin"), `${path} redirects to ${got.location ?? "nowhere"}, not sign-in`);
58 return `${path} is there and asks for sign-in`;
59 }
60
61 const SECURITY_HEADERS: ReadonlyArray<readonly [string, RegExp | null]> = [
62 ["content-security-policy", /default-src/],
63 ["x-content-type-options", /^nosniff$/i],
64 ["referrer-policy", /./],
65 ["strict-transport-security", /max-age=\d+/],
66 ["permissions-policy", /./],
67 ["cross-origin-opener-policy", /./],
68 ];
69
70 export const probes: readonly Probe[] = [
71 {
72 issue: 11541,
73 item: "the front door answers with a way to start a forge",
74 run: async (get) => {
75 const got = await bodyOk(get, "/");
76 expect((got.headers.get("content-type") ?? "").startsWith("text/html"), "/ is not HTML");
77 expect(/<form[^>]*method="post"/i.test(got.text), "/ has no form to start a forge");
78 return "/ answers 200 with a start form";
79 },
80 },
81 {
82 issue: 11539,
83 item: "the forge is alive",
84 run: async (get) => {
85 const got = await bodyOk(get, "/healthz");
86 expect(got.text.trim() === "ok", `/healthz says "${got.text.trim().slice(0, 40)}", not ok`);
87 return "/healthz is ok";
88 },
89 },
90 {
91 issue: 11158,
92 item: "a stranger is told how to start, in words, from the link",
93 run: async (get) => {
94 const got = await bodyOk(get, "/llms.txt");
95 expect(/start my forge/i.test(got.text), "/llms.txt does not say how to start a forge");
96 return "/llms.txt says how to start";
97 },
98 },
99 {
100 issue: 11573,
101 item: "the forge is ready, not draining",
102 run: async (get) => {
103 const got = await bodyOk(get, "/readyz");
104 expect(got.text.trim() === "ok", `/readyz says "${got.text.trim().slice(0, 40)}", not ok`);
105 return "/readyz is ok";
106 },
107 },
108 {
109 issue: 10304,
110 item: "production reports a release version",
111 run: async (get) => {
112 const got = await bodyOk(get, "/api/v1/version");
113 const v = (JSON.parse(got.text) as { version?: unknown }).version;
114 expect(typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v), "/api/v1/version has no x.y.z version");
115 return `version ${String(v)}`;
116 },
117 },
118 {
119 issue: 11507,
120 item: "production names the commit it runs, so it can be told from main",
121 run: async (get) => {
122 const got = await bodyOk(get, "/llms.txt");
123 const m = /Running \S+ at ([0-9a-f]{7,40})/.exec(got.text);
124 expect(m !== null, "/llms.txt does not name the running commit");
125 return `running ${m?.[1] ?? ""}`;
126 },
127 },
128 {
129 issue: 11138,
130 item: "/pricing sells a forge: a checkout form",
131 run: async (get) => {
132 const got = await bodyOk(get, "/pricing");
133 expect(/<form[^>]*action="\/pricing\/order"/i.test(got.text), "/pricing has no order form");
134 return "/pricing answers with the order form";
135 },
136 },
137 {
138 issue: 11140,
139 item: "plans are listed, and the free one sleeps rather than being deleted",
140 run: async (get) => {
141 const got = await bodyOk(get, "/pricing");
142 const m = /<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/i.exec(got.text);
143 expect(m !== null, "/pricing lists no plans");
144 const offers = (JSON.parse(m?.[1] ?? "{}") as { offers?: { description?: string }[] }).offers ?? [];
145 expect(offers.length >= 2, `/pricing lists ${offers.length} plans, not two or more`);
146 expect(offers.some((o) => /sleeps/i.test(o.description ?? "")), "no plan says it sleeps when idle");
147 // The lapse rule: the page's sentence and data attribute, and the plans read, agree.
148 const attr = /data-grace-days="(\d+)"/.exec(got.text);
149 expect(attr !== null, "/pricing states no days of grace (data-grace-days)");
150 const said = /you have (\d+) days? of grace\. After that your forge sleeps and keeps its data/i.exec(got.text);
151 expect(said !== null, "/pricing does not say that a lapsed forge sleeps and keeps its data after its grace");
152 expect(said?.[1] === attr?.[1], `/pricing says ${said?.[1]} days of grace in words and ${attr?.[1]} in its attribute`);
153 const api = await bodyOk(get, "/api/v1/plans");
154 const rule = JSON.parse(api.text) as { graceDays?: unknown; lapse?: unknown };
155 expect(rule.lapse === "sleep", `/api/v1/plans says lapse ${JSON.stringify(rule.lapse)}, not "sleep"`);
156 expect(String(rule.graceDays) === attr?.[1], `/pricing says ${attr?.[1]} days of grace, /api/v1/plans ${String(rule.graceDays)}`);
157 return `${offers.length} plans; a lapsed payment has ${attr?.[1]} days of grace, then the forge sleeps and keeps its data (page and API agree)`;
158 },
159 },
160 {
161 issue: 11141,
162 item: "an owner's plan and billing page exists",
163 run: async (get) => {
164 const gate = await gated(get, "/settings/billing");
165 const got = await bodyOk(get, "/pricing");
166 const m = /<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/i.exec(got.text);
167 expect(m !== null, "/pricing lists no plans");
168 type Prop = { name?: string; value?: unknown };
169 const offers = (JSON.parse(m?.[1] ?? "{}") as { offers?: { name?: string; additionalProperty?: Prop[] }[] }).offers ?? [];
170 expect(offers.length > 0, "/pricing lists no plans");
171 const attr = /data-grace-days="(\d+)"/.exec(got.text)?.[1];
172 for (const o of offers) {
173 const prop = (n: string): unknown => (o.additionalProperty ?? []).find((p) => p.name === n)?.value;
174 const ceiling = prop("At its CPU ceiling");
175 expect(typeof ceiling === "string" && /slowed/i.test(ceiling), `the ${o.name ?? "?"} offer says nothing of what its CPU ceiling does`);
176 const days = prop("Days of grace after a lapsed payment");
177 expect(attr !== undefined && String(days) === attr, `the ${o.name ?? "?"} offer says ${String(days)} days of grace, the page ${String(attr)}`);
178 expect(/sleeps/i.test(String(prop("After the grace") ?? "")), `the ${o.name ?? "?"} offer does not say the forge sleeps after its grace`);
179 }
180 return `${gate}; each of ${offers.length} plans says what its CPU ceiling does and that a lapsed forge sleeps after ${attr} days of grace`;
181 },
182 },
183 {
184 issue: 11515,
185 item: "an owner's crew settings (their own key and budgets) exist",
186 run: (get) => gated(get, "/settings/crew"),
187 },
188 {
189 issue: 11595,
190 item: "no schedule is past its period",
191 // The forge-wide count on the public health answer (#12512): a stranger reads it, no repository named.
192 run: async (get) => {
193 const got = await bodyOk(get, "/api/v1/health");
194 const s = (JSON.parse(got.text) as { schedules?: { overdue?: unknown; oldestSeconds?: unknown } }).schedules;
195 if (s === undefined || typeof s.overdue !== "number" || typeof s.oldestSeconds !== "number")
196 return unproven("/api/v1/health carries no schedules count: this forge predates #12512");
197 expect(s.overdue === 0, `${s.overdue} schedule(s) overdue, the oldest by ${ageWords(s.oldestSeconds)}`);
198 return "/api/v1/health: no schedule is overdue";
199 },
200 },
201 {
202 issue: 10441,
203 item: "the security headers are on the page and on a machine answer",
204 run: async (get) => {
205 for (const path of ["/", "/healthz"]) {
206 const got = await get(path);
207 for (const [name, shape] of SECURITY_HEADERS) {
208 const v = got.headers.get(name);
209 expect(v !== null, `${path} lacks ${name}`);
210 expect(shape === null || shape.test(v ?? ""), `${path} has a bad ${name}: ${v ?? ""}`);
211 }
212 }
213 return "CSP, nosniff, referrer-policy, HSTS, permissions-policy, COOP on / and /healthz";
214 },
215 },
216 ];
217
218 /** `3 h 12 min`, `45 s`: an age as a person reads it. */
219 export function ageWords(seconds: number): string {
220 const s = Math.max(0, Math.floor(seconds));
221 if (s < 60) return `${s} s`;
222 const m = Math.floor(s / 60);
223 if (m < 60) return `${m} min`;
224 const h = Math.floor(m / 60);
225 if (h < 48) return `${h} h ${m % 60} min`;
226 return `${Math.floor(h / 24)} d ${h % 24} h`;
227 }
228
229 /** Runs every probe against `base` with GET only; a probe that throws is a fail. */
230 export async function prove(base: string, fetcher: Fetch): Promise<Result[]> {
231 const root = base.replace(/\/+$/, "");
232 const get: Get = async (path) => {
233 const res = await fetcher(root + path, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(15_000) });
234 return { status: res.status, headers: res.headers, text: await res.text(), location: res.headers.get("location") };
235 };
236 const out: Result[] = [];
237 for (const p of probes) {
238 try {
239 const r = await p.run(get);
240 out.push(r instanceof Unproven ? { issue: p.issue, item: p.item, status: "unproven", detail: r.why } : { issue: p.issue, item: p.item, status: "pass", detail: r });
241 } catch (e) {
242 out.push({ issue: p.issue, item: p.item, status: "fail", detail: e instanceof Fail ? e.message : `probe error: ${String(e)}` });
243 }
244 }
245 return out;
246 }
247
248 export const line = (r: Result): string => `${r.status} #${r.issue} ${r.item}: ${r.detail}`;
12 import { line, prove } from "../src/core/v1_proof.ts";
13 export * from "../src/core/v1_proof.ts";
24914
25015 if (import.meta.main) {
25116 const base = process.argv[2];
src/actions/chapters.ts +59 −4
@@ -24,17 +24,20 @@ import {
2424 type Chapter,
2525 type Item,
2626 type ChapterError,
27 recordV1,
28 V1_NAME,
2729 } from "../core/chapters.ts";
2830 import { addDependency } from "../core/dependencies.ts";
2931 import { getIssue, labelsFor, type Issue } from "../core/issues.ts";
3032 import { laterGate } from "../crew/later.ts";
3133 import { canAdmin, type Repo } from "../core/repos.ts";
3234 import type { User } from "../core/users.ts";
35 import { currentProof, line, probes, type Proof, type Result as ProbeResult } from "../core/v1_proof.ts";
3336 import { runGit } from "../git/env.ts";
3437 import { repoDir } from "../git/repos.ts";
3538 import { err, ok, type Result } from "../kernel/result.ts";
3639
37 export type ChapterActError = ChapterError | "forbidden" | "no_issue" | "unfinished" | "no_branch" | "tag_exists" | "git" | "too_late" | "moved" | "another_open";
40 export type ChapterActError = ChapterError | "forbidden" | "no_issue" | "unfinished" | "no_branch" | "tag_exists" | "git" | "too_late" | "moved" | "another_open" | "unproven";
3841
3942 /** How long after closing a chapter its owner may take the close back. */
4043 export const CLOSE_UNDO_MS = 60_000;
@@ -102,6 +105,8 @@ function owner(app: App, actor: User | undefined, repo: Repo): actor is User {
102105 export function draft(app: App, actor: User | undefined, repo: Repo, input: { name: string; means?: string }): Result<Chapter, ChapterActError> {
103106 if (!owner(app, actor, repo)) return err("forbidden");
104107 const made = draftChapter(app.db, repo.id, input, actor.id);
108 // The first chapter is the v1 list: drafting it records the issues of every probe in it.
109 if (made.ok && made.value.name === V1_NAME) recordV1(app.db, repo.id, probes.map((p) => p.issue), actor.id);
105110 if (made.ok) app.bus.append({ kind: "chapter.drafted", repoId: repo.id, actorId: actor.id, payload: { name: made.value.name } });
106111 return made;
107112 }
@@ -170,7 +175,52 @@ interface ClosePlan {
170175 readonly ref: string;
171176 }
172177
173 async function closePlan(app: App, actor: User | undefined, repo: Repo, name: string, ship: boolean): Promise<Result<ClosePlan, ChapterActError>> {
178 /** A refusal as a value: the code, and for `unproven` the sentence naming the probes that fail. */
179 export interface Refused {
180 readonly error: ChapterActError;
181 readonly words?: string;
182 }
183
outdated

Module-level Map as a side channel for the refusal words: unbounded, per-process, stale across restarts. Return the words in the error value instead.

184 /** Why a refused act stopped, in the words every door prints. */
185 export function refusalWords(app: App, chapter: Chapter | undefined, refused: Refused): string {
186 if (chapter !== undefined && refused.error === "unfinished") return stopsClose(app, chapter) ?? CHAPTER_WORDS.unfinished;
187 if (refused.error === "unproven") return refused.words ?? CHAPTER_WORDS.unproven;
188 return CHAPTER_WORDS[refused.error];
189 }
190
191 /** A refusal that carries its sentence. */
192 const unprovenBecause = (words: string): { readonly ok: false; readonly error: ChapterActError; readonly words: string } => ({ ok: false, error: "unproven", words });
193
194 /** Longest a whole proof may take inside a request: the probes run side by side. */
195 const PROOF_CAP_MS = 20_000;
196
outdated

High: this early return skips the proof when the chapter holds no probe issue, so removing the issues disables the refusal the issue requires. Gate on the name only.

197 /**
198 * v1.0.0 closes only when production passes every probe; names those that fail. Null if proven.
199 * Keyed on the name alone.
200 */
201 async function unprovenWords(app: App, chapter: Chapter, proof: Proof): Promise<string | null> {
202 if (chapter.name !== V1_NAME) return null;
203 if (app.config.url === undefined) return `${chapter.name} cannot close: this forge has no public origin to prove production against.`;
204 let results: ProbeResult[];
205 let timer: ReturnType<typeof setTimeout> | undefined;
206 try {
207 const cap = new Promise<never>((_, reject) => {
208 timer = setTimeout(() => reject(new Error("proof timed out")), PROOF_CAP_MS);
209 });
210 results = await Promise.race([proof(app.config.url), cap]);
211 } catch (e) {
212 console.error(`chapter ${chapter.name}: the proof could not run: ${String(e)}`);
213 return `${chapter.name} cannot close: the proof could not run.`;
214 } finally {
215 clearTimeout(timer);
216 }
217 const bad = results.filter((r) => r.status !== "pass");
218 if (results.length > 0 && bad.length === 0) return null;
219 if (results.length === 0) return `${chapter.name} cannot close: the proof ran no probes.`;
220 return `${chapter.name} cannot close until production passes every probe: ${bad.length} of ${results.length} do not. ${bad.map(line).join("; ")}`;
221 }
222
223 async function closePlan(app: App, actor: User | undefined, repo: Repo, name: string, ship: boolean, proof: Proof = currentProof()): Promise<Result<ClosePlan, ChapterActError>> {
174224 if (!owner(app, actor, repo)) return err("forbidden");
175225 const chapter = getChapter(app.db, repo.id, name);
176226 if (chapter === undefined) return err("not_found");
@@ -179,6 +229,8 @@ async function closePlan(app: App, actor: User | undefined, repo: Repo, name: st
179229 const items = itemsOf(app.db, chapter);
180230 const left = items.filter((i) => i.status !== "done");
181231 if (left.length > 0 && !ship) return err("unfinished");
232 const why = await unprovenWords(app, chapter, proof);
233 if (why !== null) return unprovenBecause(why);
182234 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
183235 const tipped = await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${repo.defaultBranch}^{commit}`], { cwd: dir });
184236 if (!tipped.ok) return err("no_branch");
@@ -195,9 +247,10 @@ export async function preview(
195247 verb: "open" | "add" | "remove" | "close",
196248 name: string,
197249 number?: number,
250 proof: Proof = currentProof(),
198251 ): Promise<Result<{ says: string; tag?: string; moves?: { number: number; title: string }[]; into?: string }, ChapterActError>> {
199252 if (verb === "close") {
200 const planned = await closePlan(app, actor, repo, name, true);
253 const planned = await closePlan(app, actor, repo, name, true, proof);
201254 if (!planned.ok) return planned;
202255 const { chapter, items, left, tip } = planned.value;
203256 const into = left.length === 0 ? undefined : (nextChapterOf(app.db, repo.id)?.name ?? nextName(chapter.name));
@@ -232,8 +285,9 @@ export async function close(
232285 name: string,
233286 ship: boolean,
234287 now = new Date(),
288 proof: Proof = currentProof(),
235289 ): Promise<Result<Chapter, ChapterActError>> {
236 const planned = await closePlan(app, actor, repo, name, ship);
290 const planned = await closePlan(app, actor, repo, name, ship, proof);
237291 if (!planned.ok) return planned;
238292 const { actor: by, chapter, items, left, dir, tip, ref } = planned.value;
239293 if (!(await runGit(["update-ref", ref, tip, ""], { cwd: dir })).ok) return err("git");
@@ -326,5 +380,6 @@ export const CHAPTER_WORDS: Readonly<Record<ChapterActError, string>> = {
326380 git: "The tag could not be written.",
327381 too_late: "The minute to take the close back has passed.",
328382 moved: "That close moved items to the next chapter, so it cannot be taken back.",
383 unproven: "v1.0.0 closes only when the proof passes on production, every probe.",
329384 another_open: "Another chapter has been opened since, so this close cannot be taken back.",
330385 };
src/core/chapters.ts +24
@@ -136,6 +136,30 @@ export function startChapter(db: Database, chapter: Chapter, now: Date): Result<
136136 return ok(getChapterById(db, chapter.id)!);
137137 }
138138
139 /** The first chapter: the v1 list, closed once production is proven (`actions/chapters.ts`). */
140 export const V1_NAME = "v1.0.0";
141
142 /**
143 * Record the v1 list as the chapter `v1.0.0`: drafted when absent, each of `numbers` that is an
144 * issue of the repository goes in it. Repeatable; an item already in a closed chapter stays there.
145 * Returns the chapter and the numbers that are no issue here.
146 */
147 export function recordV1(db: Database, repoId: string, numbers: readonly number[], byId: string): Result<{ chapter: Chapter; missing: number[] }, ChapterError> {
148 let chapter = getChapter(db, repoId, V1_NAME);
149 if (chapter === undefined) {
150 const made = draftChapter(db, repoId, { name: V1_NAME, means: "v1.0.0 is proven on production: every probe of scripts/v1-proven.ts passes." }, byId);
151 if (!made.ok) return made;
152 chapter = made.value;
153 }
154 const missing: number[] = [];
155 for (const n of [...new Set(numbers)].sort((a, b) => a - b)) {
156 const row = db.query<{ id: string }, [string, number]>("SELECT id FROM issue WHERE repo_id = ?1 AND number = ?2 AND kind = 'issue'").get(repoId, n);
157 if (row === null) missing.push(n);
158 else putIssue(db, chapter, row.id, byId);
159 }
160 return ok({ chapter, missing });
161 }
162
139163 /** The next name after `name`: v1.0.0 → v2.0.0. */
140164 export function nextName(name: string): string {
141165 const m = /^(\D*)(\d+)(.*)$/.exec(name);
src/core/v1_proof.ts added +249
@@ -0,0 +1,249 @@
1 /** The read-only probes of the v1.0.0 list: `scripts/v1-proven.ts` runs them, as does a close. */
2 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
3 export interface Probe {
4 readonly issue: number;
5 readonly item: string;
6 /** A string is a pass; `unproven(why)` is "seen what a stranger can, not the claim". */
7 readonly run: (get: Get) => Promise<string | Unproven>;
8 }
9 export class Unproven {
10 constructor(readonly why: string) {}
11 }
12 export const unproven = (why: string): Unproven => new Unproven(why);
13 export type Status = "pass" | "fail" | "unproven";
14 export interface Result {
15 readonly issue: number;
16 readonly item: string;
17 readonly status: Status;
18 readonly detail: string;
19 }
20 interface Got {
21 readonly status: number;
22 readonly headers: Headers;
23 readonly text: string;
24 readonly location: string | null;
25 }
26 type Get = (path: string) => Promise<Got>;
27
28 class Fail extends Error {}
29 const fail = (why: string): never => {
30 throw new Fail(why);
31 };
32 const expect = (cond: boolean, why: string): void => {
33 if (!cond) fail(why);
34 };
35
36 async function bodyOk(get: Get, path: string, status = 200): Promise<Got> {
37 const got = await get(path);
38 expect(got.status === status, `${path} answers ${got.status}, not ${status}`);
39 return got;
40 }
41
42 /** The page exists and is gated: a redirect to sign-in, never a 404 or a 5xx. */
43 async function gated(get: Get, path: string): Promise<string> {
44 const got = await get(path);
45 expect(got.status === 303 || got.status === 302, `${path} answers ${got.status}, not a redirect to sign-in`);
46 expect((got.location ?? "").includes("/signin"), `${path} redirects to ${got.location ?? "nowhere"}, not sign-in`);
47 return `${path} is there and asks for sign-in`;
48 }
49
50 const SECURITY_HEADERS: ReadonlyArray<readonly [string, RegExp | null]> = [
51 ["content-security-policy", /default-src/],
52 ["x-content-type-options", /^nosniff$/i],
53 ["referrer-policy", /./],
54 ["strict-transport-security", /max-age=\d+/],
55 ["permissions-policy", /./],
56 ["cross-origin-opener-policy", /./],
57 ];
58
59 export const probes: readonly Probe[] = [
60 {
61 issue: 11541,
62 item: "the front door answers with a way to start a forge",
63 run: async (get) => {
64 const got = await bodyOk(get, "/");
65 expect((got.headers.get("content-type") ?? "").startsWith("text/html"), "/ is not HTML");
66 expect(/<form[^>]*method="post"/i.test(got.text), "/ has no form to start a forge");
67 return "/ answers 200 with a start form";
68 },
69 },
70 {
71 issue: 11539,
72 item: "the forge is alive",
73 run: async (get) => {
74 const got = await bodyOk(get, "/healthz");
75 expect(got.text.trim() === "ok", `/healthz says "${got.text.trim().slice(0, 40)}", not ok`);
76 return "/healthz is ok";
77 },
78 },
79 {
80 issue: 11158,
81 item: "a stranger is told how to start, in words, from the link",
82 run: async (get) => {
83 const got = await bodyOk(get, "/llms.txt");
84 expect(/start my forge/i.test(got.text), "/llms.txt does not say how to start a forge");
85 return "/llms.txt says how to start";
86 },
87 },
88 {
89 issue: 11573,
90 item: "the forge is ready, not draining",
91 run: async (get) => {
92 const got = await bodyOk(get, "/readyz");
93 expect(got.text.trim() === "ok", `/readyz says "${got.text.trim().slice(0, 40)}", not ok`);
94 return "/readyz is ok";
95 },
96 },
97 {
98 issue: 10304,
99 item: "production reports a release version",
100 run: async (get) => {
101 const got = await bodyOk(get, "/api/v1/version");
102 const v = (JSON.parse(got.text) as { version?: unknown }).version;
103 expect(typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v), "/api/v1/version has no x.y.z version");
104 return `version ${String(v)}`;
105 },
106 },
107 {
108 issue: 11507,
109 item: "production names the commit it runs, so it can be told from main",
110 run: async (get) => {
111 const got = await bodyOk(get, "/llms.txt");
112 const m = /Running \S+ at ([0-9a-f]{7,40})/.exec(got.text);
113 expect(m !== null, "/llms.txt does not name the running commit");
114 return `running ${m?.[1] ?? ""}`;
115 },
116 },
117 {
118 issue: 11138,
119 item: "/pricing sells a forge: a checkout form",
120 run: async (get) => {
121 const got = await bodyOk(get, "/pricing");
122 expect(/<form[^>]*action="\/pricing\/order"/i.test(got.text), "/pricing has no order form");
123 return "/pricing answers with the order form";
124 },
125 },
126 {
127 issue: 11140,
128 item: "plans are listed, and the free one sleeps rather than being deleted",
129 run: async (get) => {
130 const got = await bodyOk(get, "/pricing");
131 const m = /<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/i.exec(got.text);
132 expect(m !== null, "/pricing lists no plans");
133 const offers = (JSON.parse(m?.[1] ?? "{}") as { offers?: { description?: string }[] }).offers ?? [];
134 expect(offers.length >= 2, `/pricing lists ${offers.length} plans, not two or more`);
135 expect(offers.some((o) => /sleeps/i.test(o.description ?? "")), "no plan says it sleeps when idle");
136 // The lapse rule: the page's sentence and data attribute, and the plans read, agree.
137 const attr = /data-grace-days="(\d+)"/.exec(got.text);
138 expect(attr !== null, "/pricing states no days of grace (data-grace-days)");
139 const said = /you have (\d+) days? of grace\. After that your forge sleeps and keeps its data/i.exec(got.text);
140 expect(said !== null, "/pricing does not say that a lapsed forge sleeps and keeps its data after its grace");
141 expect(said?.[1] === attr?.[1], `/pricing says ${said?.[1]} days of grace in words and ${attr?.[1]} in its attribute`);
142 const api = await bodyOk(get, "/api/v1/plans");
143 const rule = JSON.parse(api.text) as { graceDays?: unknown; lapse?: unknown };
144 expect(rule.lapse === "sleep", `/api/v1/plans says lapse ${JSON.stringify(rule.lapse)}, not "sleep"`);
145 expect(String(rule.graceDays) === attr?.[1], `/pricing says ${attr?.[1]} days of grace, /api/v1/plans ${String(rule.graceDays)}`);
146 return `${offers.length} plans; a lapsed payment has ${attr?.[1]} days of grace, then the forge sleeps and keeps its data (page and API agree)`;
147 },
148 },
149 {
150 issue: 11141,
151 item: "an owner's plan and billing page exists",
152 run: async (get) => {
153 const gate = await gated(get, "/settings/billing");
154 const got = await bodyOk(get, "/pricing");
155 const m = /<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/i.exec(got.text);
156 expect(m !== null, "/pricing lists no plans");
157 type Prop = { name?: string; value?: unknown };
158 const offers = (JSON.parse(m?.[1] ?? "{}") as { offers?: { name?: string; additionalProperty?: Prop[] }[] }).offers ?? [];
159 expect(offers.length > 0, "/pricing lists no plans");
160 const attr = /data-grace-days="(\d+)"/.exec(got.text)?.[1];
161 for (const o of offers) {
162 const prop = (n: string): unknown => (o.additionalProperty ?? []).find((p) => p.name === n)?.value;
163 const ceiling = prop("At its CPU ceiling");
164 expect(typeof ceiling === "string" && /slowed/i.test(ceiling), `the ${o.name ?? "?"} offer says nothing of what its CPU ceiling does`);
165 const days = prop("Days of grace after a lapsed payment");
166 expect(attr !== undefined && String(days) === attr, `the ${o.name ?? "?"} offer says ${String(days)} days of grace, the page ${String(attr)}`);
167 expect(/sleeps/i.test(String(prop("After the grace") ?? "")), `the ${o.name ?? "?"} offer does not say the forge sleeps after its grace`);
168 }
169 return `${gate}; each of ${offers.length} plans says what its CPU ceiling does and that a lapsed forge sleeps after ${attr} days of grace`;
170 },
171 },
172 {
173 issue: 11515,
174 item: "an owner's crew settings (their own key and budgets) exist",
175 run: (get) => gated(get, "/settings/crew"),
176 },
177 {
178 issue: 11595,
179 item: "no schedule is past its period",
180 // The forge-wide count on the public health answer (#12512): no repository named.
181 run: async (get) => {
182 const got = await bodyOk(get, "/api/v1/health");
183 const s = (JSON.parse(got.text) as { schedules?: { overdue?: unknown; oldestSeconds?: unknown } }).schedules;
184 if (s === undefined || typeof s.overdue !== "number" || typeof s.oldestSeconds !== "number")
185 return unproven("/api/v1/health carries no schedules count: this forge predates #12512");
186 expect(s.overdue === 0, `${s.overdue} schedule(s) overdue, the oldest by ${ageWords(s.oldestSeconds)}`);
187 return "/api/v1/health: no schedule is overdue";
188 },
189 },
190 {
191 issue: 10441,
192 item: "the security headers are on the page and on a machine answer",
193 run: async (get) => {
194 for (const path of ["/", "/healthz"]) {
195 const got = await get(path);
196 for (const [name, shape] of SECURITY_HEADERS) {
197 const v = got.headers.get(name);
198 expect(v !== null, `${path} lacks ${name}`);
199 expect(shape === null || shape.test(v ?? ""), `${path} has a bad ${name}: ${v ?? ""}`);
200 }
201 }
202 return "CSP, nosniff, referrer-policy, HSTS, permissions-policy, COOP on / and /healthz";
203 },
204 },
205 ];
206
207 /** `3 h 12 min`, `45 s`: an age as a person reads it. */
208 export function ageWords(seconds: number): string {
209 const s = Math.max(0, Math.floor(seconds));
210 if (s < 60) return `${s} s`;
211 const m = Math.floor(s / 60);
212 if (m < 60) return `${m} min`;
213 const h = Math.floor(m / 60);
214 if (h < 48) return `${h} h ${m % 60} min`;
215 return `${Math.floor(h / 24)} d ${h % 24} h`;
216 }
217
218 /** Runs every probe against `base` with GET only; a probe that throws is a fail. */
219 export async function prove(base: string, fetcher: Fetch): Promise<Result[]> {
220 const root = base.replace(/\/+$/, "");
221 const get: Get = async (path) => {
222 const res = await fetcher(root + path, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(15_000) });
223 return { status: res.status, headers: res.headers, text: await res.text(), location: res.headers.get("location") };
224 };
225 // Side by side: each probe is one GET at a time, so the proof takes the slowest, not the sum.
226 return Promise.all(
227 probes.map(async (p): Promise<Result> => {
228 try {
229 const r = await p.run(get);
230 return r instanceof Unproven ? { issue: p.issue, item: p.item, status: "unproven", detail: r.why } : { issue: p.issue, item: p.item, status: "pass", detail: r };
231 } catch (e) {
232 return { issue: p.issue, item: p.item, status: "fail", detail: e instanceof Fail ? e.message : `probe error: ${String(e)}` };
233 }
234 }),
235 );
236 }
237
238 export const line = (r: Result): string => `${r.status} #${r.issue} ${r.item}: ${r.detail}`;
239
240 /** The proof a close of v1.0.0 runs: the probes against one base URL. */
241 export type Proof = (base: string) => Promise<Result[]>;
242 const readOnlyProof: Proof = (base) => prove(base, fetch);
243 let seam: Proof | undefined;
244 /** The proof a close runs when none is passed: production's unless a test put one in. */
245 export const currentProof = (): Proof => seam ?? readOnlyProof;
246 /** A test seam: a passing proof for fixtures that close `v1.0.0`; `undefined` restores it. */
247 export function useProof(proof: Proof | undefined): void {
248 seam = proof;
249 }
src/http/api/chapters.ts +3 −3
@@ -4,8 +4,8 @@
44 * and the acts in `actions/chapters.ts`; this only reads the request and answers the result.
55 */
66
7 import { CHAPTER_WORDS, close, draft, fill, open, patch } from "../../actions/chapters.ts";
8 import { itemsOf, listChapters, progressOf, type Chapter } from "../../core/chapters.ts";
7 import { CHAPTER_WORDS, close, draft, fill, open, patch, refusalWords } from "../../actions/chapters.ts";
8 import { getChapter, itemsOf, listChapters, progressOf, type Chapter } from "../../core/chapters.ts";
99 import type { Handler } from "../context.ts";
1010 import { apiError, body, json, notFound, requireScope } from "../respond.ts";
1111 import { loadRepo } from "../api.ts";
@@ -69,7 +69,7 @@ export function chapterRoutes(router: Router<Handler>): void {
6969 : null;
7070 if (done === null) return notFound();
7171 if (!done.ok)
72 return apiError(done.error, done.error === "forbidden" ? 403 : done.error === "not_found" || done.error === "no_issue" ? 404 : 409, CHAPTER_WORDS[done.error]);
72 return apiError(done.error, done.error === "forbidden" ? 403 : done.error === "not_found" || done.error === "no_issue" ? 404 : 409, refusalWords(ctx.app, verb === "ship" ? getChapter(ctx.app.db, repo.id, name) : undefined, done));
7373 const value = done.value;
7474 return json(value === undefined ? { ok: true } : shape(ctx.app.db, value, new Date()), 200);
7575 });
src/http/mcp/tools/repo.ts +4 −4
@@ -3,7 +3,7 @@ import { forkParentFor } from "../../../core/repos.ts";
33 import { audienceFor } from "../../../core/audience.ts";
44 import { upstreamFacts } from "../../../actions/upstream_follow.ts";
55 import { creditFacts } from "../../../actions/credit_facts.ts";
6 import { CHAPTER_WORDS, type ChapterActError, close, fill, open, preview } from "../../../actions/chapters.ts";
6 import { type ChapterActError, close, fill, open, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
77 import { getChapter, itemsOf, listChapters, progressOf, progressSentence } from "../../../core/chapters.ts";
88 import { err } from "../../../kernel/result.ts";
99 import { good, str, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
@@ -33,16 +33,16 @@ export const tool: Tool = {
3333 if ((verb === "add" || verb === "remove") && (typeof number !== "number" || !Number.isInteger(number) || number < 1))
3434 return bad("invalid", "`add` and `remove` need an issue `number`");
3535 const n = typeof number === "number" ? number : undefined;
36 const refused = (e: keyof typeof CHAPTER_WORDS) => bad(e, CHAPTER_WORDS[e]);
36 const refused = (r: Refused) => bad(r.error, refusalWords(ctx.app, getChapter(ctx.app.db, repo.id, name), r));
3737 if (args["confirm"] !== true) {
3838 const seen = await preview(ctx.app, user, repo, verb, name, n);
39 return seen.ok ? good({ ...seen.value, done: false, says: `${seen.value.says} Send confirm: true to do it.` }) : refused(seen.error);
39 return seen.ok ? good({ ...seen.value, done: false, says: `${seen.value.says} Send confirm: true to do it.` }) : refused(seen);
4040 }
4141 const done = verb === "close" ? await close(ctx.app, user, repo, name, true)
4242 : verb === "open" ? open(ctx.app, user, repo, name)
4343 : n === undefined ? err<ChapterActError>("not_found")
4444 : fill(ctx.app, user, repo, name, n, verb === "add");
45 return done.ok ? good({ done: true, chapter: name, action: verb, ...(n === undefined ? {} : { number: n }) }) : refused(done.error);
45 return done.ok ? good({ done: true, chapter: name, action: verb, ...(n === undefined ? {} : { number: n }) }) : refused(done);
4646 }
4747 if (args["view"] === undefined && args["chapter"] !== undefined) return bad("invalid", "`chapter` needs `view: chapters`");
4848 if (args["view"] !== undefined) {
src/tui/screens/chapters.ts +3 −3
@@ -9,7 +9,7 @@
99 * a change made there.
1010 */
1111
12 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, stopsClose, undoableClose } from "../../actions/chapters.ts";
12 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
1313 import { getChapter, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1414 import { canAdmin, type Repo } from "../../core/repos.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
@@ -45,7 +45,7 @@ async function closeOrUndo(f: Session, ctx: Ctx, repo: Repo, name: string, key:
4545 const chapter = getChapter(f.app.db, repo.id, name);
4646 if (key === "c") {
4747 const done = await close(f.app, f.user, repo, name, false);
48 const why = !done.ok && done.error === "unfinished" && chapter !== undefined ? (stopsClose(f.app, chapter) ?? CHAPTER_WORDS.unfinished) : done.ok ? "" : CHAPTER_WORDS[done.error];
48 const why = done.ok ? "" : refusalWords(f.app, chapter, done);
4949 ctx.toast(done.ok ? `Closed ${name} and tagged it. You can undo for a minute.` : why, done.ok ? undefined : "danger");
5050 } else {
5151 const done = await reopen(f.app, f.user, repo, name);
@@ -141,7 +141,7 @@ function act(f: Session, ctx: Ctx, repo: Repo, parent: Screen, name: string, key
141141 if (i !== 0) return;
142142 void ctx.track(
143143 close(f.app, f.user, repo, name, true).then((done) => {
144 ctx.toast(done.ok ? `${name} is finished.` : CHAPTER_WORDS[done.error], done.ok ? undefined : "danger");
144 ctx.toast(done.ok ? `${name} is finished.` : refusalWords(f.app, getChapter(f.app.db, repo.id, name), done), done.ok ? undefined : "danger");
145145 ctx.invalidate();
146146 }),
147147 );
src/web/pages/chapters.ts +2 −2
@@ -6,7 +6,7 @@
66 * is a same-origin POST by a person who administers the repository.
77 */
88
9 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, stopsClose } from "../../actions/chapters.ts";
9 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
1010 import { getChapter, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1111 import { canAdmin, type Repo } from "../../core/repos.ts";
1212 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -167,7 +167,7 @@ export async function chapterAct(ctx: Ctx): Promise<Response> {
167167 if (result === null) return notFoundPage(ctx);
168168 if (!result.ok) {
169169 const chapter = getChapter(app.db, repo.id, name);
170 const why = result.error === "unfinished" && chapter !== undefined ? (stopsClose(app, chapter) ?? CHAPTER_WORDS.unfinished) : CHAPTER_WORDS[result.error];
170 const why = refusalWords(app, chapter, result);
171171 return flashTo(ctx, at, { tone: "danger", message: why });
172172 }
173173 const landed = verb === "patch" && result.value !== undefined ? `${list}/${encodeURIComponent(result.value.name)}` : at;
test/chapters-page.test.ts +20
@@ -9,6 +9,8 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { newApp } from "../src/actions/apps.ts";
1111 import { CHAPTER_WORDS, close, draft, fill, open, reopen, stopsClose } from "../src/actions/chapters.ts";
12 import { useProof } from "../src/core/v1_proof.ts";
13 import { probes } from "../src/core/v1_proof.ts";
1214 import { createApp, type App } from "../src/app.ts";
1315 import { getChapter, listChapters } from "../src/core/chapters.ts";
1416 import { createIssue } from "../src/core/issues.ts";
@@ -54,9 +56,12 @@ describe("chapters on /next", () => {
5456 };
5557
5658 beforeAll(async () => {
59 // These fixtures close a plain chapter named v1.0.0: give it a proof that passes.
60 useProof(async () => probes.map((p) => ({ issue: p.issue, item: p.item, status: "pass" as const, detail: "ok" })));
5761 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-page-"));
5862 app = createApp({ dataDir, port: 0, host: "forge.test" });
5963 servers = await serve(app);
64 app.config.url = servers.url; // the close proves production at the forge's own origin
6065 const made = await createUser(app.db, { username: "alice", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: true });
6166 if (!made.ok) throw new Error(String(made.error));
6267 owner = made.value;
@@ -114,6 +119,21 @@ describe("chapters on /next", () => {
114119 expect(getChapter(app.db, repo.id, "v1.0.0")?.state).toBe("open");
115120 });
116121
122 test("an unproven v1.0.0 is refused in its own sentence at the API and the page", async () => {
123 const passing = probes.map((p) => ({ issue: p.issue, item: p.item, status: "pass" as const, detail: "ok" }));
124 useProof(async () => passing.map((r) => (r.issue === probes[0]!.issue ? { ...r, status: "fail" as const, detail: "down" } : r)));
125 const api = await fetch(`${servers.url}/api/v1/repos/alice/shop/chapters/v1.0.0/ship`, { method: "POST", headers: { authorization: `Bearer ${token}` } });
126 expect(api.status).toBe(409);
127 const said = (await api.json()) as { error: string; message?: string };
128 expect(said.error).toBe("unproven");
129 expect(JSON.stringify(said)).toContain("v1.0.0 cannot close");
130 expect(JSON.stringify(said)).not.toContain(CHAPTER_WORDS.unproven);
131 const page = await post("/alice/shop/chapters/v1.0.0/ship");
132 expect(decodeURIComponent(page.headers.get("set-cookie") ?? "")).toContain("v1.0.0 cannot close");
133 expect(getChapter(app.db, repo.id, "v1.0.0")?.state).toBe("open");
134 useProof(async () => passing);
135 });
136
117137 test("the close is a same-origin POST, with a receipt and an undo for a minute", async () => {
118138 for (const n of numbers) landed(n);
119139 const page = await (await get("/alice/shop/next")).text();
test/chapters-v1.test.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * The first chapter (#12298): drafting `v1.0.0` records the v1 list's issues in it, and closing it
3 * runs the read-only proof of `scripts/v1-proven.ts` and is refused, naming the probes, until every
4 * one passes. Any other chapter closes without a proof.
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 { newApp } from "../src/actions/apps.ts";
11 import { close, draft, open, refusalWords, type Refused } from "../src/actions/chapters.ts";
12 import type { Proof } from "../src/core/v1_proof.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { forgetFrozenItems, getChapter, itemsOf, recordV1 } from "../src/core/chapters.ts";
15 import { getRepo, type Repo } from "../src/core/repos.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { repoDir } from "../src/git/repos.ts";
18 import { commitFiles } from "../src/git/write.ts";
19 import { probes } from "../scripts/v1-proven.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 describe("v1.0.0 closes on proof", () => {
25 let dataDir = "";
26 let app: App;
27 let owner: User;
28 let repo: Repo;
29
30 const all = (status: "pass" | "fail" | "unproven", only = -1): Proof => async () =>
31 probes.map((p) => ({ issue: p.issue, item: p.item, status: p.issue === only || only === -1 ? status : "pass", detail: `${status} detail` }));
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-v1-"));
35 app = createApp({ dataDir, port: 0, host: "forge.test", url: "https://forge.test" });
36 const made = await createUser(app.db, { username: "alice", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: true });
37 if (!made.ok) throw new Error(String(made.error));
38 owner = made.value;
39 const created = await newApp(app, owner, { name: "shop", description: "Words", visibility: "public" });
40 if (!created.ok) throw new Error(String(created.error));
41 repo = getRepo(app.db, "alice", "shop")!;
42 const c = await commitFiles(repoDir(app.reposRoot, "alice", "shop"), {
43 branch: repo.defaultBranch,
44 message: "first",
45 files: [{ path: "README.md", content: "hello" }],
46 author: { name: "T", email: "[email protected]" },
47 });
48 if (!c.ok) throw new Error(JSON.stringify(c.error));
49 // The v1 list's issues, under the numbers the probes name.
50 for (const p of probes)
51 app.db
52 .query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state) VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, 'closed')`)
53 .run(`v1-${p.issue}`, repo.id, p.issue, p.item, owner.id);
54 }, 30_000);
55
56 afterAll(async () => {
57 app.close();
58 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
59 });
60
61 test("drafting v1.0.0 records the v1 list's issues in it; missing ones are named, not invented", () => {
62 const made = draft(app, owner, repo, { name: "v1.0.0" });
63 expect(made.ok).toBe(true);
64 const chapter = getChapter(app.db, repo.id, "v1.0.0")!;
65 expect(itemsOf(app.db, chapter).map((i) => i.number)).toEqual([...new Set(probes.map((p) => p.issue))].sort((a, b) => a - b));
66 const again = recordV1(app.db, repo.id, [999999, 11541], owner.id);
67 expect(again.ok && again.value.missing).toEqual([999999]);
68 });
69
70 test("a close is refused naming every probe that does not pass, and tags nothing", async () => {
71 expect(open(app, owner, repo, "v1.0.0").ok).toBe(true);
72 const chapter = getChapter(app.db, repo.id, "v1.0.0")!;
73 const refused = await close(app, owner, repo, "v1.0.0", true, new Date(), all("fail", 11539));
74 expect(refused.ok).toBe(false);
75 expect(!refused.ok && refused.error).toBe("unproven");
76 const words = refusalWords(app, chapter, refused as Refused);
77 expect(words).toContain("#11539");
78 expect(words).toContain("1 of");
79 expect(words).not.toContain("#11541");
80 expect(getChapter(app.db, repo.id, "v1.0.0")!.state).toBe("open");
81 });
82
83 test("a probe that is unproven is not a pass", async () => {
84 const refused = await close(app, owner, repo, "v1.0.0", true, new Date(), all("unproven", 11140));
85 expect(!refused.ok && refused.error).toBe("unproven");
86 });
87
88 test("a proof that cannot run refuses too", async () => {
89 const refused = await close(app, owner, repo, "v1.0.0", true, new Date(), async () => {
90 throw new Error("offline");
91 });
92 expect(!refused.ok && refused.error).toBe("unproven");
93 const words = refusalWords(app, getChapter(app.db, repo.id, "v1.0.0"), refused as Refused);
94 expect(words).toContain("could not run");
95 expect(words).not.toContain("offline"); // the detail is logged, not printed
96 });
97
98 test("when every probe passes the chapter closes and is tagged; the proof ran against the forge's origin", async () => {
99 forgetFrozenItems();
100 let base = "";
101 const proof: Proof = (b) => {
102 base = b;
103 return all("pass")(b);
104 };
105 const done = await close(app, owner, repo, "v1.0.0", true, new Date(), proof);
106 expect(done.ok).toBe(true);
107 expect(base).toBe("https://forge.test");
108 expect(getChapter(app.db, repo.id, "v1.0.0")!.state).toBe("closed");
109 });
110
111 test("removing the probe issues does not lift the refusal: the name alone gates", async () => {
112 // A fresh forge: v1.0.0 drafted and opened holding no probe issue at all.
113 const dir = await mkdtemp(join(tmpdir(), "forge-chapters-v1b-"));
114 const bare = createApp({ dataDir: dir, port: 0, host: "forge.test", url: "https://forge.test" });
115 try {
116 const u = await createUser(bare.db, { username: "carol", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: true });
117 if (!u.ok) throw new Error(String(u.error));
118 const created = await newApp(bare, u.value, { name: "shop", description: "Words", visibility: "public" });
119 if (!created.ok) throw new Error(String(created.error));
120 const r = getRepo(bare.db, "carol", "shop")!;
121 const c = await commitFiles(repoDir(bare.reposRoot, "carol", "shop"), {
122 branch: r.defaultBranch, message: "first", files: [{ path: "README.md", content: "hello" }], author: { name: "T", email: "[email protected]" },
123 });
124 if (!c.ok) throw new Error("commit");
125 expect(draft(bare, u.value, r, { name: "v1.0.0" }).ok).toBe(true);
126 expect(open(bare, u.value, r, "v1.0.0").ok).toBe(true);
127 expect(itemsOf(bare.db, getChapter(bare.db, r.id, "v1.0.0")!)).toEqual([]);
128 const refused = await close(bare, u.value, r, "v1.0.0", true, new Date(), all("fail"));
129 expect(!refused.ok && refused.error).toBe("unproven");
130 expect(getChapter(bare.db, r.id, "v1.0.0")!.state).toBe("open");
131 } finally {
132 bare.close();
133 await rm(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
134 }
135 });
136
137 test("the probes run side by side", async () => {
138 // Every request waits for the whole first wave: it only returns once all probes have asked,
139 // so a proof that ran them one at a time would never get past the first.
140 const { prove, probes } = await import("../src/core/v1_proof.ts");
141 let asked = 0;
142 let release!: () => void;
143 const wave = new Promise<void>((r) => (release = r));
144 const results = await prove("https://forge.test", async () => {
145 if (++asked >= probes.length) release();
146 await wave;
147 return new Response("", { status: 500 });
148 });
149 expect(results.length).toBe(probes.length);
150 expect(asked).toBeGreaterThanOrEqual(probes.length);
151 });
152
153 test("another chapter closes without any proof", async () => {
154 expect(draft(app, owner, repo, { name: "other" }).ok).toBe(true);
155 expect(open(app, owner, repo, "other").ok).toBe(true);
156 const never: Proof = async () => {
157 throw new Error("the proof must not run");
158 };
159 expect((await close(app, owner, repo, "other", true, new Date(), never)).ok).toBe(true);
160 });
161 });
test/chapters.test.ts +5
@@ -10,6 +10,8 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { newApp } from "../src/actions/apps.ts";
1212 import { close, draft, fill, open, patch } from "../src/actions/chapters.ts";
13 import { useProof } from "../src/core/v1_proof.ts";
14 import { probes } from "../src/core/v1_proof.ts";
1315 import { openIssue } from "../src/actions/issues.ts";
1416 import { createApp, type App } from "../src/app.ts";
1517 import { addCrew, createAgentRow, getAgent } from "../src/core/agents.ts";
@@ -72,9 +74,12 @@ describe("chapters", () => {
7274 };
7375
7476 beforeAll(async () => {
77 // These fixtures close a plain chapter named v1.0.0: give it a proof that passes.
78 useProof(async () => probes.map((p) => ({ issue: p.issue, item: p.item, status: "pass" as const, detail: "ok" })));
7579 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-"));
7680 app = createApp({ dataDir, port: 0, host: "forge.test" });
7781 servers = await serve(app);
82 app.config.url = servers.url; // the close proves production at the forge's own origin
7883 const mk = async (username: string, agent: boolean, roles: string[] = []) => {
7984 const made = await createUser(app.db, {
8085 username,
test/timers-named.test.ts +1
@@ -75,6 +75,7 @@ const ALLOWED: readonly Allowed[] = [
7575 ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]),
7676 ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]),
7777 ...allow("setTimeout", `an ssh login's auth deadline, ${PER_CONNECTION}`, [["src/ssh/server.ts", "() => { this.transport.disconnect("]]),
78 ...allow("setTimeout", "a v1.0.0 close's proof deadline: it rejects a promise and does no work on the loop", [["src/actions/chapters.ts", "() => reject(new Error(\"proof timed out\"))"]]),
7879 ...allow("setTimeout", "a maintenance duty's deadline on one call: it rejects a promise and does no work on the loop", [["src/maintain/runner.ts", "() => reject(new Error(\"timed out\"))"]]),
7980 ...allow("setTimeout", "an app request's look-again sleep in the ladder: it holds one request, does no work on the loop, and ends within the bound", [["src/http/app_turn.ts", "r"]]),
8081 ...allow("setTimeout", `a media stream's idle deadline, ${PER_CONNECTION}`, [["src/git/read.ts", "() => { finish(); controller.error("]]),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs