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

A chapter's item list hides sealed security reports from anyone who cannot see them #14926

Merged opened this

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

Merged

scout/forge:scout/14905-a-chapter-s-item-list-hides-sealed-secur → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/14905-a-chapter-s-item-list-hides-sealed-secur was merged into main as 11f50ff.

Review

Sign in to review this change.
24 files changed +367 −92
docs/features/chapters.md +6
@@ -34,3 +34,9 @@ Drafting a chapter named `v1.0.0` records the v1 list's issues in it (the issue
3434 An open chapter's page says what it has cost so far and what a chapter of its pace costs, in a line under the progress sentence (`costSentence`, `src/core/chapters.ts`). The terminal prints the same sentence after the progress sentence on the chapter's list and on each row of the chapters screen; the MCP `repo` tool's `progress` carries it too. A closed chapter keeps its finished page, which already says its cost.
3535
3636 Try it: open `/<owner>/<name>/chapters/<open chapter>` and read the line under the progress sentence.
37
38 ## Sealed reports stay sealed (#14905)
39
40 A sealed security report added to a chapter is listed only to someone who may see it (the reporter and the repository's writers). For anyone else the chapter's page, `/next`'s Chapters section, the chapter bar, the API and the MCP `repo` tool leave it out of the list and out of the counts (`itemsOf` takes the viewer, `sealedScope`; there is no default). The bar counts what the page lists, so a reporter's bar counts their own report too. The changelog's grouping by chapter (`chapterOfPulls`) leaves a sealed pull out the same way. A closed chapter's list is kept for two views only, everything and the public one; a reporter who filed a sealed issue in the repository gets theirs read fresh. The terminal's chapters screen and its /next screen read through the same function with the signed-in person, so they list and count exactly what the page does.
41
42 Try it: file a sealed issue, add it to the open chapter, then open `/<owner>/<name>/chapters/<name>` signed out: the report is not listed and the count leaves it out; signed in as a writer, or on the terminal's Chapters screen as a writer, it is there.
src/actions/chapter_wave.ts +2 −2
@@ -6,7 +6,7 @@
66 */
77
88 import type { App } from "../app.ts";
9 import { itemsOf, type Chapter } from "../core/chapters.ts";
9 import { itemsOf, PUBLIC_ITEMS, type Chapter } from "../core/chapters.ts";
1010 import { getPull } from "../core/pulls.ts";
1111 import type { Repo } from "../core/repos.ts";
1212 import type { User } from "../core/users.ts";
@@ -23,7 +23,7 @@ export async function writeChapterWave(app: App, actor: User, repo: Repo, chapte
2323 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
2424 const tree = await listTree(dir, repo.defaultBranch, "waves");
2525 if (tree.ok && tree.value.some((e) => e.name === `${version}.md`)) return false;
26 const shipped: ShippedItem[] = itemsOf(app.db, chapter)
26 const shipped: ShippedItem[] = itemsOf(app.db, chapter, PUBLIC_ITEMS)
2727 .filter((i) => i.status === "done")
2828 .map((i) => ({ number: i.number, title: i.title, pull: i.pull, pullTitle: i.pull === null ? "" : (getPull(app.db, repo.id, i.pull)?.title ?? "") }));
2929 const base = (app.config.url ?? `http://localhost:${app.config.port}`).replace(/\/+$/, "");
src/actions/chapters.ts +14 −9
@@ -11,6 +11,8 @@ import {
1111 draftChapter,
1212 getChapter,
1313 itemsOf,
14 EVERY_ITEM,
15 type ItemView,
1416 nextChapterOf,
1517 nextName,
1618 chapterOfIssue,
@@ -43,14 +45,17 @@ export type ChapterActError = ChapterError | "forbidden" | "no_issue" | "unfinis
4345 /** How long after closing a chapter its owner may take the close back. */
4446 export const CLOSE_UNDO_MS = 60_000;
4547
46 /** The items in a chapter's way: everything not yet live and proven. */
47 export function inTheWay(app: App, chapter: Chapter): Item[] {
48 return itemsOf(app.db, chapter).filter((i) => i.status !== "done");
48 /** The items in a chapter's way as `view` may see them: everything not yet live and proven. */
49 export function inTheWay(app: App, chapter: Chapter, view: ItemView): Item[] {
outdated

Default EVERY_ITEM makes the unsafe view the one a forgetful caller gets. Make view required.

50 return itemsOf(app.db, chapter, view).filter((i) => i.status !== "done");
4951 }
5052
51 /** What stops a close, in one sentence naming the issues, or null when nothing does. */
52 export function stopsClose(app: App, chapter: Chapter): string | null {
53 const left = inTheWay(app, chapter);
53 /**
54 * What stops a close, in one sentence naming the issues `view` may see, or null when nothing does.
55 * The refusal after the owner's own close names every one.
56 */
57 export function stopsClose(app: App, chapter: Chapter, view: ItemView): string | null {
outdated

Same: stopsClose names issue titles; require the view rather than defaulting to all.

58 const left = inTheWay(app, chapter, view);
5459 if (left.length === 0) return null;
5560 const shown = left.slice(0, 5).map((i) => `#${i.number} ${i.title}`).join(", ");
5661 return `${chapter.name} cannot close: ${left.length} ${left.length === 1 ? "issue is" : "issues are"} still in its way: ${shown}${left.length > 5 ? `, and ${left.length - 5} more` : ""}.`;
@@ -147,7 +152,7 @@ function fillPlan(
147152 if (chapter.state === "closed") return err(add ? "closed" : "not_found");
148153 if (add) {
149154 if (chapterOfIssue(app.db, issue.id)?.state === "closed") return err("closed");
150 } else if (!itemsOf(app.db, chapter).some((i) => i.number === issue.number)) return err("not_found");
155 } else if (!itemsOf(app.db, chapter, EVERY_ITEM).some((i) => i.number === issue.number)) return err("not_found");
151156 return ok({ actor, chapter, issue });
152157 }
153158
@@ -184,7 +189,7 @@ export interface Refused {
184189
185190 /** Why a refused act stopped, in the words every door prints. */
186191 export function refusalWords(app: App, chapter: Chapter | undefined, refused: Refused): string {
187 if (chapter !== undefined && refused.error === "unfinished") return stopsClose(app, chapter) ?? CHAPTER_WORDS.unfinished;
192 if (chapter !== undefined && refused.error === "unfinished") return stopsClose(app, chapter, EVERY_ITEM) ?? CHAPTER_WORDS.unfinished;
188193 if (refused.error === "unproven") return refused.words ?? CHAPTER_WORDS.unproven;
189194 return CHAPTER_WORDS[refused.error];
190195 }
@@ -227,7 +232,7 @@ async function closePlan(app: App, actor: User | undefined, repo: Repo, name: st
227232 if (chapter === undefined) return err("not_found");
228233 if (chapter.state === "closed") return err("closed");
229234 if (chapter.state !== "open") return err("not_draft");
230 const items = itemsOf(app.db, chapter);
235 const items = itemsOf(app.db, chapter, EVERY_ITEM);
231236 const left = items.filter((i) => i.status !== "done");
232237 if (left.length > 0 && !ship) return err("unfinished");
233238 const why = await unprovenWords(app, chapter, proof);
src/core/chapters.ts +81 −31
@@ -14,6 +14,7 @@ import { id } from "../kernel/id.ts";
1414 import { err, ok, type Result } from "../kernel/result.ts";
1515 import { closesFromBody, getPull } from "./pulls.ts";
1616 import type { Issue } from "./issues.ts";
17 import type { sealedScope } from "./sealed.ts";
1718
1819 export type ChapterState = "draft" | "open" | "closed";
1920
@@ -218,14 +219,34 @@ export interface Item {
218219 readonly costUsd: number;
219220 }
220221
221 interface ItemRow {
222 /**
223 * Whose sealed rows a list may hold (#14905), as `sealedScope` answers it: all of them for a writer
224 * or the crew, the viewer's own for anyone signed in, none for everyone else. A sealed report, and
225 * the sealed pull that fixes it, are left out of the list and out of every count made from it.
226 */
227 export type ItemView = Readonly<ReturnType<typeof sealedScope>>;
228 /** Every row: the owner's own acts (close, fill), which already checked who may. */
229 export const EVERY_ITEM: ItemView = { sealed: true };
230 /** No sealed row: what is written where anyone reads it (a wave, a manifest line). */
231 export const PUBLIC_ITEMS: ItemView = {};
232
233 interface Sealing {
234 readonly sealed: boolean;
235 readonly authorId: string;
236 }
237
238 /** Whether `view` may hold a row with this sealing. */
239 const shows = (view: ItemView, row: Sealing): boolean =>
240 !row.sealed || view.sealed === true || (view.sealedBy !== undefined && view.sealedBy === row.authorId);
241
242 interface ItemRow extends Sealing {
222243 id: string;
223244 number: number;
224245 title: string;
225246 state: "open" | "closed";
226247 }
227248
228 interface PullFact {
249 interface PullFact extends Sealing {
229250 readonly id: string;
230251 readonly number: number;
231252 readonly mergedAt: string | null;
@@ -238,14 +259,16 @@ const round4 = (n: number): number => Math.round(n * 1e4) / 1e4;
238259 * Every pull of the repository with the issue numbers it closes, read once for the whole list: the
239260 * list's cost is one pass over the pulls however many items it holds, never a scan per item.
240261 */
241 function pullFacts(db: Database, repoId: string): PullFact[] {
262 function pullFacts(db: Database, repoId: string, view: ItemView): PullFact[] {
242263 return db
243 .query<{ id: string; number: number; body: string; at: string | null }, [string]>(
244 `SELECT issue.id AS id, issue.number AS number, issue.body AS body, pull.merged_at AS at
264 .query<{ id: string; number: number; body: string; at: string | null; sealed: number; author: string }, [string]>(
265 `SELECT issue.id AS id, issue.number AS number, issue.body AS body, pull.merged_at AS at, issue.sealed AS sealed,
266 issue.author_id AS author
245267 FROM pull JOIN issue ON issue.id = pull.issue_id WHERE issue.repo_id = ?1 AND issue.body LIKE '%#%'`,
246268 )
247269 .all(repoId)
248 .map((r) => ({ id: r.id, number: r.number, mergedAt: r.at, closes: closesFromBody(r.body) }));
270 .filter((r) => shows(view, { sealed: r.sealed === 1, authorId: r.author }))
271 .map((r) => ({ id: r.id, number: r.number, mergedAt: r.at, closes: closesFromBody(r.body), sealed: r.sealed === 1, authorId: r.author }));
249272 }
250273
251274 /** What each issue's own runs spent, by issue id: one grouped read for the repository. */
@@ -290,7 +313,8 @@ function statusOf(
290313
291314 /**
292315 * A closed chapter's list never changes (its items are held, its pulls have landed), so it is read
293 * once and kept: a public page or API read of a closed chapter costs a lookup after the first.
316 * once and kept, one list per view: a public page or API read of a closed chapter costs a lookup
317 * after the first.
294318 */
295319 const FROZEN_MAX = 200;
296320 const frozen = new Map<string, Item[]>();
@@ -300,20 +324,43 @@ export function forgetFrozenItems(): void {
300324 frozen.clear();
301325 }
302326
303 /** A chapter's list, in issue order, each item with where it stands and what it cost. */
304 export function itemsOf(db: Database, chapter: Chapter): Item[] {
305 const kept = chapter.state === "closed" ? frozen.get(chapter.id) : undefined;
327 /**
328 * The view a list for `view` is the same as, when it may be kept: "all" or "none". A reporter's
329 * list is the public one unless they filed a sealed issue or pull in the repository; then it is
330 * theirs alone and read fresh (null), so many distinct readers never churn a cache.
331 */
332 export function keptView(db: Database, repoId: string, view: ItemView): "all" | "none" | null {
333 if (view.sealed === true) return "all";
334 if (view.sealedBy === undefined) return "none";
335 const owns = db
336 .query<{ one: number }, [string, string]>("SELECT 1 AS one FROM issue WHERE repo_id = ?1 AND sealed = 1 AND author_id = ?2 LIMIT 1")
337 .get(repoId, view.sealedBy);
338 return owns === null ? "none" : null;
339 }
340
341 /**
342 * A chapter's list as `view` may see it, in issue order, each item with where it stands and what it
343 * cost. A sealed item the viewer may not see is absent, and so is a sealed pull: it neither names
344 * the item's fix nor adds to its cost.
345 */
346 export function itemsOf(db: Database, chapter: Chapter, view: ItemView): Item[] {
347 const as = keptView(db, chapter.repoId, view);
348 if (as === "none") view = PUBLIC_ITEMS;
349 const key = as === null ? null : `${chapter.id}|${as}`;
350 const kept = chapter.state === "closed" && key !== null ? frozen.get(key) : undefined;
306351 if (kept !== undefined) return kept;
307352 const rows = db
308 .query<ItemRow, [string]>(
309 `SELECT i.id, i.number, i.title, i.state FROM chapter_item c JOIN issue i ON i.id = c.issue_id
310 WHERE c.chapter_id = ?1`,
353 .query<Omit<ItemRow, "sealed"> & { sealed: number }, [string]>(
354 `SELECT i.id, i.number, i.title, i.state, i.sealed, i.author_id AS authorId FROM chapter_item c
355 JOIN issue i ON i.id = c.issue_id WHERE c.chapter_id = ?1`,
311356 )
312357 .all(chapter.id)
358 .map((r): ItemRow => ({ ...r, sealed: r.sealed === 1 }))
359 .filter((r) => shows(view, r))
313360 .sort((a, b) => a.number - b.number);
314361 const out: Item[] = [];
315362 if (rows.length > 0) {
316 const facts = pullFacts(db, chapter.repoId);
363 const facts = pullFacts(db, chapter.repoId, view);
317364 const spend = runSpend(db, chapter.repoId);
318365 for (const r of rows) {
319366 const closing = facts.filter((f) => f.id !== r.id && f.closes.includes(r.number));
@@ -321,9 +368,9 @@ export function itemsOf(db: Database, chapter: Chapter): Item[] {
321368 out.push({ issueId: r.id, number: r.number, title: r.title, ...statusOf(db, chapter.repoId, r, closing), costUsd: cost });
322369 }
323370 }
324 if (chapter.state === "closed") {
371 if (chapter.state === "closed" && key !== null) {
325372 if (frozen.size >= FROZEN_MAX) frozen.delete(frozen.keys().next().value!);
326 frozen.set(chapter.id, out);
373 frozen.set(key, out);
327374 }
328375 return out;
329376 }
@@ -348,7 +395,7 @@ export function progressOf(chapter: Chapter, items: readonly Item[], now: Date):
348395 /**
349396 * The one short line a page's manifest carries ("chapter v2: 7 of 19 left"), or null with no
350397 * chapter open. Counts and the chapter's name only: no issue title, so it reads the same to
351 * everyone.
398 * everyone, and a sealed item is not counted (`PUBLIC_ITEMS`).
352399 */
353400 export function chapterManifestLine(db: Database, repoId: string): string | null {
354401 const open = openChapterOf(db, repoId);
@@ -365,7 +412,8 @@ export function chapterManifestLine(db: Database, repoId: string): string | null
365412 function leftOf(db: Database, chapter: Chapter): { left: number; total: number } {
366413 const rows = db
367414 .query<{ id: string; number: number; state: string }, [string]>(
368 `SELECT i.id, i.number, i.state FROM chapter_item c JOIN issue i ON i.id = c.issue_id WHERE c.chapter_id = ?1`,
415 `SELECT i.id, i.number, i.state FROM chapter_item c JOIN issue i ON i.id = c.issue_id
416 WHERE c.chapter_id = ?1 AND i.sealed = 0`,
369417 )
370418 .all(chapter.id);
371419 const closed = rows.filter((r) => r.state === "closed");
@@ -376,7 +424,7 @@ function leftOf(db: Database, chapter: Chapter): { left: number; total: number }
376424 `SELECT i.id AS id, i.body AS body FROM release r
377425 JOIN issue i ON i.repo_id = r.repo_id AND i.number = r.pull_number
378426 JOIN pull p ON p.issue_id = i.id
379 WHERE r.repo_id = ?1 AND r.ok = 1 AND p.merged_at IS NOT NULL AND i.body LIKE '%#%'`,
427 WHERE r.repo_id = ?1 AND r.ok = 1 AND p.merged_at IS NOT NULL AND i.sealed = 0 AND i.body LIKE '%#%'`,
380428 )
381429 .all(chapter.repoId)
382430 .map((p) => ({ id: p.id, closes: closesFromBody(p.body) }));
@@ -501,22 +549,24 @@ export function inheritChapter(db: Database, parent: Issue, children: readonly I
501549 * text or time. A pull serves the chapter holding its own issue, else the chapter holding an issue
502550 * it closes (`Closes #N`). One query over the items and one over the merged pulls.
503551 */
504 export function chapterOfPulls(db: Database, repoId: string): Map<number, string> {
552 export function chapterOfPulls(db: Database, repoId: string, view: ItemView): Map<number, string> {
505553 const items = db
506 .query<{ number: number; chapter: string }, [string]>(
507 `SELECT i.number AS number, c.chapter_id AS chapter FROM chapter_item c
554 .query<{ number: number; chapter: string; sealed: number; author: string }, [string]>(
555 `SELECT i.number AS number, c.chapter_id AS chapter, i.sealed AS sealed, i.author_id AS author FROM chapter_item c
508556 JOIN issue i ON i.id = c.issue_id JOIN chapter ch ON ch.id = c.chapter_id WHERE ch.repo_id = ?1`,
509557 )
510 .all(repoId);
558 .all(repoId)
559 .filter((r) => shows(view, { sealed: r.sealed === 1, authorId: r.author }));
511560 const out = new Map<number, string>();
512561 if (items.length === 0) return out;
513562 const held = new Map(items.map((r) => [r.number, r.chapter]));
514563 const merged = db
515 .query<{ number: number; body: string }, [string]>(
516 `SELECT issue.number AS number, issue.body AS body FROM pull JOIN issue ON issue.id = pull.issue_id
517 WHERE issue.repo_id = ?1 AND pull.merged_at IS NOT NULL`,
564 .query<{ number: number; body: string; sealed: number; author: string }, [string]>(
565 `SELECT issue.number AS number, issue.body AS body, issue.sealed AS sealed, issue.author_id AS author
566 FROM pull JOIN issue ON issue.id = pull.issue_id WHERE issue.repo_id = ?1 AND pull.merged_at IS NOT NULL`,
518567 )
519 .all(repoId);
568 .all(repoId)
569 .filter((r) => shows(view, { sealed: r.sealed === 1, authorId: r.author }));
520570 for (const p of merged) {
521571 const chapter = held.get(p.number) ?? closesFromBody(p.body).map((n) => held.get(n)).find((c) => c !== undefined);
522572 if (chapter !== undefined) out.set(p.number, chapter);
@@ -539,13 +589,13 @@ export const barCount = (bar: Bar): string => `${bar.chapter.name}: ${bar.done}
539589 export const barNext = (bar: Bar): string => (bar.next === null ? "" : `next: #${bar.next.number} ${bar.next.title}`);
540590
541591 /**
542 * The bar for a repository; null when no chapter is open. The next item is the lowest-numbered
543 * one not done.
592 * The bar for a repository as `view` may see it; null when no chapter is open. The next item is
593 * the lowest-numbered one not done.
544594 */
545 export function barOf(db: Database, repoId: string): Bar | null {
595 export function barOf(db: Database, repoId: string, view: ItemView): Bar | null {
546596 const chapter = openChapterOf(db, repoId);
547597 if (chapter === undefined) return null;
548 const items = itemsOf(db, chapter);
598 const items = itemsOf(db, chapter, view);
549599 const done = items.filter((i) => i.status === "done").length;
550600 const next = items.find((i) => i.status !== "done") ?? null;
551601 return { chapter, done, total: items.length, next };
src/http/api/chapters.ts +8 −6
@@ -5,15 +5,16 @@
55 */
66
77 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";
8 import { getChapter, itemsOf, listChapters, progressOf, type Chapter, type ItemView } from "../../core/chapters.ts";
9 import { sealedScope } from "../../core/sealed.ts";
910 import type { Handler } from "../context.ts";
1011 import { apiError, body, json, notFound, requireScope } from "../respond.ts";
1112 import { loadRepo } from "../api.ts";
1213 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1314 import type { Router } from "../router.ts";
1415
15 const shape = (db: Parameters<typeof itemsOf>[0], c: Chapter, now: Date) => {
16 const items = itemsOf(db, c);
16 const shape = (db: Parameters<typeof itemsOf>[0], c: Chapter, now: Date, view: ItemView) => {
17 const items = itemsOf(db, c, view);
1718 return {
1819 name: c.name,
1920 means: c.means,
@@ -35,7 +36,8 @@ export function chapterRoutes(router: Router<Handler>): void {
3536 const repo = loadRepo(ctx);
3637 if (!repo) return notFound();
3738 const now = new Date();
38 return json({ chapters: listChapters(ctx.app.db, repo.id).map((c) => shape(ctx.app.db, c, now)) }, 200, { "cache-control": "no-store" });
39 const view = sealedScope(ctx.app.db, repo, ctx.auth.user);
40 return json({ chapters: listChapters(ctx.app.db, repo.id).map((c) => shape(ctx.app.db, c, now, view)) }, 200, { "cache-control": "no-store" });
3941 });
4042
4143 router.add("POST", "/api/v1/repos/:owner/:name/chapters", async (ctx) => {
@@ -49,7 +51,7 @@ export function chapterRoutes(router: Router<Handler>): void {
4951 means: typeof input["means"] === "string" ? input["means"] : "",
5052 });
5153 if (!made.ok) return apiError(made.error, made.error === "forbidden" ? 403 : made.error === "exists" ? 409 : 422, CHAPTER_WORDS[made.error]);
52 return json(shape(ctx.app.db, made.value, new Date()), 201);
54 return json(shape(ctx.app.db, made.value, new Date(), sealedScope(ctx.app.db, repo, ctx.auth.user)), 201);
5355 });
5456
5557 router.add("POST", "/api/v1/repos/:owner/:name/chapters/:chapter/:verb", async (ctx) => {
@@ -71,6 +73,6 @@ export function chapterRoutes(router: Router<Handler>): void {
7173 if (!done.ok)
7274 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));
7375 const value = done.value;
74 return json(value === undefined ? { ok: true } : shape(ctx.app.db, value, new Date()), 200);
76 return json(value === undefined ? { ok: true } : shape(ctx.app.db, value, new Date(), sealedScope(ctx.app.db, repo, ctx.auth.user)), 200);
7577 });
7678 }
src/http/mcp/tools/repo.ts +2 −1
@@ -7,6 +7,7 @@ import { creditFacts } from "../../../actions/credit_facts.ts";
77 import { type ChapterActError, close, fill, open, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
88 import { costSentence, getChapter, itemsOf, spentOf, listChapters, progressOf, progressSentence } from "../../../core/chapters.ts";
99 import { err } from "../../../kernel/result.ts";
10 import { sealedScope } from "../../../core/sealed.ts";
1011 import { good, str, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1112
1213 export const tool: Tool = {
@@ -54,7 +55,7 @@ export const tool: Tool = {
5455 return good({ chapters: listChapters(ctx.app.db, repo.id).map((c) => ({ name: c.name, means: c.means, state: c.state })) });
5556 const c = getChapter(ctx.app.db, repo.id, name);
5657 if (c === undefined) return bad("not_found", "no such chapter");
57 const items = itemsOf(ctx.app.db, c);
58 const items = itemsOf(ctx.app.db, c, sealedScope(ctx.app.db, repo, user));
5859 const p = progressOf(c, items, now);
5960 return good({
6061 name: c.name, means: c.means, state: c.state, progress: progressSentence(p), cost: costSentence(items), spentUsd: spentOf(items), finishesOn: p.finishesOn,
src/release/chapter_groups.ts +2 −1
@@ -7,6 +7,7 @@
77
88 import type { Database } from "bun:sqlite";
99 import { chapterOfPulls, listChapters, type Chapter } from "../core/chapters.ts";
10 import { sealedScope } from "../core/sealed.ts";
1011 import { canRead, getRepo } from "../core/repos.ts";
1112 import type { User } from "../core/users.ts";
1213 import type { ChapterWave } from "./chapter_waves.ts";
@@ -70,7 +71,7 @@ export function chapterEntries(db: Database, live: readonly Landing[], user: Use
7071 if (repo === undefined) continue;
7172 const canSee = canRead(db, repo, user);
7273 if (!canSee) continue;
73 const served = chapterOfPulls(db, repo.id);
74 const served = chapterOfPulls(db, repo.id, sealedScope(db, repo, user));
7475 for (const chapter of listChapters(db, repo.id)) {
7576 if (chapter.state === "draft") continue;
7677 const pulls = [...served].filter(([, id]) => id === chapter.id).map(([number]) => number);
src/tui/screens/changelog.ts +2 −1
@@ -8,6 +8,7 @@
88 */
99
1010 import { chapterOfPulls, listChapters } from "../../core/chapters.ts";
11 import { sealedScope } from "../../core/sealed.ts";
1112 import { withWaves } from "../../release/chapter_waves.ts";
1213 import { groupByChapter, type ChapterEntry, type Group } from "../../release/chapter_groups.ts";
1314 import { gather, plainTitle } from "../../story/gather.ts";
@@ -257,7 +258,7 @@ export function changelogScreen(f: Session, ctx: Ctx): Screen {
257258 const name = `${read.repo.ownerName}/${read.repo.name}`;
258259 // Whether this reader may see the repository goes through the same door as opening a pull.
259260 const canSee = sourceFor(f.app, f.user, { owner: read.repo.ownerName, name: read.repo.name }).ok;
260 const served = chapterOfPulls(f.app.db, read.repo.id);
261 const served = chapterOfPulls(f.app.db, read.repo.id, sealedScope(f.app.db, read.repo, f.user));
261262 const entries: ChapterEntry[] = listChapters(f.app.db, read.repo.id).map((chapter) => ({
262263 repo: name,
263264 chapter,
src/tui/screens/chapters.ts +4 −3
@@ -12,6 +12,7 @@
1212 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
1313 import { barCount, barNext, barOf, costSentence, getChapter, nextChapterOf, nextWords, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1414 import { canAdmin, type Repo } from "../../core/repos.ts";
15 import { sealedScope } from "../../core/sealed.ts";
1516 import type { Ctx, Screen } from "../app/app.ts";
1617 import type { Command } from "../app/palette.ts";
1718 import { binding } from "../app/keys.ts";
@@ -25,7 +26,7 @@ const isChapterEvent = (kind: string): boolean => kind.startsWith("chapter.") ||
2526
2627 /** The words under a chapter's name: what done means, then how far it is. */
2728 function chapterRow(f: Session, repo: Repo, c: Chapter): ListRow {
28 const items = itemsOf(f.app.db, c);
29 const items = itemsOf(f.app.db, c, sealedScope(f.app.db, repo, f.user));
2930 const p = progressOf(c, items, new Date());
3031 const undo = c.state === "closed" && undoableClose(f.app, repo, c) ? " Closed just now: u undoes it." : "";
3132 const progress = (c.state === "closed" ? "finished" : `${progressSentence(p)} ${costSentence(items)}`) + undo;
@@ -59,7 +60,7 @@ export function chapterScreen(f: Session, ctx: Ctx, repo: Repo, name: string): S
5960 const state = new ListState();
6061 const items = (): Item[] => {
6162 const c = getChapter(f.app.db, repo.id, name);
62 return c === undefined ? [] : itemsOf(f.app.db, c);
63 return c === undefined ? [] : itemsOf(f.app.db, c, sealedScope(f.app.db, repo, f.user));
6364 };
6465 // The page's Next line, read when the screen loads and when a chapter event arrives, not per
6566 // frame.
@@ -186,7 +187,7 @@ export function chaptersScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
186187 render(area, s) {
187188 const c = ctx.theme.c;
188189 const chapters = all();
189 const bar = barOf(f.app.db, repo.id);
190 const bar = barOf(f.app.db, repo.id, sealedScope(f.app.db, repo, f.user));
190191 const [barArea, head, list] = split(area, "v", [len(bar === null ? 0 : 1), len(1), fillSpace(1)]);
191192 // The home's bar, the same words: the open chapter's count and its next item.
192193 if (bar !== null) s.text(barArea!.x, barArea!.y, truncate(`${barCount(bar)} ${barNext(bar)}`.trim(), barArea!.w), style(c.fg, c.bg), barArea!.x + barArea!.w);
src/tui/screens/next.ts +1 −1
@@ -70,8 +70,8 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7070 growing = undefined;
7171 ranked = undefined;
7272 } else {
73 ranked = chapterLineWords(listChapters(f.db, repo.id), (ch) => itemsOf(f.db, ch), new Date()) ?? undefined;
7473 const scope = sealedScope(f.db, repo, f.user);
74 ranked = chapterLineWords(listChapters(f.db, repo.id), (ch) => itemsOf(f.db, ch, scope), new Date()) ?? undefined;
7575 const next = nextUp(f.db, repo, scope, (ready) => notStartable(f.app, repo, ready, scope));
7676 rows = next.rows;
7777 away = next.notNowTotal;
src/web/pages/chapters.ts +2 −1
@@ -9,6 +9,7 @@
99 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
1010 import { costSentence, nextParts, getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1111 import { canAdmin, type Repo } from "../../core/repos.ts";
12 import { sealedScope } from "../../core/sealed.ts";
1213 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1314 import type { Ctx } from "../../http/context.ts";
1415 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repoPalette } from "../chrome.ts";
@@ -108,7 +109,7 @@ export function chapterPage(ctx: Ctx): Response {
108109 const c = getChapter(ctx.app.db, repo.id, ctx.params.chapter ?? "");
109110 if (c === undefined) return notFoundPage(ctx);
110111 const may = isOwner(ctx, repo);
111 const items = itemsOf(ctx.app.db, c);
112 const items = itemsOf(ctx.app.db, c, sealedScope(ctx.app.db, repo, ctx.auth.user));
112113 const p = progressOf(c, items, new Date());
113114 const rendering = performance.now();
114115 const here = hrefOf(repo, c);
src/web/pages/next_chapters.ts +6 −3
@@ -7,6 +7,7 @@
77 import { CLOSE_UNDO_MS, stopsClose, undoableClose } from "../../actions/chapters.ts";
88 import { chapterLineParts, itemsOf, progressOf, progressSentence, type Chapter } from "../../core/chapters.ts";
99 import { canAdmin, type Repo } from "../../core/repos.ts";
10 import { sealedScope } from "../../core/sealed.ts";
1011 import type { Ctx } from "../../http/context.ts";
1112 import { repoBase } from "../chrome.ts";
1213 import { html, type Html } from "../html.ts";
@@ -27,11 +28,12 @@ export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonl
2728 const base = repoBase(repo);
2829 const may = ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent" && canAdmin(app.db, repo, ctx.auth.user);
2930 const now = Date.now();
31 const view = sealedScope(app.db, repo, ctx.auth.user);
3032 const rows = all.slice(0, SHOWN).map((c) => {
31 const items = itemsOf(app.db, c);
33 const items = itemsOf(app.db, c, view);
3234 const p = progressOf(c, items, new Date(now));
3335 const link = html`<a href="${base}/chapters/${encodeURIComponent(c.name)}">${c.name}</a>`;
34 const stop = c.state === "open" ? stopsClose(app, c) : null;
36 const stop = c.state === "open" ? stopsClose(app, c, view) : null;
3537 const undo = c.state === "closed" && may && undoableClose(app, repo, c, now);
3638 const recent = c.state === "closed" && c.closedAt !== null && now - Date.parse(c.closedAt) <= CLOSE_UNDO_MS;
3739 const meta =
@@ -66,7 +68,8 @@ export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonl
6668 */
6769 export function chapterLine(ctx: Ctx, repo: Repo, all: readonly Chapter[]): Html | null {
6870 const base = repoBase(repo);
69 const p = chapterLineParts(all, (c) => itemsOf(ctx.app.db, c), new Date());
71 const view = sealedScope(ctx.app.db, repo, ctx.auth.user);
72 const p = chapterLineParts(all, (c) => itemsOf(ctx.app.db, c, view), new Date());
7073 if (p === null) return null;
7174 if (p.chapter === null) return html`<p class="muted" data-chapter-line>${p.lead}<a href="${base}/chapters">${p.name}</a>${p.tail}</p>`;
7275 return html`<p data-chapter-line>${p.lead}<a href="${base}/chapters/${encodeURIComponent(p.chapter.name)}">${p.name}</a>${p.tail}</p>`;
src/web/studio/chapter_bar.ts +8 −2
@@ -5,8 +5,9 @@
55 * the chapter, the next item is the meta, in full so it wraps rather than cuts.
66 */
77 import type { App } from "../../app.ts";
8 import { barCount, barNext, barOf } from "../../core/chapters.ts";
8 import { barCount, barNext, barOf, keptView } from "../../core/chapters.ts";
99 import { canRead, getRepo } from "../../core/repos.ts";
10 import { sealedScope } from "../../core/sealed.ts";
1011 import type { User } from "../../core/users.ts";
1112 import { repoBase } from "../chrome.ts";
1213 import { html, type Html } from "../html.ts";
@@ -18,7 +19,12 @@ export function chapterBar(app: App, user: User | undefined): Html | null {
1819 if (owner === "" || name === "") return null;
1920 const repo = getRepo(app.db, owner, name);
2021 if (repo === undefined || !canRead(app.db, repo, user)) return null;
21 const bar = appReuse(app.db, `chapter-bar:${repo.id}`, () => barOf(app.db, repo.id));
22 // Kept per repository and audience, as the chapter page sees it (`sealedScope`): a writer's bar
23 // may name a sealed item, a reporter's counts their own, everyone else's neither names nor counts
24 // one. Only the "all" and "none" bars are kept; a reporter's own is read fresh.
25 const view = sealedScope(app.db, repo, user);
outdated

A reporter sees their own sealed item on the chapter page but the bar uses the public view, so the two disagree. Key by the real scope, or test and document the difference.

26 const as = keptView(app.db, repo.id, view);
27 const bar = as === null ? barOf(app.db, repo.id, view) : appReuse(app.db, `chapter-bar:${repo.id}:${as}`, () => barOf(app.db, repo.id, view));
2228 if (bar === null) return null;
2329 return html`<ul class="list setting-list door-section">${row({
2430 nav: true,
test/changelog-chapters.test.ts +4 −4
@@ -6,7 +6,7 @@ import { chapterStamp, shippedRegion } from "../src/web/pages/changelog.ts";
66 import { withWaves } from "../src/release/chapter_waves.ts";
77 import { chapterLines } from "../src/tui/screens/changelog.ts";
88 import { chapterEntries, groupByChapter, type ChapterEntry } from "../src/release/chapter_groups.ts";
9 import { chapterOfPulls } from "../src/core/chapters.ts";
9 import { chapterOfPulls, EVERY_ITEM } from "../src/core/chapters.ts";
1010 import { createRepo } from "../src/actions/repos.ts";
1111 import { getRepo } from "../src/core/repos.ts";
1212 import { createUser } from "../src/core/users.ts";
@@ -116,7 +116,7 @@ test("which chapter a pull served is read from the items; chapterStamp moves wit
116116 const id = mergedPull(app, repo.id, n, body);
117117 app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', ?2, 'a', 'b', ?3)").run(id, `p${n}`, day(5));
118118 }
119 expect([...chapterOfPulls(app.db, repo.id)]).toEqual([[2, c1]]);
119 expect([...chapterOfPulls(app.db, repo.id, EVERY_ITEM)]).toEqual([[2, c1]]);
120120 const live = [land(3, day(5)), land(2, day(5))].map((l) => ({ ...l, repo: "own/r" }));
121121 const groups = groupByChapter(live, chapterEntries(app.db, live, undefined));
122122 expect(groups.map((g) => [g.kind, g.landings.map((l) => l.number)])).toEqual([["chapter", []], ["chapter", [2]], ["between", [3]]]);
@@ -178,8 +178,8 @@ test("a pull that closes issues in two chapters is placed in the first match, in
178178 };
179179 put(3, "Closes #2, closes #1");
180180 put(4, "Closes #1 and closes #2");
181 expect(chapterOfPulls(app.db, repo.id).get(3)).toBe(c2);
182 expect(chapterOfPulls(app.db, repo.id).get(4)).toBe(c1);
181 expect(chapterOfPulls(app.db, repo.id, EVERY_ITEM).get(3)).toBe(c2);
182 expect(chapterOfPulls(app.db, repo.id, EVERY_ITEM).get(4)).toBe(c1);
183183 } finally {
184184 app.close();
185185 }
test/chapter-next.test.ts +2 −2
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { newApp } from "../src/actions/apps.ts";
77 import { createApp, type App } from "../src/app.ts";
8 import { draftChapter, startChapter, getChapter } from "../src/core/chapters.ts";
8 import { draftChapter, startChapter, getChapter, EVERY_ITEM } from "../src/core/chapters.ts";
99 import { getRepo, type Repo } from "../src/core/repos.ts";
1010 import { createToken } from "../src/core/tokens.ts";
1111 import { createUser, type User } from "../src/core/users.ts";
@@ -94,7 +94,7 @@ const terminalNext = async () => {
9494 };
9595 const line = (slug: string) => {
9696 const r = getRepo(app.db, "alice", slug)!;
97 return chapterLineWords(listChapters(app.db, r.id), (c) => itemsOf(app.db, c), new Date());
97 return chapterLineWords(listChapters(app.db, r.id), (c) => itemsOf(app.db, c, EVERY_ITEM), new Date());
9898 };
9999 return { screenOf, line };
100100 };
test/chapters-cost.test.ts +2 −2
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { newApp } from "../src/actions/apps.ts";
77 import { createApp, type App } from "../src/app.ts";
8 import { costSentence, draftChapter, getChapter, itemsOf, putIssue, spentOf, startChapter } from "../src/core/chapters.ts";
8 import { costSentence, draftChapter, getChapter, itemsOf, putIssue, spentOf, startChapter, EVERY_ITEM } from "../src/core/chapters.ts";
99 import { createIssue } from "../src/core/issues.ts";
1010 import { getRepo, type Repo } from "../src/core/repos.ts";
1111 import { createUser } from "../src/core/users.ts";
@@ -70,7 +70,7 @@ describe("an open chapter's cost", () => {
7070 )
7171 .get(c.id)!.s;
7272 expect(sum).toBe(1.85);
73 const items = itemsOf(app.db, chapter);
73 const items = itemsOf(app.db, chapter, EVERY_ITEM);
7474 expect(spentOf(items)).toBe(1.85);
7575 expect(costSentence(items)).toBe("$1.85 spent so far.");
7676 });
test/chapters-page.test.ts +2 −2
@@ -12,7 +12,7 @@ import { CHAPTER_WORDS, close, draft, fill, open, reopen, stopsClose } from "../
1212 import { useProof } from "../src/core/v1_proof.ts";
1313 import { probes } from "../src/core/v1_proof.ts";
1414 import { createApp, type App } from "../src/app.ts";
15 import { getChapter, listChapters } from "../src/core/chapters.ts";
15 import { EVERY_ITEM, getChapter, listChapters } from "../src/core/chapters.ts";
1616 import { createIssue } from "../src/core/issues.ts";
1717 import { getRepo, type Repo } from "../src/core/repos.ts";
1818 import { createAgentRow } from "../src/core/agents.ts";
@@ -112,7 +112,7 @@ describe("chapters on /next", () => {
112112 const page = await (await get("/alice/shop/next")).text();
113113 expect(page).toContain("v1.0.0 cannot close: 2 issues are still in its way");
114114 expect(page).toContain(`#${numbers[0]} Item Alpha`);
115 expect(stopsClose(app, getChapter(app.db, repo.id, "v1.0.0")!)).toContain(`#${numbers[1]} Item Beta`);
115 expect(stopsClose(app, getChapter(app.db, repo.id, "v1.0.0")!, EVERY_ITEM)).toContain(`#${numbers[1]} Item Beta`);
116116 const refused = await post("/alice/shop/chapters/v1.0.0/close");
117117 expect(refused.status).toBeLessThan(400);
118118 expect(decodeURIComponent(refused.headers.get("set-cookie") ?? "")).toContain("cannot close");
test/chapters-sealed.test.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * A chapter's list holds sealed security reports only for those who may see them (#14905): a reader
3 * sees neither the report nor the sealed pull that fixes it, and every count agrees with the list.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { newApp } from "../src/actions/apps.ts";
10 import { manifestFor } from "../src/actions/here.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { barOf, chapterOfPulls, draftChapter, forgetFrozenItems, itemsOf, progressOf, putIssue, startChapter, type Chapter } from "../src/core/chapters.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { getRepo, type Repo } from "../src/core/repos.ts";
15 import { sealedScope } from "../src/core/sealed.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 import { createForgeApp } from "../src/tui/forge.ts";
20 import { chapterScreen, chaptersScreen } from "../src/tui/screens/chapters.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { chapterBar } from "../src/web/studio/chapter_bar.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { settleApp } from "./helpers/tui.ts";
25
26 quietLogs();
27
28 let dir = "";
29 let app: App;
30 let servers: Servers;
31 const tokens = new Map<User, string>();
32 let owner: User;
33 let reader: User;
34 let reporter: User;
35 let repo: Repo;
36 let chapter: Chapter;
37 let sealedNumber = 0;
38 let fixNumber = 0;
39
40 const person = async (name: string, first = false): Promise<User> => {
41 const made = await createUser(app.db, { username: name, email: `${name}@forge.test`, password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: first });
42 if (!made.ok) throw new Error(String(made.error));
43 return made.value;
44 };
45
46 beforeAll(async () => {
47 dir = await mkdtemp(join(tmpdir(), "forge-chapters-sealed-"));
48 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
49 owner = await person("alice", true);
50 reader = await person("bob");
51 reporter = await person("carol");
52 const c = await newApp(app, owner, { name: "shop", description: "Words", visibility: "public" });
53 if (!c.ok) throw new Error(String(c.error));
54 repo = getRepo(app.db, "alice", "shop")!;
55 const ch = draftChapter(app.db, repo.id, { name: "v2" }, owner.id);
56 if (!ch.ok) throw new Error("draft");
57 const plain = createIssue(app.db, { repoId: repo.id, authorId: owner.id, title: "Plain work" });
58 const report = createIssue(app.db, { repoId: repo.id, authorId: reporter.id, title: "Token leak in /hook", sealed: true });
59 if (!plain.ok || !report.ok) throw new Error("issue");
60 putIssue(app.db, ch.value, plain.value.id, owner.id);
61 putIssue(app.db, ch.value, report.value.id, owner.id);
62 sealedNumber = report.value.number;
63 // The sealed fix also claims the plain item: a reader must not learn its number from there
64 // either.
65 fixNumber = 9001;
66 app.db
67 .query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, sealed) VALUES ('fix', ?1, ?2, 'pull', 'Fix', ?3, ?4, 'open', 1)`)
68 .run(repo.id, fixNumber, `Closes #${sealedNumber}, closes #${plain.value.number}`, owner.id);
69 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES ('fix', 'main', 'fix', 'a', 'b', '2026-11-10T00:00:00.000Z')`).run();
70 app.db.query("UPDATE issue SET state = 'closed' WHERE id IN (?1, ?2)").run(plain.value.id, report.value.id);
71 startChapter(app.db, ch.value, new Date());
72 chapter = ch.value;
73 servers = await serve(app);
74 for (const u of [owner, reader, reporter]) tokens.set(u, createToken(app.db, u.id, "t", "rw").token);
75 }, 30_000);
76
77 afterAll(async () => {
78 servers.stop();
79 app.close();
80 await rm(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
81 });
82
83 const seen = (user: User | undefined) => itemsOf(app.db, chapter, sealedScope(app.db, repo, user));
84
85 test("a reader and a passer-by see no sealed item, no sealed pull, and counts that agree", () => {
86 for (const who of [reader, undefined]) {
87 const items = seen(who);
88 expect(items.map((i) => i.title)).toEqual(["Plain work"]);
89 expect(items.every((i) => i.pull !== fixNumber)).toBe(true);
90 expect(JSON.stringify(items)).not.toContain("Token leak");
91 expect(progressOf(chapter, items, new Date()).total).toBe(1);
92 const bar = barOf(app.db, repo.id, sealedScope(app.db, repo, who))!;
93 expect(bar.total).toBe(1);
94 }
95 });
96
97 test("the writer sees the report and its fix; its reporter sees their own", () => {
98 const all = seen(owner);
99 expect(all.map((i) => i.title).sort()).toEqual(["Plain work", "Token leak in /hook"]);
100 expect(all.find((i) => i.number === sealedNumber)!.pull).toBe(fixNumber);
101 expect(all.find((i) => i.title === "Plain work")!.pull).toBe(fixNumber);
102 expect(seen(reporter).map((i) => i.number)).toContain(sealedNumber);
103 });
104
105 test("the manifest line, the same to everyone, does not count the sealed item", () => {
106 const m = manifestFor(app, reader, undefined, "https://forge.test", "/alice/shop");
107 if (!m.ok || m.value.here.kind !== "repository") throw new Error("no manifest");
108 expect(m.value.here.chapter).toBe("chapter v2: 1 of 1 left");
109 });
110
111 const LEAK = "Token leak";
112 const auth = (who: User | undefined): Record<string, string> => (who === undefined ? {} : { authorization: `Bearer ${tokens.get(who)}` });
113 const text = async (path: string, who: User | undefined) => (await fetch(`${servers.url}${path}`, { headers: auth(who) })).text();
114 const mcp = async (who: User, args: unknown) => {
115 const res = await fetch(`${servers.url}/mcp`, {
116 method: "POST",
117 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...auth(who) },
118 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "repo", arguments: args } }),
119 });
120 const body = (await res.json()) as { result: { content: { text: string }[] } };
121 return body.result.content[0]!.text;
122 };
123
124 test("the chapter page, /next and the API: the writer and the reporter see the report, a reader and a passer-by do not", async () => {
125 for (const path of ["/alice/shop/chapters/v2", "/alice/shop/next", "/api/v1/repos/alice/shop/chapters"]) {
126 for (const who of [owner, reporter]) expect(await text(path, who)).toContain(LEAK);
127 for (const who of [reader, undefined]) {
128 const body = await text(path, who);
129 expect(body).toContain("v2");
130 expect(body).not.toContain(LEAK);
131 expect(body).not.toContain(`#${sealedNumber}`);
132 }
133 }
134 });
135
136 test("the MCP repo tool names the report's item to the writer only", async () => {
137 expect(await mcp(owner, { repo: "alice/shop", view: "chapters", chapter: "v2" })).toContain(LEAK);
138 const read = await mcp(reader, { repo: "alice/shop", view: "chapters", chapter: "v2" });
139 expect(read).toContain("Plain work");
140 expect(read).not.toContain(LEAK);
141 });
142
143 test("the chapter bar counts what the page lists: two for the writer and the reporter, one for anyone else", () => {
144 const was = app.config.forgeRepo;
145 app.config.forgeRepo = "alice/shop";
146 try {
147 const bar = (who: User | undefined) => String(chapterBar(app, who));
148 // The reader's bar is read first so a kept public bar is in the cache when the reporter asks.
149 for (const who of [reader, undefined]) expect(bar(who)).toContain("v2: 0 of 1");
150 expect(bar(owner)).toContain("v2: 0 of 2");
151 expect(bar(reporter)).toContain("v2: 0 of 2");
152 expect(bar(reader)).toContain("v2: 0 of 1");
153 } finally {
154 if (was === undefined) delete app.config.forgeRepo;
155 else app.config.forgeRepo = was;
156 }
157 });
158
159 test("the terminal's Chapters screen and the chapter's list show what the page shows", async () => {
160 const shown = async (who: User | undefined, one: boolean) => {
161 const guest = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who };
162 const { app: tui, session } = createForgeApp(app, guest, { terminal: headlessTerminal(120, 30), exitHooks: false });
163 tui.start();
164 tui.ctx.push(one ? chapterScreen(session, tui.ctx, repo, "v2") : chaptersScreen(session, tui.ctx, repo));
165 await settleApp(tui);
166 const out = tui.screen.toText().replace(/\s+/g, " ");
167 tui.stop?.();
168 return out;
169 };
170 expect(await shown(owner, false)).toContain("v2: 0 of 2");
171 expect(await shown(reader, false)).toContain("v2: 0 of 1");
172 expect(await shown(owner, true)).toContain(LEAK);
173 const list = await shown(reader, true);
174 expect(list).toContain("Plain work");
175 expect(list).not.toContain(LEAK);
176 });
177
178 test("the changelog's chapter grouping holds a sealed pull only for those who may see it", () => {
179 expect(chapterOfPulls(app.db, repo.id, sealedScope(app.db, repo, owner)).get(fixNumber)).toBe(chapter.id);
180 expect(chapterOfPulls(app.db, repo.id, sealedScope(app.db, repo, reader)).has(fixNumber)).toBe(false);
181 });
182
183 test("a closed chapter's kept list is kept per view: the writer's never reaches a reader", () => {
184 forgetFrozenItems();
185 app.db.query("UPDATE chapter SET state = 'closed' WHERE id = ?1").run(chapter.id);
186 const closed = { ...chapter, state: "closed" as const };
187 expect(itemsOf(app.db, closed, sealedScope(app.db, repo, owner)).length).toBe(2);
188 expect(itemsOf(app.db, closed, sealedScope(app.db, repo, undefined)).length).toBe(1);
189 });
190
191 test("a closed chapter keeps only the all and the public list: a reporter's own is read fresh, a reader's is the public one", () => {
192 forgetFrozenItems();
193 const closed = { ...chapter, state: "closed" as const };
194 expect(itemsOf(app.db, closed, sealedScope(app.db, repo, reporter)).map((i) => i.number)).toContain(sealedNumber);
195 expect(itemsOf(app.db, closed, sealedScope(app.db, repo, reader)).length).toBe(1);
196 // The reader's list is the kept public one, the same array, so distinct readers add no entry.
197 expect(itemsOf(app.db, closed, sealedScope(app.db, repo, reader))).toBe(itemsOf(app.db, closed, {}));
198 });
test/chapters-v1.test.ts +3 −3
@@ -11,7 +11,7 @@ import { newApp } from "../src/actions/apps.ts";
1111 import { close, draft, open, refusalWords, type Refused } from "../src/actions/chapters.ts";
1212 import type { Proof } from "../src/core/v1_proof.ts";
1313 import { createApp, type App } from "../src/app.ts";
14 import { forgetFrozenItems, getChapter, itemsOf, recordV1 } from "../src/core/chapters.ts";
14 import { forgetFrozenItems, getChapter, itemsOf, recordV1, EVERY_ITEM } from "../src/core/chapters.ts";
1515 import { getRepo, type Repo } from "../src/core/repos.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { repoDir } from "../src/git/repos.ts";
@@ -62,7 +62,7 @@ describe("v1.0.0 closes on proof", () => {
6262 const made = draft(app, owner, repo, { name: "v1.0.0" });
6363 expect(made.ok).toBe(true);
6464 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));
65 expect(itemsOf(app.db, chapter, EVERY_ITEM).map((i) => i.number)).toEqual([...new Set(probes.map((p) => p.issue))].sort((a, b) => a - b));
6666 const again = recordV1(app.db, repo.id, [999999, 11541], owner.id);
6767 expect(again.ok && again.value.missing).toEqual([999999]);
6868 });
@@ -124,7 +124,7 @@ describe("v1.0.0 closes on proof", () => {
124124 if (!c.ok) throw new Error("commit");
125125 expect(draft(bare, u.value, r, { name: "v1.0.0" }).ok).toBe(true);
126126 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([]);
127 expect(itemsOf(bare.db, getChapter(bare.db, r.id, "v1.0.0")!, EVERY_ITEM)).toEqual([]);
128128 const refused = await close(bare, u.value, r, "v1.0.0", true, new Date(), all("fail"));
129129 expect(!refused.ok && refused.error).toBe("unproven");
130130 expect(getChapter(bare.db, r.id, "v1.0.0")!.state).toBe("open");
test/chapters.test.ts +5 −5
@@ -15,7 +15,7 @@ import { probes } from "../src/core/v1_proof.ts";
1515 import { openIssue } from "../src/actions/issues.ts";
1616 import { createApp, type App } from "../src/app.ts";
1717 import { addCrew, createAgentRow, getAgent } from "../src/core/agents.ts";
18 import { chapterOfIssue, forgetFrozenItems, getChapter, inheritChapter, itemsOf, nextName, patchName, progressOf } from "../src/core/chapters.ts";
18 import { chapterOfIssue, forgetFrozenItems, getChapter, inheritChapter, itemsOf, nextName, patchName, progressOf, EVERY_ITEM } from "../src/core/chapters.ts";
1919 import { createIssue, getIssue, type Issue } from "../src/core/issues.ts";
2020 import { getRepo, type Repo } from "../src/core/repos.ts";
2121 import { createToken } from "../src/core/tokens.ts";
@@ -192,7 +192,7 @@ describe("chapters", () => {
192192
193193 test("an item is struck only when live and proven, not when its pull merged", () => {
194194 const chapter = getChapter(app.db, repo.id, "v1.0.0")!;
195 const find = (n: number) => itemsOf(app.db, chapter).find((i) => i.number === n)!;
195 const find = (n: number) => itemsOf(app.db, chapter, EVERY_ITEM).find((i) => i.number === n)!;
196196 expect(find(issues[0]!.number).status).not.toBe("done");
197197 land(issues[0]!, false);
198198 expect(find(issues[0]!.number).status).toBe("building");
@@ -202,7 +202,7 @@ describe("chapters", () => {
202202 expect(done.status).toBe("done");
203203 expect(done.doneAt).toBe("2026-11-11T08:00:00.000Z");
204204 expect(done.builder).toBe("build");
205 const progress = progressOf(chapter, itemsOf(app.db, chapter), new Date("2026-11-12T00:00:00.000Z"));
205 const progress = progressOf(chapter, itemsOf(app.db, chapter, EVERY_ITEM), new Date("2026-11-12T00:00:00.000Z"));
206206 expect(progress.done).toBe(1);
207207 expect(progress.finishesOn).not.toBeNull();
208208 });
@@ -296,11 +296,11 @@ describe("chapters", () => {
296296 return typeof v === "function" ? v.bind(target) : v;
297297 },
298298 });
299 const first = itemsOf(counting, closed);
299 const first = itemsOf(counting, closed, EVERY_ITEM);
300300 expect(first.length).toBeGreaterThan(0);
301301 expect(scans).toBeLessThanOrEqual(1);
302302 const after = statements;
303 expect(itemsOf(counting, closed)).toBe(first);
303 expect(itemsOf(counting, closed, EVERY_ITEM)).toBe(first);
304304 expect(statements).toBe(after);
305305 });
306306
test/manifest-chapter.test.ts +3 −3
@@ -6,7 +6,7 @@ import { join } from "node:path";
66 import { newApp } from "../src/actions/apps.ts";
77 import { manifestFor } from "../src/actions/here.ts";
88 import { createApp, type App } from "../src/app.ts";
9 import { chapterManifestLine, draftChapter, getChapter, itemsOf, NAME, putIssue, startChapter } from "../src/core/chapters.ts";
9 import { chapterManifestLine, draftChapter, getChapter, itemsOf, NAME, putIssue, startChapter, EVERY_ITEM } from "../src/core/chapters.ts";
1010 import { openIssue } from "../src/actions/issues.ts";
1111 import { getRepo, type Repo } from "../src/core/repos.ts";
1212 import { createUser, type User } from "../src/core/users.ts";
@@ -88,12 +88,12 @@ test("the count is items not yet done: a done item leaves it, a building one sta
8888 return i.value;
8989 });
9090 expect(line(owner)).toBe("chapter v3: 4 of 4 left");
91 const first = itemsOf(app.db, ch)[0]!;
91 const first = itemsOf(app.db, ch, EVERY_ITEM)[0]!;
9292 land(first.issueId, first.number);
9393 expect(line(owner)).toBe("chapter v3: 3 of 4 left");
9494 // closed without a proven release: building, still counted as left
9595 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(made[0]!.id);
96 expect(itemsOf(app.db, ch).find((i) => i.issueId === made[0]!.id)!.status).toBe("building");
96 expect(itemsOf(app.db, ch, EVERY_ITEM).find((i) => i.issueId === made[0]!.id)!.status).toBe("building");
9797 expect(line(owner)).toBe("chapter v3: 3 of 4 left");
9898 });
9999
test/mcp-chapters-act.test.ts +5 −5
@@ -8,7 +8,7 @@ import { createRepo } from "../src/actions/repos.ts";
88 import { CHAPTER_WORDS, close, draft, fill, open } from "../src/actions/chapters.ts";
99 import { createApp, type App } from "../src/app.ts";
1010 import { createIssue } from "../src/core/issues.ts";
11 import { getChapter, itemsOf, listChapters } from "../src/core/chapters.ts";
11 import { getChapter, itemsOf, listChapters, EVERY_ITEM } from "../src/core/chapters.ts";
1212 import { getRepo } from "../src/core/repos.ts";
1313 import { createToken } from "../src/core/tokens.ts";
1414 import { createUser, getUserByName } from "../src/core/users.ts";
@@ -38,7 +38,7 @@ const call = async (token: string, args: unknown) => {
3838 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
3939 };
4040 const repo = () => getRepo(app.db, "alice", "pub")!;
41 const state = () => JSON.stringify(listChapters(app.db, repo().id).map((c) => [c.name, c.state, itemsOf(app.db, c).map((i) => i.number)]));
41 const state = () => JSON.stringify(listChapters(app.db, repo().id).map((c) => [c.name, c.state, itemsOf(app.db, c, EVERY_ITEM).map((i) => i.number)]));
4242
4343 beforeAll(async () => {
4444 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-chapters-act-"));
@@ -105,7 +105,7 @@ test("confirmed open and fill land; a refusal uses CHAPTER_WORDS", async () => {
105105 expect((await call(alice, { repo: "alice/pub", action: "open", chapter: "v1", confirm: true })).value.done).toBe(true);
106106 expect((await call(alice, { repo: "alice/pub", action: "open", chapter: "v1", confirm: true })).error).toContain(CHAPTER_WORDS.already_open);
107107 for (const num of nums) expect((await call(alice, { repo: "alice/pub", action: "add", chapter: "v1", number: num, confirm: true })).value.done).toBe(true);
108 expect(itemsOf(app.db, getChapter(app.db, repo().id, "v1")!).length).toBe(2);
108 expect(itemsOf(app.db, getChapter(app.db, repo().id, "v1")!, EVERY_ITEM).length).toBe(2);
109109 expect((await call(alice, { repo: "alice/pub", action: "remove", chapter: "v1", number: nums[1], confirm: true })).value.done).toBe(true);
110110 expect((await call(alice, { repo: "alice/pub", action: "add", chapter: "v1", number: 999, confirm: true })).error).toContain(CHAPTER_WORDS.no_issue);
111111 expect((await call(alice, { repo: "alice/pub", action: "add", chapter: "v1", confirm: true })).error).toContain("number");
@@ -128,7 +128,7 @@ test("an unconfirmed close names the tag and what moves, and changes nothing; co
128128 const c = getChapter(app.db, repo().id, "v1")!;
129129 expect(c.state).toBe("closed");
130130 const next = getChapter(app.db, repo().id, "v2")!;
131 expect(itemsOf(app.db, next).map((i) => i.number).sort()).toEqual([...nums].sort());
131 expect(itemsOf(app.db, next, EVERY_ITEM).map((i) => i.number).sort()).toEqual([...nums].sort());
132132 expect((await runGit(["rev-parse", "--verify", "--quiet", "refs/tags/v1"], { cwd: repoDir(app.reposRoot, "alice", "pub") })).ok).toBe(true);
133133 expect((await call(alice, { repo: "alice/pub", action: "close", chapter: "v1" })).error).toContain(CHAPTER_WORDS.closed);
134134 });
@@ -201,7 +201,7 @@ test("closing through the MCP leaves what the page's close leaves", async () =>
201201 const tag = await runGit(["rev-parse", "--verify", "--quiet", "refs/tags/v1^{commit}"], { cwd: repoDir(app.reposRoot, "alice", name) });
202202 const head = await runGit(["rev-parse", `refs/heads/${r.defaultBranch}`], { cwd: repoDir(app.reposRoot, "alice", name) });
203203 return {
204 chapters: listChapters(app.db, r.id).map((c) => [c.name, c.state, c.tagOid === null ? null : "tip", itemsOf(app.db, c).map((i) => i.title)]),
204 chapters: listChapters(app.db, r.id).map((c) => [c.name, c.state, c.tagOid === null ? null : "tip", itemsOf(app.db, c, EVERY_ITEM).map((i) => i.title)]),
205205 tagAtTip: tag.ok && head.ok && tag.value.trim() === head.value.trim(),
206206 };
207207 };
test/mcp-chapters.test.ts +3 −3
@@ -7,7 +7,7 @@ import { createRepo } from "../src/actions/repos.ts";
77 import { draft, fill, open } from "../src/actions/chapters.ts";
88 import { createApp, type App } from "../src/app.ts";
99 import { createIssue } from "../src/core/issues.ts";
10 import { getChapter, itemsOf, progressOf, progressSentence } from "../src/core/chapters.ts";
10 import { getChapter, itemsOf, progressOf, progressSentence, EVERY_ITEM } from "../src/core/chapters.ts";
1111 import { getRepo } from "../src/core/repos.ts";
1212 import { createToken } from "../src/core/tokens.ts";
1313 import { createUser } from "../src/core/users.ts";
@@ -58,7 +58,7 @@ beforeAll(async () => {
5858 for (const num of nums) expect(fill(app, a, repo, "v1", num, true).ok).toBe(true);
5959 expect(open(app, a, repo, "v1").ok).toBe(true);
6060 const c = getChapter(app.db, repo.id, "v1")!;
61 const [first, second] = itemsOf(app.db, c);
61 const [first, second] = itemsOf(app.db, c, EVERY_ITEM);
6262 // One done (closed by a merged, proven pull), one building (merged, not proven), one left.
6363 for (const [issue, proven, pn] of [[first!, true, 900], [second!, false, 901]] as const) {
6464 app.db.query("UPDATE issue SET state = 'closed', closed_at = '2026-11-10T00:00:00.000Z' WHERE id = ?1").run(issue.issueId);
@@ -85,7 +85,7 @@ test("a named chapter answers done, building, left and the page's sentence", asy
8585 expect(r.value.items.map((i: any) => i.status).sort()).toEqual(["building", "done", "left"]);
8686 const repo = getRepo(app.db, "alice", "pub")!;
8787 const c = getChapter(app.db, repo.id, "v1")!;
88 expect(r.value.progress).toBe(progressSentence(progressOf(c, itemsOf(app.db, c), new Date())));
88 expect(r.value.progress).toBe(progressSentence(progressOf(c, itemsOf(app.db, c, EVERY_ITEM), new Date())));
8989 expect(r.value.progress).toStartWith("1 of 3 done");
9090 const page = await (await fetch(`${servers.url}/alice/pub/chapters/v1`, { headers: { authorization: `Bearer ${alice}` } })).text();
9191 expect(page).toContain(r.value.progress);
test/tui-chapter-bar.test.ts +2 −2
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createRepo } from "../src/actions/repos.ts";
77 import { createApp, type App } from "../src/app.ts";
8 import { barCount, barNext, barOf, draftChapter, getChapter, startChapter } from "../src/core/chapters.ts";
8 import { barCount, barNext, barOf, draftChapter, getChapter, startChapter, EVERY_ITEM } from "../src/core/chapters.ts";
99 import { createIssue } from "../src/core/issues.ts";
1010 import { putIssue } from "../src/core/chapters.ts";
1111 import type { Repo } from "../src/core/repos.ts";
@@ -58,7 +58,7 @@ test("no open chapter: no bar line; an open one prints the count and the next it
5858 if (!made.ok) throw new Error("issue");
5959 putIssue(app.db, d.value, made.value.id, owner.id);
6060 startChapter(app.db, getChapter(app.db, repo.id, "v2")!, new Date());
61 const bar = barOf(app.db, repo.id)!;
61 const bar = barOf(app.db, repo.id, EVERY_ITEM)!;
6262 expect(barCount(bar)).toBe("v2: 0 of 1");
6363 expect(barNext(bar)).toBe(`next: #${made.value.number} First thing`);
6464 expect(await screenText()).toContain(`v2: 0 of 1 next: #${made.value.number} First thing`);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs