From cdc88bf091521fd87c7a62d54a53a0ddd02b69a5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:23:20 +0000 Subject: [PATCH 01/11] fix(ui-server): count an undone media effect as awaiting review again when nothing selects An Undo from review while another card was pending, or after the pass had ended, left the review's stored media count at the effect's value until the next selection, so the server disagreed with `brain sync` and the CLI. The Undo now re-reads the count with the pass's deferrals, as a selection does, without selecting (#2783). Co-Authored-By: Claude Opus 5.5 --- .changeset/media-undo-recount.md | 5 ++++ .../ui-server/src/inbox/hygiene-review.ts | 9 +++++++ .../ui-server/src/inbox/hygiene-writes.ts | 14 +++++++++++ .../tests/hygiene-media-effects.test.ts | 25 +++++++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 .changeset/media-undo-recount.md diff --git a/.changeset/media-undo-recount.md b/.changeset/media-undo-recount.md new file mode 100644 index 0000000000..000995f9bf --- /dev/null +++ b/.changeset/media-undo-recount.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Undoing a media effect from hygiene review now updates the review's media count when another card is pending or the pass has ended. Before, the count kept the undone effect until the next selection, so it disagreed with `brain sync`. diff --git a/packages/ui-server/src/inbox/hygiene-review.ts b/packages/ui-server/src/inbox/hygiene-review.ts index 723ab48958..d9420166c0 100644 --- a/packages/ui-server/src/inbox/hygiene-review.ts +++ b/packages/ui-server/src/inbox/hygiene-review.ts @@ -237,6 +237,13 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no if (generation !== pauseGeneration) return; await write("select", now(), principalId, resumeRetired, paused, next, finding, options); } + /** The counts the pass's next selection would store, read with its deferrals, without selecting. */ + async function recount(principalId: string) { + const deferred = state().deferred ?? []; + const next = nextSchema.parse(await cli(deferred.length > 0 ? ["next", "--defer", deferred.map(d => `${d.findingId}=${d.fingerprint}`).join(",")] : ["next"])); + authority(principalId); + await write("counts", now(), principalId, next); + } async function ensureNext(principalId?: string, resumeRetired = false) { if (!preparing) preparing = select(principalId, resumeRetired).finally(() => { preparing = null; }); await preparing; @@ -268,6 +275,8 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no await write("mediaUndo", now(), principalId, item.id, journalId, receipt, receipt.outcome === "refused" ? media.receipt(journalId, principalId) : null); // The finding is pending again; an active review with no card selects it in order. if (receipt.outcome === "undone" && state().status === "active" && !state().pendingActionId) await ensureNext(principalId); + // Otherwise nothing selects now, and the stored count must not keep the effect's (#2783). + else if (receipt.outcome === "undone") await recount(principalId); return { ...read(), mediaUndo: receipt }; } /** diff --git a/packages/ui-server/src/inbox/hygiene-writes.ts b/packages/ui-server/src/inbox/hygiene-writes.ts index 3e087c8551..c9fbf7e720 100644 --- a/packages/ui-server/src/inbox/hygiene-writes.ts +++ b/packages/ui-server/src/inbox/hygiene-writes.ts @@ -237,6 +237,20 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP } }).immediate(); }, + /** + * The counts a selection stores, read again without selecting (#2783): an + * Undo while a card is pending, or after the pass ended, puts a finding + * back to awaiting review, so the stored count must say so too. + */ + counts(time: number, principalId: string, next: z.infer) { + at = time; + authority(principalId); + return db.transaction(() => { + if ("blocker" in next) return; + const review = state(); + save({ ...review, counts: next.counts, media: mediaOf(next) ?? review.media }); + }).immediate(); + }, admit(time: number, principalId: string, request: ClientInboxResolve) { at = time; return db.transaction(() => { diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts index d3bb1095b2..bf034b58ac 100644 --- a/packages/ui-server/tests/hygiene-media-effects.test.ts +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -314,6 +314,31 @@ test("undo-media from review undoes a resolved Delete, records the Undo on the c expect(again?.status).toBe("pending"); }); +test("undo-media while another card is pending, or after the pass ended, counts the restored file as awaiting review again (#2783)", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + expect(f.review.read().review.media, "MEDIA_REVIEW_COUNT_BEFORE").toEqual({ awaitingReview: 2, setAside: 0, kept: 0 }); + await resolveWith(f, card.id, "media-delete"); + const second = f.review.read().action!; + expect(f.review.read().review.media).toEqual({ awaitingReview: 1, setAside: 0, kept: 0 }); + const journalId = createInboxStoreRead(f.db, card.id)!.hygiene!.outcome!.media!.journalId; + // The other card stays the pending one, and the count the review shows is the CLI's again. + const undone = await f.review.undoMedia(f.reviewer.id, journalId); + expect(undone.mediaUndo.outcome).toBe("undone"); + expect(undone.action?.id, "MEDIA_REVIEW_UNDO_KEEPS_CARD").toBe(second.id); + expect(undone.review.media, "MEDIA_REVIEW_UNDO_RECOUNTED").toEqual({ awaitingReview: 2, setAside: 0, kept: 0 }); + expect((await f.brain.hygiene!(["next"]) as { media: { awaitingReview: number } }).media.awaitingReview, "MEDIA_REVIEW_UNDO_CLI_COUNT").toBe(2); + // After the pass: deleting the last one ends it, and its Undo is counted although nothing selects. + await resolveWith(f, second.id, "media-delete"); + const third = f.review.read().action!; + await resolveWith(f, third.id, "media-delete"); + expect(f.review.read().review.status).toBe("complete"); + expect(f.review.read().review.media).toEqual({ awaitingReview: 0, setAside: 0, kept: 0 }); + const last = await f.review.undoMedia(f.reviewer.id, createInboxStoreRead(f.db, third.id)!.hygiene!.outcome!.media!.journalId); + expect(last.review.status, "MEDIA_REVIEW_UNDO_PASS_STAYS_COMPLETE").toBe("complete"); + expect(last.review.media, "MEDIA_REVIEW_UNDO_RECOUNTED_COMPLETE").toEqual({ awaitingReview: 1, setAside: 0, kept: 0 }); +}); + test("undo-media refuses before any write when a file changed since, and the card shows why", async () => { const f = await setup(); const card = await reviewWithTwo(f); From 8f4490cd466e07f8d953297a0d7eea5459f3ea7c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:28:44 +0000 Subject: [PATCH 02/11] test(ui-server): verify media hygiene review end to end across the CLI, sync and a restartable server An Odysseus brain with a bare remote, the real offline CLI and brain sync, and the real review server as its own process: decisions go over its socket, and it is stopped, killed and booted again on the same state. Each of the five actions is applied, its file, config, reference, pin and kept-log bytes read, undone and read again, and applied again before an ordinary sync commits it. The CLI, sync and the server agree on count and selection at every step. Capacity, stale-premise, interruption, disposition/count and isolation each have a scenario whose guard, when broken, fails it (#2783). Co-Authored-By: Claude Opus 5.5 --- .../tests/fixtures/media-flow-server.ts | 117 ++++++ .../ui-server/tests/helpers/media-flow.ts | 261 ++++++++++++ .../ui-server/tests/media-review-flow.test.ts | 393 ++++++++++++++++++ 3 files changed, 771 insertions(+) create mode 100644 packages/ui-server/tests/fixtures/media-flow-server.ts create mode 100644 packages/ui-server/tests/helpers/media-flow.ts create mode 100644 packages/ui-server/tests/media-review-flow.test.ts diff --git a/packages/ui-server/tests/fixtures/media-flow-server.ts b/packages/ui-server/tests/fixtures/media-flow-server.ts new file mode 100644 index 0000000000..f1ec3efed2 --- /dev/null +++ b/packages/ui-server/tests/fixtures/media-flow-server.ts @@ -0,0 +1,117 @@ +/** + * The media review flow's server (#2783): the real brain client and core CLI, + * hygiene review coordinator, journal-backed media effects under the real + * writer gate and change journal, inbox store and stream, review and files + * routes, on loopback. Nothing is canned. `tests/helpers/media-flow.ts` boots + * it on one state directory, and stops, kills and boots it again there. + * + * argv: + * + * Test-only seams, each named by the parent: a principal per request + * (`x-media-flow-principal` or `?as=` on the socket: the owner Odysseus, a + * second owner device, a delegated agent), and `interrupt.txt`, which stops + * this process dead at one CLI step of a media effect so the parent can kill + * it there. The change journal's native checkpoints use the test-only copied + * fixture, as in the media effects suite. + */ +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { Hono } from "hono"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { createUiDb } from "../../src/db/client.js"; +import { createPrincipal } from "../../src/db/principals.js"; +import { createBrainClient } from "../../src/brain/client.js"; +import { createHostBoundary } from "../../src/brain/host-boundary.js"; +import { createTurnJournal } from "../../src/brain/turn-journal.js"; +import { createWriterGate } from "../../src/brain/writer-gate.js"; +import { createMediaEffects } from "../../src/inbox/media-effects.js"; +import { createHygieneReview } from "../../src/inbox/hygiene-review.js"; +import { createHygieneReviewRoutes } from "../../src/routes/hygiene-review.js"; +import { createFilesRoutes } from "../../src/routes/files.js"; +import { createInboxStore } from "../../src/inbox/store.js"; +import { createInboxStream } from "../../src/inbox/stream.js"; +import type { AppEnv } from "../../src/app-env.js"; +import { createNativeJournalFixture } from "../helpers/native-journal-fixture.js"; + +const [brainPath, state, port, cap] = process.argv.slice(2) as [string, string, string, string]; +const dbPath = join(state, "ui.sqlite"); +const db = createUiDb(dbPath); +const principalsFile = join(state, "principals.json"); +type Principals = { owner: string; penelope: string; agent: string }; +const principals: Principals = existsSync(principalsFile) ? JSON.parse(readFileSync(principalsFile, "utf8")) : (() => { + const owner = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 86400 }); + const penelope = createPrincipal(db, { authMethod: "password", label: "Penelope tablet", ttlSeconds: 86400 }); + const agent = createPrincipal(db, { authMethod: "delegated", label: "Telemachus research", createdBy: owner.id, ttlSeconds: 86400 }); + const ids = { owner: owner.id, penelope: penelope.id, agent: agent.id }; + writeFileSync(principalsFile, JSON.stringify(ids)); + return ids; +})(); +const principalOf = (as: string | null | undefined) => principals[(as ?? "owner") as keyof Principals] ?? principals.owner; + +const native = createNativeJournalFixture(brainPath, state); +const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath, dbPath, objectsRoot: join(state, "objects"), ...(Number(cap) > 0 ? { capBytes: Number(cap) } : {}) }); +await journal.ready; +const gate = createWriterGate(db, brainPath); +// The brain client the app builds, on a host without a qualified worker: the +// CLI runs as a host process under the same gates. The hosted native proof +// runs this flow's effects inside real maintenance workers instead. +const boundary = createHostBoundary({ brainPath, exec: {}, dbPath, workerHost: () => ({ ok: false, requirement: "the media flow fixture runs the CLI on the host" }) }); +const brain = createBrainClient({ brainPath, exec: {}, boundary }); + +/** Stop dead at `interrupt.txt`'s CLI step, before (`keep-copy`) or after (`media`) it runs. */ +const interrupt = existsSync(join(state, "interrupt.txt")) ? readFileSync(join(state, "interrupt.txt"), "utf8").trim() : ""; +function halt(): never { + writeFileSync(join(state, "interrupted.flag"), "interrupted"); + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0); + throw new Error("unreachable"); +} +async function hygiene(args: string[]) { + const applying = args[0] === interrupt && !args.includes("--dry-run"); + if (applying && interrupt === "keep-copy") halt(); + const result = await brain.hygiene!(args); + if (applying && interrupt === "media") halt(); + return result; +} +const media = createMediaEffects(db, { brainPath, journal, gate, lock: createKeyedLock(), cli: hygiene, + authorized: id => id === principals.owner || id === principals.penelope }); +const review = createHygieneReview(db, { brain, media }); +// As the app does at boot: an interrupted effect is compensated before anything else runs. +await review.recover(); + +const store = createInboxStore(db), stream = createInboxStream(store, db, undefined, review.resolver); +const app = new Hono(); +app.use("*", async (c, next) => { c.set("principal", { id: principalOf(c.req.header("x-media-flow-principal")) } as never); await next(); }); +app.route("/api", createHygieneReviewRoutes(review)); +app.route("/api", createFilesRoutes({ brainRoot: brainPath })); +const auth = (principalId: string) => ({ principalId, expiresAt: Number.MAX_SAFE_INTEGER, valid: true, retain: () => () => {}, release() {} }); + +const server = Bun.serve<{ principalId: string }, never>({ + hostname: "127.0.0.1", port: Number(port), + fetch(req, s) { + const url = new URL(req.url); + if (url.pathname === "/ws" && s.upgrade(req, { data: { principalId: principalOf(url.searchParams.get("as")) } })) return; + return app.fetch(req); + }, + websocket: { + open(ws) { ws.send(JSON.stringify({ type: "server_hello", protocolRev: 2, capabilities: { inbox: true } })); }, + message(ws, raw) { + const parsed = parseClientMessage(String(raw)); + if (!parsed.ok) throw new Error(parsed.error); + const msg = parsed.message, ctx = { raw: ws, send: (s: string) => ws.send(s), close: () => ws.close() }; + if (msg.type === "inbox_subscribe") stream.handleSubscribe(ctx as never, msg, auth(ws.data.principalId) as never); + else if (msg.type === "inbox_unsubscribe") stream.handleUnsubscribe(ctx as never, msg); + else if (msg.type === "inbox_resolve" || msg.type === "inbox_snooze") void stream.handleDecision!(ctx as never, msg, auth(ws.data.principalId) as never); + }, + close(ws) { stream.dropConnection({ raw: ws } as never); }, + }, +}); +console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}`, principals })); +process.on("SIGTERM", async () => { + stream.close(); + server.stop(true); + await journal.close(); + await native.close(); + db.close(); + process.exit(0); +}); diff --git a/packages/ui-server/tests/helpers/media-flow.ts b/packages/ui-server/tests/helpers/media-flow.ts new file mode 100644 index 0000000000..6d5b408235 --- /dev/null +++ b/packages/ui-server/tests/helpers/media-flow.ts @@ -0,0 +1,261 @@ +/** + * The integrated media review flow (#2783, epic #1777): one Odysseus brain + * with a bare remote, the real offline core CLI, and the real review server + * (`tests/fixtures/media-flow-server.ts`) as a child process that can be + * stopped, killed and booted again on the same SQLite, journal and Markdown + * state. Shared by the Bun suite and the browser fixture. Nothing reaches the + * network: Git talks to a local bare repository, and the server listens on + * loopback only. + */ +import { spawn, type ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { deflateSync } from "node:zlib"; + +const REPO = resolve(import.meta.dir, "../../../.."); +const CORE_CLI = join(REPO, "packages/core/src/cli/brain.ts"); +const SERVER = join(REPO, "packages/ui-server/tests/fixtures/media-flow-server.ts"); +const PRELOAD = join(REPO, "scripts/test-network-child-preload.ts"); + +/** Odysseus's media: what each file is for in the flow. */ +export const LOOM = "photos/penelope-loom.png"; +export const SHIELD = "photos/achilles-shield.png"; +export const SKETCH = "inbox/cyclops-sketch.png"; +export const ARGUS = "photos/argus-waiting.png"; +export const HARBOUR = ".brain/scratch/2026-07-12/harbour-dawn.png"; +export const NOTE = "notes/the-return.md"; +export const CONFIG = "brain.config.json"; +export const PINS = ".brain/scratch-pins/pins.json"; +export const KEPT = "context/hygiene/kept.md"; +/** Where Move and Keep a permanent copy put their files. */ +export const LOOM_TO = "places/ithaca/penelope-loom.png"; +export const HARBOUR_TO = "places/ithaca/harbour-dawn.png"; +/** The counted content media; the pinned scratch file is review-only. */ +export const COUNTED = [LOOM, SHIELD, SKETCH, ARGUS] as const; + +export const CONFIG_TEXT = '{ "media": { "ignore": [".brain/scratch/**"] } }\n'; +/** + * Notes are edited today, so a Move's rewrite of one is never a silent edit + * that review would select before the media; they were written on Odysseus's + * date. + */ +const TODAY = (() => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; })(); +export const NOTE_TEXT = "---\ntitle: The return\ntype: note\ncreated: 2026-07-12\nupdated: " + TODAY + "\ntags: [voyage]\n---\n# The return\n\nPenelope's loom, as she left it:\n\n![loom](../photos/penelope-loom.png)\n"; +export const PINS_TEXT = JSON.stringify({ version: 1, ready: true, sessions: { [JSON.stringify(["pi", "voyage-home"])]: [HARBOUR] } }); + +const CRC = Uint32Array.from({ length: 256 }, (_, n) => { for (let k = 0; k < 8; k++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1; return n >>> 0; }); +function chunk(type: string, data: Buffer) { + const body = Buffer.concat([Buffer.from(type, "latin1"), data]); + let c = 0xffffffff; for (const b of body) c = CRC[(c ^ b) & 255]! ^ (c >>> 8); + const out = Buffer.alloc(12 + data.length); out.writeUInt32BE(data.length, 0); body.copy(out, 4); out.writeUInt32BE((c ^ 0xffffffff) >>> 0, 8 + data.length); + return out; +} +/** A valid one-colour PNG, so each file has its own bytes and the browser can render it. */ +export function png(width: number, height: number, rgb: [number, number, number]): Buffer { + const header = Buffer.alloc(13); header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4); header.set([8, 2, 0, 0, 0], 8); + const row = Buffer.concat([Buffer.from([0]), Buffer.from(Array.from({ length: width }, () => rgb).flat())]); + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(Buffer.concat(Array.from({ length: height }, () => row)))), chunk("IEND", Buffer.alloc(0))]); +} +/** A PNG of seeded noise: deflate cannot shrink it, so its bytes are about `side² × 3`. */ +export function noisePng(side: number, seed = 12): Buffer { + let x = seed >>> 0; + const header = Buffer.alloc(13); header.writeUInt32BE(side, 0); header.writeUInt32BE(side, 4); header.set([8, 2, 0, 0, 0], 8); + const raw = Buffer.alloc(side * (side * 3 + 1)); + for (let i = 0; i < raw.length; i++) { x = (Math.imul(x, 1664525) + 1013904223) >>> 0; raw[i] = i % (side * 3 + 1) === 0 ? 0 : x >>> 24; } + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 0 })), chunk("IEND", Buffer.alloc(0))]); +} +export const MEDIA_BYTES: Record = { + [LOOM]: png(24, 16, [176, 112, 64]), + [SHIELD]: png(20, 20, [200, 168, 40]), + [SKETCH]: png(16, 12, [96, 96, 96]), + [ARGUS]: png(18, 12, [120, 80, 48]), + [HARBOUR]: png(32, 18, [40, 96, 160]), +}; +export const sha = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex"); + +export function git(cwd: string, ...args: string[]): string { + const r = Bun.spawnSync(["git", "-C", cwd, ...args], { env: gitEnv(cwd) }); + if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`); + return r.stdout.toString().trim(); +} +function gitEnv(home: string) { return { PATH: process.env.PATH ?? "", HOME: home, GIT_CONFIG_NOSYSTEM: "1" }; } +function put(root: string, path: string, bytes: string | Buffer) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), bytes); } + +export interface Parity { + /** `brain sync --json` in the brain: the count it reports and its one media line. */ + sync: { pending: number; setAside: { dismissed: number; snoozed: number; kept: number }; report: string; agent: unknown; status: string } | null; + /** The server's review read: its media counts, pending card and deferrals. */ + server: { media: { awaitingReview: number; setAside: number; kept: number } | null; status: string; findingId: string | null; path: string | null; deferred: string[] }; + /** `brain hygiene next`, with the server's deferrals: the CLI's selection and counts. */ + cli: { media: { awaitingReview: number; setAside: number; kept: number }; findingId: string | null; path: string | null }; + /** Whether the CLI finds the server's pending card's finding eligible, at its fingerprint. */ + eligible: boolean | null; +} + +export type Principal = "owner" | "penelope" | "agent"; + +/** One flow: its brain, remote and server state, removed by `close()`. */ +export function createMediaFlow(options: { directory?: string; media?: readonly string[]; config?: string; bytes?: Record } = {}) { + const directory = options.directory ?? mkdtempSync(join(tmpdir(), "brain-media-flow-")); + const root = join(directory, "brain"), remote = join(directory, "remote.git"), state = join(directory, "server"); + mkdirSync(root); mkdirSync(state); + Bun.spawnSync(["git", "init", "-q", "--bare", "-b", "main", remote], { env: gitEnv(directory) }); + git(root, "init", "-q", "-b", "main"); + for (const [k, v] of [["user.name", "Odysseus"], ["user.email", "odysseus@example.test"], ["commit.gpgsign", "false"]]) git(root, "config", k!, v!); + put(root, ".gitignore", ".brain/\nbrain.db\nbrain.db-*\n.brain-index/\nnode_modules\n"); + put(root, CONFIG, options.config ?? CONFIG_TEXT); + // The vendored CLI entry the server's brain client runs (`scripts/brain-cli.ts`). + put(root, "scripts/brain-cli.ts", `await import(${JSON.stringify(CORE_CLI)});\n`); + put(root, "notes/ithaca.md", "---\ntitle: Ithaca\ntype: note\ncreated: 2026-07-12\nupdated: " + TODAY + "\ntags: [voyage]\n---\n# Ithaca\n\nThe island Odysseus sails home to.\n"); + put(root, NOTE, NOTE_TEXT); + git(root, "add", "-A"); git(root, "commit", "-qm", "Odysseus's brain"); + git(root, "remote", "add", "origin", remote); git(root, "push", "-q", "-u", "origin", "main"); + const present = options.media ?? Object.keys(MEDIA_BYTES); + for (const path of present) put(root, path, options.bytes?.[path] ?? MEDIA_BYTES[path]!); + // The conversation that linked the scratch file pins it; the pins exist with or without it. + put(root, PINS, PINS_TEXT); + + let child: ChildProcess | undefined, url = "", stderr = ""; + const home = join(directory, "home"); mkdirSync(home); + const env = { PATH: process.env.PATH ?? "", HOME: home, BRAIN_ROOT: root, GIT_CONFIG_NOSYSTEM: "1", TMPDIR: process.env.TMPDIR ?? tmpdir() }; + + function cliRun(args: string[]) { + const r = Bun.spawnSync([process.execPath, "--preload", PRELOAD, CORE_CLI, ...args], { cwd: root, env }); + return { code: r.exitCode ?? -1, stdout: r.stdout.toString(), stderr: r.stderr.toString() }; + } + /** The real offline CLI; exits 0 and 1 carry JSON. */ + function cli(...args: string[]): any { + const r = cliRun(args); + if (![0, 1].includes(r.code)) throw new Error(`brain ${args.join(" ")} exited ${r.code}: ${r.stderr}`); + return JSON.parse(r.stdout); + } + /** One ordinary `brain sync`, as a person or cron runs it. */ + function sync(): any { return cli("sync", "--json"); } + + async function boot(boot: { port?: number; capBytes?: number; interrupt?: string } = {}) { + if (child) throw new Error("server already running"); + if (boot.interrupt) writeFileSync(join(state, "interrupt.txt"), boot.interrupt); else rmSync(join(state, "interrupt.txt"), { force: true }); + rmSync(join(state, "interrupted.flag"), { force: true }); + stderr = ""; + const proc = spawn(process.execPath, ["--preload", PRELOAD, SERVER, root, state, String(boot.port ?? 0), String(boot.capBytes ?? 0)], { cwd: REPO, env, stdio: ["ignore", "pipe", "pipe"] }); + child = proc; + proc.stderr!.on("data", b => { stderr += String(b); }); + url = await new Promise((res, reject) => { + let out = ""; + const timer = setTimeout(() => { proc.kill("SIGKILL"); reject(new Error(`media flow server did not start: ${stderr}`)); }, 20_000); + proc.once("exit", code => { clearTimeout(timer); reject(new Error(`media flow server exited ${code}: ${stderr}`)); }); + proc.stdout!.on("data", b => { out += String(b); if (out.includes("\n")) { clearTimeout(timer); try { res(JSON.parse(out.split("\n")[0]!).url); } catch (e) { reject(e); } } }); + }); + return url; + } + /** SIGTERM: the server closes its stream, journal and database. */ + async function stop() { + const proc = child; child = undefined; + if (!proc || proc.exitCode !== null) return; + const ended = once(proc, "exit"); proc.kill("SIGTERM"); const [code] = await ended; + if (code !== 0) throw new Error(`media flow server stopped with ${code}: ${stderr}`); + } + /** SIGKILL: as if the host died, with nothing closed or committed. */ + async function kill() { + const proc = child; child = undefined; + if (!proc || proc.exitCode !== null) return; + const ended = once(proc, "exit"); proc.kill("SIGKILL"); await ended; + } + const headers = (as: Principal) => ({ "content-type": "application/json", "x-media-flow-principal": as }); + async function request(path: string, init: { method?: string; body?: unknown; as?: Principal } = {}) { + const r = await fetch(`${url}${path}`, { method: init.method ?? (init.body === undefined ? "GET" : "POST"), headers: headers(init.as ?? "owner"), ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}) }); + const text = await r.text(); + return { status: r.status, body: text ? JSON.parse(text) : null }; + } + const read = async (as: Principal = "owner") => (await request("/api/hygiene/review", { as })).body; + const command = (operation: string, as: Principal = "owner") => request("/api/hygiene/review", { body: { operation }, as }); + const preview = (body: { itemId: string; optionId: string; expectedVersion: number; input: unknown; requestId?: string }, as: Principal = "owner") => request("/api/hygiene/review/preview", { body, as }); + const undo = (journalId: string, as: Principal = "owner") => request("/api/hygiene/review", { body: { operation: "undo-media", journalId }, as }); + + /** One device on the review's socket: decisions go out as `inbox_resolve`, as from the browser. */ + async function device(as: Principal = "owner") { + const frames: any[] = []; + const ws = new WebSocket(`${url.replace("http:", "ws:")}/ws?as=${as}`); + ws.addEventListener("message", e => frames.push(JSON.parse(String(e.data)))); + await new Promise((res, reject) => { ws.addEventListener("open", () => res()); ws.addEventListener("error", () => reject(new Error("socket failed"))); }); + ws.send(JSON.stringify({ type: "inbox_subscribe", view: "actions" })); + return { + frames, ws, + resolve(itemId: string, optionId: string, extra: Record = {}) { + ws.send(JSON.stringify({ type: "inbox_resolve", itemId, optionId, ...extra })); + }, + /** The latest replicated state of one item, as this device's stream holds it. */ + item(id: string): any { + let latest: any = null; + for (const f of frames) { + if (f.type === "inbox_snapshot") latest = f.items.find((i: any) => i.id === id) ?? latest; + if (f.type === "inbox_delta" && f.change.kind === "upsert_item" && f.change.itemId === id) latest = f.change.item; + } + return latest; + }, + async close() { if (ws.readyState === WebSocket.OPEN) { const closed = new Promise(r => ws.addEventListener("close", r)); ws.close(); await closed; } }, + }; + } + + /** Wait until the review read satisfies `check`; the review settles after the socket acknowledges. */ + async function until(check: (read: any) => boolean, what: string, deadlineMs = 20_000) { + const end = Date.now() + deadlineMs; + let last: any; + while (Date.now() < end) { + last = await read(); + if (check(last)) return last; + await Bun.sleep(25); + } + throw new Error(`media flow: ${what} never held; last read ${JSON.stringify(last).slice(0, 2000)}`); + } + + /** + * Count and selection from the server and the offline CLI, at one instant. + * With `sync`, an ordinary `brain sync` runs too, and commits and pushes + * whatever the brain's rules track: use it where the flow has settled. + */ + async function parity(options: { sync?: boolean } = {}): Promise { + const r = await read(); + const deferred = (r.review.deferred ?? []) as Array<{ findingId: string; fingerprint: string }>; + const next = cli("hygiene", "--json", "next", ...(deferred.length ? ["--defer", deferred.map(d => `${d.findingId}=${d.fingerprint}`).join(",")] : [])); + const synced = options.sync === false ? null : sync(); + const finding = r.action?.status === "pending" ? r.action.hygiene.finding : null; + const selected = finding ? cli("hygiene", "--json", "next", "--finding", finding.id, "--dry-run") : null; + return { + eligible: selected ? selected.finding?.id === finding.id && selected.finding.fingerprint === finding.fingerprint : null, + sync: synced ? { pending: synced.run.leftovers.mediaPending, setAside: synced.run.leftovers.mediaSetAside, report: synced.run.report, agent: synced.agent, status: synced.run.status } : null, + server: { media: r.review.media ?? null, status: r.review.status, findingId: finding?.id ?? null, path: finding?.path ?? null, deferred: deferred.map(d => d.findingId) }, + cli: { media: { awaitingReview: next.media.awaitingReview, setAside: next.media.setAside, kept: next.media.kept }, findingId: next.finding?.id ?? null, path: next.finding?.path ?? null }, + }; + } + + /** Every byte the flow can change: media, config, the referencing note, pins and the kept log. */ + function bytes(): Record { + const out: Record = {}; + for (const path of [...Object.keys(MEDIA_BYTES), LOOM_TO, HARBOUR_TO, CONFIG, NOTE, PINS, KEPT]) + out[path] = existsSync(join(root, path)) ? sha(readFileSync(join(root, path))) : null; + return out; + } + const text = (path: string) => existsSync(join(root, path)) ? readFileSync(join(root, path), "utf8") : null; + /** What Git holds on the remote's main after a sync pushed. */ + const remoteFiles = () => git(root, "ls-tree", "-r", "--name-only", "origin/main").split("\n").filter(Boolean); + const interrupted = () => existsSync(join(state, "interrupted.flag")); + + async function close() { + await kill(); + rmSync(directory, { recursive: true, force: true }); + } + return { directory, root, remote, state, get url() { return url; }, get stderr() { return stderr; }, + cli, cliRun, sync, git: (...args: string[]) => git(root, ...args), boot, stop, kill, request, read, command, preview, undo, device, until, parity, bytes, text, remoteFiles, interrupted, close }; +} +export type MediaFlow = ReturnType; + +/** The bytes the flow starts with, by path; files the flow creates start absent. */ +export function initialBytes(media: readonly string[] = Object.keys(MEDIA_BYTES)): Record { + const out: Record = {}; + for (const [path, bytes] of Object.entries(MEDIA_BYTES)) out[path] = media.includes(path) ? sha(bytes) : null; + return { ...out, [LOOM_TO]: null, [HARBOUR_TO]: null, [CONFIG]: sha(CONFIG_TEXT), [NOTE]: sha(NOTE_TEXT), [PINS]: sha(PINS_TEXT), [KEPT]: null }; +} diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts new file mode 100644 index 0000000000..40014e2d15 --- /dev/null +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -0,0 +1,393 @@ +/** + * Media hygiene review end to end (#2783, epic #1777; design rev 4 §10, + * rev 5 §12, rev 6 §6, rev 6.1 §3). One Odysseus brain with a bare remote, + * the real offline CLI and `brain sync`, and the real review server as a + * separate process (`helpers/media-flow.ts`): decisions go over its socket as + * the browser sends them, and the server is stopped, killed and booted again + * on the same state. Every step reads the actual file, config, reference, + * pin and kept-log bytes, and holds the CLI and the server to the same count + * and the same selection. Offline and keyless. + */ +import { afterEach, expect, test } from "bun:test"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + ARGUS, CONFIG, CONFIG_TEXT, COUNTED, HARBOUR, HARBOUR_TO, KEPT, LOOM, LOOM_TO, MEDIA_BYTES, NOTE, NOTE_TEXT, PINS, PINS_TEXT, SHIELD, SKETCH, + createMediaFlow, initialBytes, noisePng, sha, type MediaFlow, type Parity, +} from "./helpers/media-flow.js"; + +const flows: MediaFlow[] = []; +afterEach(async () => { for (const f of flows.splice(0)) await f.close(); }); +async function flow(media?: readonly string[], boot: Parameters[0] = {}, config?: string, bytes?: Record) { + const f = createMediaFlow({ media, config, bytes }); flows.push(f); + await f.boot(boot); + return f; +} + +type Want = { pending: number; dismissed?: number; snoozed?: number; kept?: number }; +/** + * The CLI and the server report one count, one set-aside split and one + * selection; a sync's report names the count and never a media path. + */ +function agree(p: Parity, want: Want, selection: "selected" | "kept" = "selected") { + const setAside = { dismissed: want.dismissed ?? 0, snoozed: want.snoozed ?? 0, kept: want.kept ?? 0 }; + expect(p.server.media, "MEDIA_FLOW_SERVER_COUNT").toEqual({ awaitingReview: want.pending, setAside: setAside.dismissed + setAside.snoozed, kept: setAside.kept }); + expect(p.cli.media, "MEDIA_FLOW_CLI_COUNT").toEqual(p.server.media!); + // Right after the server selects, it selects what the CLI selects. A card an + // Undo did not replace stays the server's selection, and must still be eligible. + if (selection === "selected") expect(p.cli.findingId, "MEDIA_FLOW_SELECTION").toBe(p.server.findingId); + // A finished pass selects nothing until the next one starts. + else if (p.server.status === "complete") expect(p.server.findingId, "MEDIA_FLOW_SELECTION_COMPLETE").toBeNull(); + else expect(p.eligible, "MEDIA_FLOW_SELECTION_ELIGIBLE").toBe(true); + if (!p.sync) return; + expect({ pending: p.sync.pending, setAside: p.sync.setAside }, "MEDIA_FLOW_SYNC_COUNT").toEqual({ pending: want.pending, setAside }); + expect(p.sync.agent, "MEDIA_FLOW_SYNC_NO_AGENT").toEqual({ invoked: false, reason: "not-needed" }); + const line = p.sync.report.split("\n").find(l => l.startsWith("Media awaiting review:")); + if (want.pending + setAside.dismissed + setAside.snoozed + setAside.kept === 0) expect(line, "MEDIA_FLOW_REPORT_LINE").toBeUndefined(); + else expect(line, "MEDIA_FLOW_REPORT_LINE").toBe([`Media awaiting review: ${want.pending}`, + ...(setAside.dismissed + setAside.snoozed ? [`${setAside.dismissed + setAside.snoozed} set aside`] : []), + ...(setAside.kept ? [`${setAside.kept} kept as a copy`] : []), ...(want.pending ? ["review in Actions"] : [])].join(" · ")); + for (const path of [...Object.keys(MEDIA_BYTES), "photos/", "inbox/", ".brain/"]) expect(p.sync.report, "MEDIA_FLOW_REPORT_NO_PATH").not.toContain(path); +} + +/** The pending card, which must be the media finding at `path`. */ +async function cardFor(f: MediaFlow, path: string) { + const r = await f.until(read => read.action?.status === "pending", "a pending card"); + expect(r.action.hygiene.finding.path, "MEDIA_FLOW_CARD").toBe(path); + expect(r.action.hygiene.finding.category).toBe("media"); + return r.action; +} +/** Wait until the server has finished the decision on `cardId` and settled its next selection. */ +const settled = (f: MediaFlow, cardId: string) => f.until(r => r.action?.id !== cardId && (r.review.status !== "active" || r.action?.status === "pending"), `card ${cardId} settled`); +/** + * Leave pending every card until the one at `path`, as a person working + * through review does, starting the next pass when this one has finished. + */ +async function reach(f: MediaFlow, device: Awaited>, path: string) { + for (let i = 0; i < 2 * (COUNTED.length + 1); i++) { + if ((await f.read()).review.status === "complete") expect((await f.command("start")).status).toBe(200); + const r = await f.until(read => read.action?.status === "pending", "a pending card"); + if (r.action.hygiene.finding.path === path) return r.action; + device.resolve(r.action.id, "leave-pending"); + await settled(f, r.action.id); + } + throw new Error(`review never selected ${path}`); +} +/** Preview a destination for Move or Keep a permanent copy, as the card's input does. */ +async function destination(f: MediaFlow, card: any, optionId: string, to: string) { + const previewed = await f.preview({ itemId: card.id, optionId, expectedVersion: card.version, input: to }); + expect(previewed.status).toBe(200); + expect(previewed.body.refusals, "MEDIA_FLOW_PREVIEW_REFUSALS").toEqual([]); + return previewed.body; +} +const receiptOf = async (f: MediaFlow, device: Awaited>, cardId: string) => { + const end = Date.now() + 10_000; + while (Date.now() < end) { + const item = device.item(cardId); + if (item?.status === "resolved" && item.hygiene?.outcome) return item.hygiene.outcome; + await Bun.sleep(25); + } + throw new Error(`no receipt replicated for ${cardId}`); +}; + +test("sync reports only the count, and review selects each media finding the CLI selects, with the same count", async () => { + const f = await flow(); + const before = f.bytes(); + expect(before, "MEDIA_FLOW_FIXTURE_BYTES").toEqual(initialBytes()); + // Before any review: the offline sync and the CLI count the four content files, never the pinned scratch. + const first = f.sync(); + expect(first.run.leftovers.mediaPending).toBe(COUNTED.length); + expect(first.run.report.split("\n").at(-1), "MEDIA_FLOW_COUNT_ONLY").toBe("Media awaiting review: 4 · review in Actions"); + expect(first.agent).toEqual({ invoked: false, reason: "not-needed" }); + await f.command("start"); + const device = await f.device(); + const seen: string[] = []; + // Every media finding is selected once a pass, each where the CLI selects it, and each stays counted. + for (let i = 0; i < COUNTED.length + 1; i++) { + const p = await f.parity({ sync: i === 0 }); + agree(p, { pending: COUNTED.length }); + expect(p.server.path).not.toBeNull(); + seen.push(p.server.path!); + const id = (await f.read()).action.id; + device.resolve(id, "leave-pending"); + if ((await settled(f, id)).review.status === "complete") break; + } + expect([...seen].sort(), "MEDIA_FLOW_EVERY_FINDING").toEqual([...COUNTED, HARBOUR].sort()); + // Leave pending wrote nothing: every byte is the fixture's. + expect(f.bytes(), "MEDIA_FLOW_LEAVE_PENDING_NO_WRITE").toEqual(before); + agree(await f.parity(), { pending: COUNTED.length }); + await device.close(); +}); + +/** + * One action through review: apply it, read every byte, Undo it and read + * them again, then apply it again on the successor card and let an ordinary + * sync commit and push the result. `expectApplied` names the bytes after. + */ +async function actionRoundTrip(f: MediaFlow, path: string, optionId: string, to: string | undefined, expectApplied: (bytes: Record) => void, want: { applied: Want; initial: Want }) { + const device = await f.device(); + await f.command("start"); + const initial = f.bytes(); + let card = await reach(f, device, path); + agree(await f.parity({ sync: true }), want.initial); + if (to) await destination(f, card, optionId, to); + device.resolve(card.id, optionId); + const receipt = await receiptOf(f, device, card.id); + expect(receipt.media, "MEDIA_FLOW_APPLIED").toMatchObject({ outcome: optionId === "media-keep-copy" ? "kept" : "applied", undo: { available: true } }); + await settled(f, card.id); + expectApplied(f.bytes()); + agree(await f.parity({ sync: false }), want.applied); + + // Undo puts back every byte the effect wrote, and the finding is pending again. + const undone = await f.undo(receipt.media.journalId); + expect(undone.status).toBe(200); + expect(undone.body.mediaUndo, "MEDIA_FLOW_UNDONE").toMatchObject({ outcome: "undone" }); + // Undo of a kept copy leaves the kept log without its entry (rev 5 §5.7). + const keptLog = f.text(KEPT); + expect({ ...f.bytes(), [KEPT]: initial[KEPT] }, "MEDIA_FLOW_UNDO_BYTES").toEqual(initial); + if (initial[KEPT] === null && keptLog !== null) expect(keptLog, "MEDIA_FLOW_UNDO_KEPT_ENTRY").not.toContain("### media-"); + else expect(f.bytes()[KEPT]).toBe(initial[KEPT]!); + // A sync after Undo commits none of it. + const p = await f.parity({ sync: true }); + agree(p, want.initial, "kept"); + for (const file of [path, ...(to ? [to] : [])]) expect(f.remoteFiles(), "MEDIA_FLOW_UNDO_NOT_COMMITTED").not.toContain(file); + + // Apply again, from the card review selects for the restored finding. + card = await reach(f, device, path); + if (to) await destination(f, card, optionId, to); + device.resolve(card.id, optionId); + expect((await receiptOf(f, device, card.id)).media.outcome).toBe(optionId === "media-keep-copy" ? "kept" : "applied"); + await settled(f, card.id); + expectApplied(f.bytes()); + agree(await f.parity({ sync: true }), want.applied); + await device.close(); + return f.remoteFiles(); +} + +test("Persist here: the config tracks exactly the file, Undo restores its bytes, and the next sync commits the file and the rule", async () => { + const f = await flow([SHIELD, ARGUS]); + const tracked = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["photos/achilles-shield.png"] } }\n'; + const remote = await actionRoundTrip(f, SHIELD, "media-persist", undefined, bytes => { + expect(bytes[CONFIG], "MEDIA_FLOW_PERSIST_CONFIG").toBe(sha(tracked)); + expect(bytes[SHIELD], "MEDIA_FLOW_PERSIST_FILE").toBe(sha(MEDIA_BYTES[SHIELD]!)); + }, { initial: { pending: 2 }, applied: { pending: 1 } }); + expect(remote, "MEDIA_FLOW_PERSIST_COMMITTED").toEqual(expect.arrayContaining([SHIELD, CONFIG])); + expect(remote).not.toContain(ARGUS); + expect(f.git("show", `origin/main:${CONFIG}`)).toBe(tracked.trimEnd()); +}); + +test("Move into a tracked folder: the file and its reference move together, Undo restores both, and the next sync commits the moved file and the note", async () => { + // Move adds no rule: the destination is final because the brain already tracks it. + const config = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/**"] } }\n'; + const f = await flow([LOOM, ARGUS], {}, config); + const moved = NOTE_TEXT.replace("../photos/penelope-loom.png", "../places/ithaca/penelope-loom.png"); + const remote = await actionRoundTrip(f, LOOM, "media-move", LOOM_TO, bytes => { + expect(bytes[LOOM], "MEDIA_FLOW_MOVE_SOURCE").toBeNull(); + expect(bytes[LOOM_TO], "MEDIA_FLOW_MOVE_DESTINATION").toBe(sha(MEDIA_BYTES[LOOM]!)); + expect(bytes[NOTE], "MEDIA_FLOW_MOVE_REFERENCE").toBe(sha(moved)); + expect(bytes[CONFIG], "MEDIA_FLOW_MOVE_CONFIG").toBe(sha(config)); + }, { initial: { pending: 2 }, applied: { pending: 1 } }); + expect(remote, "MEDIA_FLOW_MOVE_COMMITTED").toEqual(expect.arrayContaining([LOOM_TO, NOTE])); + expect(remote).not.toContain(LOOM); + expect(f.git("show", `origin/main:${NOTE}`) + "\n").toBe(moved); +}); + +test("Delete: the file goes, Undo restores its exact bytes, and the next sync has one file fewer to count and nothing to commit for it", async () => { + const f = await flow([SKETCH, ARGUS]); + const remote = await actionRoundTrip(f, SKETCH, "media-delete", undefined, bytes => { + expect(bytes[SKETCH], "MEDIA_FLOW_DELETE_FILE").toBeNull(); + expect(bytes[CONFIG], "MEDIA_FLOW_DELETE_CONFIG").toBe(sha(CONFIG_TEXT)); + }, { initial: { pending: 2 }, applied: { pending: 1 } }); + expect(remote).not.toContain(SKETCH); +}); + +test("Keep a permanent copy of linked, normally ignored scratch: the original, its pins and link stay, Undo removes the copy, rule and kept entry, and the next sync commits only the copy", async () => { + const f = await flow([HARBOUR, ARGUS]); + const tracked = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/ithaca/harbour-dawn.png"] } }\n'; + const remote = await actionRoundTrip(f, HARBOUR, "media-keep-copy", HARBOUR_TO, bytes => { + expect(bytes[HARBOUR], "MEDIA_FLOW_KEEP_ORIGINAL").toBe(sha(MEDIA_BYTES[HARBOUR]!)); + expect(bytes[HARBOUR_TO], "MEDIA_FLOW_KEEP_COPY").toBe(sha(MEDIA_BYTES[HARBOUR]!)); + expect(bytes[PINS], "MEDIA_FLOW_KEEP_PINS").toBe(sha(PINS_TEXT)); + expect(bytes[CONFIG], "MEDIA_FLOW_KEEP_CONFIG").toBe(sha(tracked)); + expect(f.text(KEPT), "MEDIA_FLOW_KEEP_ENTRY").toContain(`- copy: \`${HARBOUR_TO}\`\n- copy-sha256: ${sha(MEDIA_BYTES[HARBOUR]!)}\n`); + // Pinned scratch is review-only (#2780 ruling): its copy never enters the routine count. + }, { initial: { pending: 1 }, applied: { pending: 1 } }); + expect(remote, "MEDIA_FLOW_KEEP_COMMITTED").toEqual(expect.arrayContaining([HARBOUR_TO, CONFIG])); + expect(remote.filter(p => p.startsWith(".brain/")), "MEDIA_FLOW_KEEP_SCRATCH_UNCOMMITTED").toEqual([]); + // The conversation link still serves the original through the files route. + const served = await fetch(`${f.url}/api/files/content?path=${encodeURIComponent(HARBOUR)}&raw=1`, { headers: { "x-media-flow-principal": "owner" } }); + expect(served.status).toBe(200); + expect(sha(Buffer.from(await served.arrayBuffer())), "MEDIA_FLOW_KEEP_LINK_SERVES_ORIGINAL").toBe(sha(MEDIA_BYTES[HARBOUR]!)); +}); + +test("restart and reconnect mid-pass keep the deferrals, set-aside dispositions and counts, and a new pass selects deferred media again", async () => { + const f = await flow([LOOM, SHIELD, SKETCH, ARGUS]); + const before = f.bytes(); + let device = await f.device(); + await f.command("start"); + // Dismiss one file and snooze another: both set aside, so neither is awaiting review. + const dismissed = await f.until(r => r.action?.status === "pending", "a pending card"); + device.resolve(dismissed.action.id, "dismiss"); + const snoozed = await settled(f, dismissed.action.id); + device.resolve(snoozed.action.id, "later"); + const third = await settled(f, snoozed.action.id); + agree(await f.parity({ sync: true }), { pending: 2, dismissed: 1, snoozed: 1 }); + // Leave one pending: it still counts, and is skipped for the rest of the pass. + device.resolve(third.action.id, "leave-pending"); + const fourth = await settled(f, third.action.id); + expect(fourth.review.deferred.map((d: { findingId: string }) => d.findingId), "MEDIA_FLOW_DEFERRED").toEqual([third.action.hygiene.findingId]); + agree(await f.parity({ sync: false }), { pending: 2, dismissed: 1, snoozed: 1 }); + + // The host dies mid-pass: nothing is closed. The same state boots again on the same port. + const port = Number(new URL(f.url).port); + await f.kill(); + await f.boot({ port }); + const rebooted = await f.read(); + expect(rebooted.review.pendingActionId, "MEDIA_FLOW_RESTART_SAME_CARD").toBe(fourth.review.pendingActionId); + expect(rebooted.review.deferred, "MEDIA_FLOW_RESTART_DEFERRALS").toEqual(fourth.review.deferred); + expect(rebooted.review.media, "MEDIA_FLOW_RESTART_COUNTS").toEqual(fourth.review.media); + agree(await f.parity({ sync: true }), { pending: 2, dismissed: 1, snoozed: 1 }); + // A device reconnects and receives the same card; a clean stop and start keep it too. + await device.close(); + device = await f.device(); + await f.until(() => device.item(fourth.review.pendingActionId)?.status === "pending", "the reconnected device holds the pending card"); + await f.stop(); + await f.boot({ port }); + device = await f.device(); + expect((await f.read()).review.deferred).toEqual(fourth.review.deferred); + device.resolve(fourth.review.pendingActionId, "leave-pending"); + const finished = await settled(f, fourth.review.pendingActionId); + expect(finished.review.status, "MEDIA_FLOW_PASS_COMPLETE").toBe("complete"); + agree(await f.parity({ sync: true }), { pending: 2, dismissed: 1, snoozed: 1 }); + // Nothing was written to the brain's media, config or references. + expect({ ...f.bytes(), [KEPT]: null }, "MEDIA_FLOW_DISPOSITIONS_NO_MEDIA_WRITE").toEqual(before); + + // The next pass forgets the deferrals and selects both deferred files again. + const next = (await f.command("start")).body; + expect(next.review.pass, "MEDIA_FLOW_NEW_PASS").toBe(2); + expect(next.review.deferred).toEqual([]); + agree(await f.parity({ sync: false }), { pending: 2, dismissed: 1, snoozed: 1 }); + expect([third.action.hygiene.findingId, fourth.action.hygiene.findingId], "MEDIA_FLOW_NEW_PASS_RESELECTS").toContain(next.action.hygiene.findingId); + await device.close(); +}); + +test("capacity: a capture that cannot fit the change journal refuses before any write, and nothing changes in either count", async () => { + // A 1.4 MB sketch against a 1 MiB journal: its pre-image cannot be captured. + const f = await flow([SKETCH, ARGUS], { capBytes: 1024 * 1024 }, undefined, { [SKETCH]: noisePng(700) }); + const device = await f.device(); + await f.command("start"); + const before = f.bytes(); + const card = await reach(f, device, SKETCH); + device.resolve(card.id, "media-delete"); + const receipt = (await f.until(r => r.action?.hygiene?.outcome && r.action.hygiene.outcome.status !== "applying", "a refused outcome")).action.hygiene.outcome; + expect(receipt, "MEDIA_FLOW_CAPACITY_REFUSED").toMatchObject({ status: "refused", reason: "capture-capacity", media: { outcome: "refused", reason: "capture-capacity" } }); + expect(f.bytes(), "MEDIA_FLOW_CAPACITY_NO_WRITE").toEqual(before); + agree(await f.parity({ sync: true }), { pending: 2 }, "kept"); + await device.close(); +}); + +test("stale premise: a config edited after the Move preview makes the apply stale, with nothing moved or rewritten", async () => { + const config = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/**"] } }\n'; + const f = await flow([LOOM, ARGUS], {}, config); + const device = await f.device(); + await f.command("start"); + const card = await reach(f, device, LOOM); + await destination(f, card, "media-move", LOOM_TO); + // Penelope adds an unrelated standing rule on another device before Odysseus confirms. + const edited = '{ "media": { "ignore": [".brain/scratch/**", "*.psd"], "track": ["places/**"] } }\n'; + writeFileSync(join(f.root, CONFIG), edited); + const before = f.bytes(); + device.resolve(card.id, "media-move"); + await f.until(() => !!device.item(card.id)?.hygiene?.outcome && device.item(card.id).hygiene.outcome.status !== "applying", "the card's outcome"); + const outcome = device.item(card.id).hygiene.outcome; + expect(outcome, "MEDIA_FLOW_STALE_OUTCOME").toMatchObject({ status: "stale", media: { outcome: "stale", reason: "premise-changed" } }); + expect(f.bytes(), "MEDIA_FLOW_STALE_NO_WRITE").toEqual(before); + expect(f.text(NOTE), "MEDIA_FLOW_STALE_REFERENCE").toBe(NOTE_TEXT); + agree(await f.parity({ sync: false }), { pending: 2 }, "kept"); + await device.close(); +}); + +/** Run until the server halts at its interrupt step, then kill it there and boot it again. */ +async function interrupted(f: MediaFlow, port: number, decide: () => void) { + decide(); + const end = Date.now() + 10_000; + while (!f.interrupted() && Date.now() < end) await Bun.sleep(25); + expect(f.interrupted(), "MEDIA_FLOW_INTERRUPTED").toBe(true); + const written = f.bytes(); + await f.kill(); + await f.boot({ port }); + return written; +} + +test("interruption: a host killed between the copy and its kept entry is compensated at boot, and nothing is kept or committed", async () => { + const f = await flow([HARBOUR, ARGUS], { interrupt: "keep-copy" }); + const port = Number(new URL(f.url).port); + const device = await f.device(); + await f.command("start"); + const before = f.bytes(); + const card = await reach(f, device, HARBOUR); + await destination(f, card, "media-keep-copy", HARBOUR_TO); + const written = await interrupted(f, port, () => device.resolve(card.id, "media-keep-copy")); + // Step 6 wrote the copy and its rule; step 6b, the kept entry, never ran. + expect(written[HARBOUR_TO], "MEDIA_FLOW_INTERRUPTED_COPY_WRITTEN").toBe(sha(MEDIA_BYTES[HARBOUR]!)); + expect(written[KEPT]).toBeNull(); + expect(f.bytes(), "MEDIA_FLOW_INTERRUPTED_COPY_COMPENSATED").toEqual(before); + const recovered = await f.until(r => r.action?.hygiene?.outcome?.media, "the recovered receipt"); + expect(recovered.action.hygiene.outcome, "MEDIA_FLOW_INTERRUPTED_COPY_RECEIPT").toMatchObject({ status: "check_failed", media: { outcome: "compensated", action: "keep-copy" } }); + agree(await f.parity({ sync: true }), { pending: 1 }, "kept"); + expect(f.remoteFiles(), "MEDIA_FLOW_INTERRUPTED_COPY_UNCOMMITTED").not.toContain(HARBOUR_TO); + await device.close().catch(() => {}); +}); + +test("interruption: a host killed after a Move wrote the file and its reference is compensated at boot and never re-applied", async () => { + const f = await flow([LOOM, ARGUS], { interrupt: "media" }, '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/**"] } }\n'); + const port = Number(new URL(f.url).port); + const device = await f.device(); + await f.command("start"); + const before = f.bytes(); + const card = await reach(f, device, LOOM); + await destination(f, card, "media-move", LOOM_TO); + const written = await interrupted(f, port, () => device.resolve(card.id, "media-move")); + expect(written[LOOM_TO], "MEDIA_FLOW_INTERRUPTED_MOVE_WRITTEN").toBe(sha(MEDIA_BYTES[LOOM]!)); + expect(written[LOOM]).toBeNull(); + expect(f.bytes(), "MEDIA_FLOW_INTERRUPTED_MOVE_COMPENSATED").toEqual(before); + expect(f.text(NOTE)).toBe(NOTE_TEXT); + const recovered = await f.until(r => r.action?.hygiene?.outcome?.media, "the recovered receipt"); + expect(recovered.action.hygiene.outcome, "MEDIA_FLOW_INTERRUPTED_MOVE_RECEIPT").toMatchObject({ status: "check_failed", media: { outcome: "compensated", action: "move" } }); + agree(await f.parity({ sync: true }), { pending: 2 }, "kept"); + expect(f.remoteFiles()).not.toContain(LOOM_TO); + await device.close().catch(() => {}); +}); + +test("isolation: another owner device cannot undo Odysseus's effect, and a delegated agent can neither start, preview, apply nor undo", async () => { + const f = await flow([SKETCH, ARGUS]); + const device = await f.device(); + await f.command("start"); + const card = await reach(f, device, SKETCH); + device.resolve(card.id, "media-delete"); + const receipt = await receiptOf(f, device, card.id); + expect(receipt.media.outcome).toBe("applied"); + await settled(f, card.id); + const deleted = f.bytes(); + // Penelope's tablet is an owner too, but the receipt is Odysseus's. + expect((await f.undo(receipt.media.journalId, "penelope")).status, "MEDIA_FLOW_ISOLATION_OTHER_OWNER_UNDO").toBe(500); + expect(f.bytes(), "MEDIA_FLOW_ISOLATION_OTHER_OWNER_NO_WRITE").toEqual(deleted); + + // The delegated research agent has no review authority at all. + const pending = (await f.until(r => r.action?.status === "pending", "the next card")).action; + expect((await f.command("start", "agent")).status, "MEDIA_FLOW_ISOLATION_AGENT_START").toBe(403); + expect((await f.preview({ itemId: pending.id, optionId: "media-delete", expectedVersion: pending.version, input: null }, "agent")).status, "MEDIA_FLOW_ISOLATION_AGENT_PREVIEW").toBe(403); + expect((await f.undo(receipt.media.journalId, "agent")).status, "MEDIA_FLOW_ISOLATION_AGENT_UNDO").toBe(403); + const agent = await f.device("agent"); + agent.resolve(pending.id, "media-delete"); + await Bun.sleep(500); + expect((await f.read()).action, "MEDIA_FLOW_ISOLATION_AGENT_CARD").toEqual(pending); + expect(f.bytes(), "MEDIA_FLOW_ISOLATION_AGENT_NO_WRITE").toEqual(deleted); + agree(await f.parity({ sync: false }), { pending: 1 }); + + // Odysseus's own Undo still works. + expect((await f.undo(receipt.media.journalId)).body.mediaUndo.outcome).toBe("undone"); + expect(f.bytes()[SKETCH]).toBe(sha(MEDIA_BYTES[SKETCH]!)); + await agent.close(); + await device.close(); +}); From fb9f46c0a79f38d47d96de7d2d281276fb508809 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:28:44 +0000 Subject: [PATCH 03/11] test(ui-react): run each media review action from the card against the real flow The C5 fixture gains a mediaFlow mode that boots the real review flow and forwards its hygiene routes to it, with ops that read the brain's bytes, counts and remote, and kill and boot the server again. The new layout file runs Persist here, Move, Delete and Keep a permanent copy from the card, Undo from the receipt, and Leave pending across a host restart and reconnect, holding the server, the CLI and brain sync to one count (#2783). Co-Authored-By: Claude Opus 5.5 --- .../browser/hygiene-media-flow.layout.tsx | 251 ++++++++++++++++++ .../tests/fixtures/hygiene-browser-server.ts | 32 ++- 2 files changed, 280 insertions(+), 3 deletions(-) create mode 100644 packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx diff --git a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx new file mode 100644 index 0000000000..53aae30205 --- /dev/null +++ b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx @@ -0,0 +1,251 @@ +/// +/** + * Media hygiene review end to end in the browser (#2783, epic #1777): the + * real consumer against the real review server, real offline CLI and an + * Odysseus brain with a bare remote (`ui-server/tests/helpers/media-flow.ts`, + * booted by the C5 fixture's `mediaFlow`). Each of the five actions runs from + * the card; the fixture then reads the brain's actual bytes and holds the + * server's count and selection to the CLI's and an ordinary `brain sync`'s. + * Raw previews come from the flow's real files route. Offline and keyless. + */ +import { afterAll, afterEach, beforeAll, expect, test } from "vitest"; +import { commands, page, userEvent } from "vitest/browser"; +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { parseServerMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { DesktopPalette } from "../../src/components/layout/desktop-palette.js"; +import { ActivityPage } from "../../src/components/activity/activity-page.js"; +import { stopHygieneFixture } from "./hygiene-fixture-stop.ts"; + +type Bytes = Record; +type Counts = { awaitingReview: number; setAside: number; kept: number }; +type Flow = { + url: string; bytes?: Bytes; texts?: Record; remote?: string[]; + parity?: { sync: { pending: number; setAside: { dismissed: number; snoozed: number; kept: number }; report: string } | null; + server: { media: Counts | null; findingId: string | null; status: string }; cli: { media: Counts; findingId: string | null }; eligible: boolean | null }; +}; +let fixture: { id: string; url: string } | undefined; +let renderer: Root | undefined, ui: BrainUiRoot | undefined, host: HTMLDivElement | undefined, socket: WebSocket | undefined; +let styles: HTMLStyleElement; +const originalTheme = document.documentElement.dataset.theme; +const viewport = { width: innerWidth, height: innerHeight }; +beforeAll(async () => { + styles = document.createElement("style"); + styles.textContent = await commands.formConsumerStyles(); + document.head.append(styles); +}); +afterAll(async () => { + styles.remove(); + await page.viewport(viewport.width, viewport.height); +}); +afterEach(async () => { + const r = renderer, u = ui, s = socket, h = host, f = fixture; + renderer = ui = socket = host = fixture = undefined; + if (r) flushSync(() => r.unmount()); + u?.dispose(); + s?.close(); + h?.remove(); + if (f) await stopHygieneFixture(f.id); + if (originalTheme === undefined) delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = originalTheme; +}); + +const LOOM = "photos/penelope-loom.png", SHIELD = "photos/achilles-shield.png", SKETCH = "inbox/cyclops-sketch.png", ARGUS = "photos/argus-waiting.png"; +const HARBOUR = ".brain/scratch/2026-07-12/harbour-dawn.png"; +const NOTE = "notes/the-return.md", CONFIG = "brain.config.json", PINS = ".brain/scratch-pins/pins.json", KEPT = "context/hygiene/kept.md"; +const TRACK_PLACES = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/**"] } }\n'; + +const set = async (patch: Record) => ((await commands.hygieneServer({ op: "set", id: fixture!.id, patch })) as { flow: Flow }).flow; + +/** Open a socket to the flow's server and route the root's decisions over it, as the app's connection does. */ +async function connect(root: BrainUiRoot, url: string) { + const ws = socket = new WebSocket(`${url.replace("http:", "ws:")}/ws?as=owner`); + root.connection.send = (msg) => { + if (ws.readyState !== WebSocket.OPEN) return false; + ws.send(JSON.stringify(msg)); + return true; + }; + ws.onmessage = (e) => { + const p = parseServerMessage(e.data); + if (!p.ok) throw new Error(p.error); + root.connection.handleServerMessage(p.message); + }; + ws.onclose = () => root.stores.inbox.getState().connectionLost(); + await expect.poll(() => root.stores.inbox.getState().online).toBe(true); +} + +async function scene(mediaFlow: { media: string[]; config?: string }, width: number, theme: string) { + await page.viewport(width, 1000); + document.documentElement.dataset.theme = theme; + fixture = (await commands.hygieneServer({ op: "start" })) as NonNullable; + const flow = await set({ mediaFlow }); + const root = ui = createBrainUiRoot({ + storage: null, + // Raw media bytes come from the flow's real files route, as an `` does from the host. + config: { backendUrl: flow.url }, + request: async (url, init) => { + const target = new URL(url, location.origin); + // JSON goes through the page's same-origin hygiene route, which forwards it to the flow. + if (target.pathname.includes("/hygiene/")) return fetch(`${target.pathname}${target.search}`, init); + if (target.pathname.endsWith("/activity/runs")) return Response.json({ live: [], history: [] }); + if (target.pathname.endsWith("/activity/inbox")) return Response.json({ intents: [] }); + return new Response("{}", { status: 404 }); + }, + }); + await connect(root, flow.url); + const h = host = document.createElement("div"); + h.style.height = "1000px"; + h.style.display = "flex"; + h.className = "bg-background text-foreground"; + document.body.append(h); + const r = renderer = createRoot(h); + flushSync(() => r.render()); + await expect.poll(() => h.querySelector("[data-hygiene-id]")).not.toBeNull(); + if (width >= 1280) await page.getByRole("button", { name: /^Open finding:/ }).click(); + await expect.poll(() => h.querySelector("[data-hygiene-media]")).not.toBeNull(); + return flow; +} +const card = () => host!.querySelector("[data-hygiene-media]"); +const title = () => card()?.querySelector("[data-hygiene-title]")?.textContent ?? null; +const region = () => card()?.querySelector('[role="region"][aria-label="Preview"]'); +const status = () => card()?.querySelector('[role="status"][data-media-status]')?.textContent; +const commit = () => card()!.querySelectorAll("[data-bk-button]")[0]!; +const receipt = () => host!.querySelector("[data-media-receipt]")?.textContent ?? ""; +const countLine = () => host!.querySelector("[data-hygiene-media-count]")?.textContent ?? null; +const name = (path: string) => path.slice(path.lastIndexOf("/") + 1); +async function ready() { + await expect.poll(() => status()).toBe("Preview ready"); + await expect.poll(() => region()?.dataset.mediaPreviewRegion).toBe("ready"); +} +async function destination(value: string) { + await page.getByRole("textbox", { name: /Destination/ }).fill(value); + await userEvent.keyboard("{Enter}"); +} +/** Leave pending, from the card, every finding before the one at `path`. */ +async function reach(path: string) { + for (let i = 0; i < 4 && title() !== name(path); i++) { + const from = title(); + await page.getByRole("button", { name: "Leave pending", exact: true }).click(); + await expect.poll(() => title() !== null && title() !== from).toBe(true); + } + expect(title(), "MEDIA_FLOW_BROWSER_CARD").toBe(name(path)); +} +/** The server and the CLI agree on count and selection; with a sync, so does `brain sync`, and the card's count line. */ +async function agree(pending: number, options: { sync?: boolean; selected?: boolean } = {}) { + // An Undo's receipt replicates before its request returns; the server's count settles with the request. + await expect.poll(async () => ((await set({ flowRead: true })) as Flow & { flowRead: { review: { media?: Counts } } }).flowRead.review.media?.awaitingReview, { timeout: 5000 }).toBe(pending); + const { parity } = await set({ flowParity: options.sync === false ? "cli" : "sync" }); + expect(parity!.server.media, "MEDIA_FLOW_BROWSER_SERVER_COUNT").toEqual({ awaitingReview: pending, setAside: 0, kept: 0 }); + expect(parity!.cli.media, "MEDIA_FLOW_BROWSER_CLI_COUNT").toEqual(parity!.server.media); + if (options.selected !== false) expect(parity!.cli.findingId, "MEDIA_FLOW_BROWSER_SELECTION").toBe(parity!.server.findingId); + else if (parity!.server.findingId) expect(parity!.eligible, "MEDIA_FLOW_BROWSER_SELECTION_ELIGIBLE").toBe(true); + if (parity!.sync) { + expect(parity!.sync.pending, "MEDIA_FLOW_BROWSER_SYNC_COUNT").toBe(pending); + expect(parity!.sync.report).toContain(`Media awaiting review: ${pending}`); + for (const path of [LOOM, SHIELD, SKETCH, ARGUS, HARBOUR]) expect(parity!.sync.report).not.toContain(path); + } + await expect.poll(() => countLine(), { timeout: 5000 }).toBe(`Media awaiting review: ${pending}`); +} +async function undo(prefix: RegExp, path: string) { + await page.getByRole("button", { name: prefix }).click(); + await page.getByRole("button", { name: "Confirm undo", exact: true }).click(); + await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Undone · ${name(path)} is awaiting review again`); +} + +test("dark 320: Persist here from the card tracks exactly the file; Undo from the receipt restores the config's bytes", async () => { + const flow = await scene({ media: [SHIELD, ARGUS] }, 320, "dark"); + const before = (await set({ flowBytes: true })).bytes!; + await reach(SHIELD); + await page.getByRole("radio", { name: "Persist here" }).click(); + await ready(); + expect(commit().textContent).toBe(`Persist ${name(SHIELD)}`); + commit().click(); + await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Persisted · ${SHIELD}`); + const applied = await set({ flowBytes: [CONFIG] }); + expect(applied.texts![CONFIG], "MEDIA_FLOW_BROWSER_PERSIST_CONFIG").toBe('{ "media": { "ignore": [".brain/scratch/**"], "track": ["photos/achilles-shield.png"] } }\n'); + expect(applied.bytes![SHIELD]).toBe(before[SHIELD]); + await agree(1, { sync: false }); + await undo(/^Undo: Persisted/, SHIELD); + expect((await set({ flowBytes: true })).bytes, "MEDIA_FLOW_BROWSER_PERSIST_UNDO").toEqual(before); + await agree(2, { selected: false }); + expect(flow.url).toMatch(/^http:\/\/127\.0\.0\.1:/); +}); + +test("light 1280: Move… with its destination moves the file and rewrites its reference; the next sync commits both", async () => { + await scene({ media: [LOOM, ARGUS], config: TRACK_PLACES }, 1280, "light"); + await reach(LOOM); + // The preview loads the file's real bytes from the files route. + await expect.poll(() => card()!.querySelector("[data-media-frame] img")?.naturalWidth ?? 0).toBe(24); + await page.getByRole("radio", { name: "Move to a final location" }).click(); + await destination("places/ithaca/penelope-loom.png"); + await ready(); + expect(region()!.textContent).toContain(NOTE); + commit().click(); + await expect.poll(() => receipt(), { timeout: 5000 }).toContain("Moved"); + const moved = await set({ flowBytes: [NOTE] }); + expect(moved.bytes![LOOM], "MEDIA_FLOW_BROWSER_MOVE_SOURCE").toBeNull(); + expect(moved.bytes!["places/ithaca/penelope-loom.png"], "MEDIA_FLOW_BROWSER_MOVE_DESTINATION").not.toBeNull(); + expect(moved.texts![NOTE], "MEDIA_FLOW_BROWSER_MOVE_REFERENCE").toContain("![loom](../places/ithaca/penelope-loom.png)"); + await agree(1); + expect((await set({ flowRemote: true })).remote, "MEDIA_FLOW_BROWSER_MOVE_COMMITTED").toEqual(expect.arrayContaining(["places/ithaca/penelope-loom.png", NOTE])); +}); + +test("dark 1280: Delete… removes exactly the file, and Undo from the receipt restores its bytes", async () => { + await scene({ media: [SKETCH, ARGUS] }, 1280, "dark"); + const before = (await set({ flowBytes: true })).bytes!; + await reach(SKETCH); + await page.getByRole("radio", { name: "Delete" }).click(); + await ready(); + expect(commit().textContent).toBe(`Delete ${name(SKETCH)}`); + commit().click(); + await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Deleted · ${SKETCH}`); + expect((await set({ flowBytes: true })).bytes, "MEDIA_FLOW_BROWSER_DELETED").toEqual({ ...before, [SKETCH]: null }); + await agree(1, { sync: false }); + await undo(/^Undo: Deleted/, SKETCH); + expect((await set({ flowBytes: true })).bytes, "MEDIA_FLOW_BROWSER_DELETE_UNDO").toEqual(before); + await agree(2, { selected: false }); +}); + +test("light 320: Keep a permanent copy… of linked scratch copies it and leaves the original and its pins; the next sync commits only the copy", async () => { + await scene({ media: [HARBOUR, ARGUS] }, 320, "light"); + const before = (await set({ flowBytes: true })).bytes!; + await reach(HARBOUR); + await page.getByRole("radio", { name: "Keep a permanent copy" }).click(); + await destination("places/ithaca/harbour-dawn.png"); + await ready(); + commit().click(); + await expect.poll(() => receipt(), { timeout: 5000 }).toContain("Kept a permanent copy at places/ithaca/harbour-dawn.png · the original stays linked to its conversation"); + const kept = await set({ flowBytes: [CONFIG, KEPT] }); + expect(kept.bytes!["places/ithaca/harbour-dawn.png"], "MEDIA_FLOW_BROWSER_KEEP_COPY").toBe(before[HARBOUR]); + expect(kept.bytes![HARBOUR], "MEDIA_FLOW_BROWSER_KEEP_ORIGINAL").toBe(before[HARBOUR]); + expect(kept.bytes![PINS], "MEDIA_FLOW_BROWSER_KEEP_PINS").toBe(before[PINS]); + expect(kept.texts![CONFIG]).toBe('{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/ithaca/harbour-dawn.png"] } }\n'); + expect(kept.texts![KEPT], "MEDIA_FLOW_BROWSER_KEEP_ENTRY").toContain("- copy: `places/ithaca/harbour-dawn.png`"); + // Pinned scratch is review-only: the routine count is the content file's alone. + await agree(1); + const remote = (await set({ flowRemote: true })).remote!; + expect(remote, "MEDIA_FLOW_BROWSER_KEEP_COMMITTED").toContain("places/ithaca/harbour-dawn.png"); + expect(remote.filter((p) => p.startsWith(".brain/"))).toEqual([]); +}); + +test("dark 320: Leave pending, then the host restarts mid-pass and the device reconnects to the same card, deferral and count", async () => { + const flow = await scene({ media: [SHIELD, ARGUS] }, 320, "dark"); + const first = title(); + await page.getByRole("button", { name: "Leave pending", exact: true }).click(); + await expect.poll(() => title() !== null && title() !== first).toBe(true); + const second = title(); + await agree(2); + // The host dies; the socket drops. The same state boots again on the same port. + await set({ flowRestart: true }); + await expect.poll(() => ui!.stores.inbox.getState().online).toBe(false); + await connect(ui!, flow.url); + await expect.poll(() => title()).toBe(second); + expect((await set({ flowRead: true }) as Flow & { flowRead: { review: { deferred: unknown[] } } }).flowRead.review.deferred, "MEDIA_FLOW_BROWSER_RESTART_DEFERRAL").toHaveLength(1); + await agree(2); + await page.getByRole("button", { name: "Leave pending", exact: true }).click(); + await expect.poll(() => card()).toBeNull(); + await expect.poll(() => countLine()).toBe("Media awaiting review: 2"); + expect((await set({ flowBytes: true })).bytes![SHIELD]).not.toBeNull(); +}); diff --git a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts index b24a12bbee..16dd2d08c6 100644 --- a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts +++ b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts @@ -1,5 +1,8 @@ /** Offline C5 fixture: real routes/coordinator/SQLite/stream, deterministic CLI boundary. - * C6 owns the separate full browser → CLI → Markdown proof. */ + * C6 owns the separate full browser → CLI → Markdown proof. With `mediaFlow`, + * the hygiene routes forward instead to the real media review flow (#2783): + * an Odysseus brain, the real CLI and the real review server, as its own + * process (`ui-server/tests/helpers/media-flow.ts`). */ import { createHash } from "node:crypto"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -15,6 +18,7 @@ import { createInboxStream } from "../../../ui-server/src/inbox/stream.js"; import type { AppEnv } from "../../../ui-server/src/app-env.js"; import type { BrainClient } from "../../../ui-server/src/brain/client.js"; import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { createMediaFlow, type MediaFlow } from "../../../ui-server/tests/helpers/media-flow.js"; const scratch = mkdtempSync(join(tmpdir(), "c5-server-")); const db = createUiDb(join(scratch, "ui.sqlite")); @@ -461,6 +465,14 @@ const auth = { release() {}, }; const app = new Hono(); +/** The real media review flow, when a scene asked for it: its JSON routes answer for this fixture's. */ +let flow: MediaFlow | undefined; +app.use("/api/hygiene/*", async (c, next) => { + if (!flow) return next(); + const body = c.req.method === "GET" ? undefined : await c.req.text(); + const r = await fetch(`${flow.url}${c.req.path}`, { method: c.req.method, headers: { "content-type": "application/json", "x-media-flow-principal": "owner" }, ...(body ? { body } : {}) }); + return new Response(await r.text(), { status: r.status, headers: { "content-type": "application/json" } }); +}); app.use("*", async (c, next) => { c.set("principal", (as === "agent" ? agent : principal) as never); if (c.req.method === "GET" && c.req.path === "/api/hygiene/review") { @@ -553,7 +565,20 @@ app.post("/fixture", async (c) => { await new Promise((r) => setTimeout(r, 50)); } if (p.start) await review.command(principal.id, "start"); - return c.json({ calls, read: review.read(), reads, detailReads, selecting: !!releaseNext, files }); + // The real media flow (#2783): boot it, then read its bytes, counts and remote, or kill and boot it again. + const result: Record = {}; + if (p.mediaFlow) { + if (flow) throw new Error("media flow already running"); + flow = createMediaFlow(p.mediaFlow); + await flow.boot(); + if (p.mediaFlow.start !== false) await flow.command("start"); + } + if (flow && p.flowRestart) { const port = Number(new URL(flow.url).port); await flow.kill(); await flow.boot({ port }); } + if (flow && p.flowParity) result.parity = await flow.parity({ sync: p.flowParity === "sync" }); + if (flow && p.flowBytes) { result.bytes = flow.bytes(); result.texts = Object.fromEntries((p.flowBytes === true ? [] : p.flowBytes as string[]).map(path => [path, flow!.text(path)])); } + if (flow && p.flowRemote) result.remote = flow.remoteFiles(); + if (flow && p.flowRead) result.flowRead = await flow.read(); + return c.json({ calls, read: review.read(), reads, detailReads, selecting: !!releaseNext, files, flow: flow ? { url: flow.url, ...result } : null }); }); const server = Bun.serve({ hostname: "127.0.0.1", @@ -582,11 +607,12 @@ const server = Bun.serve({ }, }); console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}` })); -process.on("SIGTERM", () => { +process.on("SIGTERM", async () => { releaseHolds(); stream.close(); server.stop(true); db.close(); rmSync(scratch, { recursive: true, force: true }); + await flow?.close(); process.exit(0); }); From 2a79ab4d0e07c275f549bd25d06798b6f1aaf81d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:35:48 +0000 Subject: [PATCH 04/11] test(ui-server): run the media review flow with its CLI in maintenance workers, also in the native runtime A worker boot mode runs every brain command the review server issues in a real maintenance worker behind the native manager boundary, with the test-only copied checkpoints, and reports the boundary's qualification. A new scenario applies and undoes Keep a permanent copy there with the counts agreeing. The Claude UID 1000 cell of the native hosted proof runs it in the same container, so the runtime_host job proves it too (#2783). Co-Authored-By: Claude Opus 5.5 --- .../tests/fixtures/media-flow-server.ts | 28 +++++++++++++----- .../ui-server/tests/helpers/media-flow.ts | 13 +++++---- .../ui-server/tests/media-review-flow.test.ts | 29 +++++++++++++++++++ scripts/native-proof/README.md | 9 ++++++ scripts/native-proof/fixture.py | 3 ++ scripts/prove-native-host.ts | 2 ++ 6 files changed, 71 insertions(+), 13 deletions(-) diff --git a/packages/ui-server/tests/fixtures/media-flow-server.ts b/packages/ui-server/tests/fixtures/media-flow-server.ts index f1ec3efed2..ade09351c6 100644 --- a/packages/ui-server/tests/fixtures/media-flow-server.ts +++ b/packages/ui-server/tests/fixtures/media-flow-server.ts @@ -5,7 +5,13 @@ * routes, on loopback. Nothing is canned. `tests/helpers/media-flow.ts` boots * it on one state directory, and stops, kills and boots it again there. * - * argv: + * argv: + * + * `worker` runs every brain CLI command the server issues in a real + * maintenance worker behind the native manager boundary, with the test-only + * copied checkpoints, as the worker-backed review suites do; a host that + * cannot start one fails rather than falling back. `host` runs them as host + * processes, as a server on a host without a qualified worker does. * * Test-only seams, each named by the parent: a principal per request * (`x-media-flow-principal` or `?as=` on the socket: the owner Odysseus, a @@ -33,8 +39,10 @@ import { createInboxStore } from "../../src/inbox/store.js"; import { createInboxStream } from "../../src/inbox/stream.js"; import type { AppEnv } from "../../src/app-env.js"; import { createNativeJournalFixture } from "../helpers/native-journal-fixture.js"; +import { replaceNativeStartupAcquisitionForFixture } from "../helpers/fixture-native-startup.js"; +import { createNativeBrainManagerClient, NATIVE_MANAGER_MAX_DELTA_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS } from "@schlessera/brain-ui-sdk/internal"; -const [brainPath, state, port, cap] = process.argv.slice(2) as [string, string, string, string]; +const [brainPath, state, port, cap, execution] = process.argv.slice(2) as [string, string, string, string, "host" | "worker"]; const dbPath = join(state, "ui.sqlite"); const db = createUiDb(dbPath); const principalsFile = join(state, "principals.json"); @@ -53,10 +61,15 @@ const native = createNativeJournalFixture(brainPath, state); const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath, dbPath, objectsRoot: join(state, "objects"), ...(Number(cap) > 0 ? { capBytes: Number(cap) } : {}) }); await journal.ready; const gate = createWriterGate(db, brainPath); -// The brain client the app builds, on a host without a qualified worker: the -// CLI runs as a host process under the same gates. The hosted native proof -// runs this flow's effects inside real maintenance workers instead. -const boundary = createHostBoundary({ brainPath, exec: {}, dbPath, workerHost: () => ({ ok: false, requirement: "the media flow fixture runs the CLI on the host" }) }); +// The brain client the app builds. In a worker, through the native manager +// boundary; otherwise on a host without a qualified worker, as host processes. +let broker: { socketPath: string; close(): void } | undefined; +if (execution === "worker") { replaceNativeStartupAcquisitionForFixture(); broker = native.serve(); } +const boundary = broker + ? createHostBoundary({ brainPath, exec: {}, dbPath, nativeManager: createNativeBrainManagerClient({ socketPath: broker.socketPath, leasePath: join(state, "native-leases.sqlite"), timeoutMs: NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: NATIVE_MANAGER_MAX_DELTA_BYTES }) }) + : createHostBoundary({ brainPath, exec: {}, dbPath, workerHost: () => ({ ok: false, requirement: "the media flow fixture runs the CLI on the host" }) }); +// As the app does at boot: qualify the worker boundary before any admission. +const governed = await boundary.prepare(); const brain = createBrainClient({ brainPath, exec: {}, boundary }); /** Stop dead at `interrupt.txt`'s CLI step, before (`keep-copy`) or after (`media`) it runs. */ @@ -106,11 +119,12 @@ const server = Bun.serve<{ principalId: string }, never>({ close(ws) { stream.dropConnection({ raw: ws } as never); }, }, }); -console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}`, principals })); +console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}`, principals, hostExecution: boundary.status().hostExecution, governed })); process.on("SIGTERM", async () => { stream.close(); server.stop(true); await journal.close(); + broker?.close(); await native.close(); db.close(); process.exit(0); diff --git a/packages/ui-server/tests/helpers/media-flow.ts b/packages/ui-server/tests/helpers/media-flow.ts index 6d5b408235..c26b41cfb6 100644 --- a/packages/ui-server/tests/helpers/media-flow.ts +++ b/packages/ui-server/tests/helpers/media-flow.ts @@ -118,7 +118,7 @@ export function createMediaFlow(options: { directory?: string; media?: readonly // The conversation that linked the scratch file pins it; the pins exist with or without it. put(root, PINS, PINS_TEXT); - let child: ChildProcess | undefined, url = "", stderr = ""; + let child: ChildProcess | undefined, url = "", stderr = "", hostExecution = "", governed: unknown = null; const home = join(directory, "home"); mkdirSync(home); const env = { PATH: process.env.PATH ?? "", HOME: home, BRAIN_ROOT: root, GIT_CONFIG_NOSYSTEM: "1", TMPDIR: process.env.TMPDIR ?? tmpdir() }; @@ -135,20 +135,21 @@ export function createMediaFlow(options: { directory?: string; media?: readonly /** One ordinary `brain sync`, as a person or cron runs it. */ function sync(): any { return cli("sync", "--json"); } - async function boot(boot: { port?: number; capBytes?: number; interrupt?: string } = {}) { + async function boot(boot: { port?: number; capBytes?: number; interrupt?: string; execution?: "host" | "worker" } = {}) { if (child) throw new Error("server already running"); if (boot.interrupt) writeFileSync(join(state, "interrupt.txt"), boot.interrupt); else rmSync(join(state, "interrupt.txt"), { force: true }); rmSync(join(state, "interrupted.flag"), { force: true }); stderr = ""; - const proc = spawn(process.execPath, ["--preload", PRELOAD, SERVER, root, state, String(boot.port ?? 0), String(boot.capBytes ?? 0)], { cwd: REPO, env, stdio: ["ignore", "pipe", "pipe"] }); + const proc = spawn(process.execPath, ["--preload", PRELOAD, SERVER, root, state, String(boot.port ?? 0), String(boot.capBytes ?? 0), boot.execution ?? "host"], { cwd: REPO, env, stdio: ["ignore", "pipe", "pipe"] }); child = proc; proc.stderr!.on("data", b => { stderr += String(b); }); - url = await new Promise((res, reject) => { + const ready = await new Promise<{ url: string; hostExecution: string; governed: unknown }>((res, reject) => { let out = ""; const timer = setTimeout(() => { proc.kill("SIGKILL"); reject(new Error(`media flow server did not start: ${stderr}`)); }, 20_000); proc.once("exit", code => { clearTimeout(timer); reject(new Error(`media flow server exited ${code}: ${stderr}`)); }); - proc.stdout!.on("data", b => { out += String(b); if (out.includes("\n")) { clearTimeout(timer); try { res(JSON.parse(out.split("\n")[0]!).url); } catch (e) { reject(e); } } }); + proc.stdout!.on("data", b => { out += String(b); if (out.includes("\n")) { clearTimeout(timer); try { res(JSON.parse(out.split("\n")[0]!)); } catch (e) { reject(e); } } }); }); + url = ready.url; hostExecution = ready.hostExecution; governed = ready.governed; return url; } /** SIGTERM: the server closes its stream, journal and database. */ @@ -248,7 +249,7 @@ export function createMediaFlow(options: { directory?: string; media?: readonly await kill(); rmSync(directory, { recursive: true, force: true }); } - return { directory, root, remote, state, get url() { return url; }, get stderr() { return stderr; }, + return { directory, root, remote, state, get url() { return url; }, get stderr() { return stderr; }, get hostExecution() { return hostExecution; }, get governed() { return governed; }, cli, cliRun, sync, git: (...args: string[]) => git(root, ...args), boot, stop, kill, request, read, command, preview, undo, device, until, parity, bytes, text, remoteFiles, interrupted, close }; } export type MediaFlow = ReturnType; diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts index 40014e2d15..dba791ce75 100644 --- a/packages/ui-server/tests/media-review-flow.test.ts +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -391,3 +391,32 @@ test("isolation: another owner device cannot undo Odysseus's effect, and a deleg await agent.close(); await device.close(); }); + +test("in maintenance workers: the review's CLI runs behind the native manager boundary, Keep a permanent copy applies and Undo restores, and the counts agree", async () => { + // Every brain command the server issues runs in a credential-free maintenance + // worker, with no host fallback; the copied checkpoints are the test-only broker's. + const f = await flow([HARBOUR, ARGUS], { execution: "worker" }); + expect(f.hostExecution, "MEDIA_FLOW_WORKER_EXECUTION").toBe("worker"); + // The boundary qualified a maintenance worker at boot, as the app requires before admission. + expect(f.governed, "MEDIA_FLOW_WORKER_QUALIFIED").toMatchObject({ available: true }); + const device = await f.device(); + const before = f.bytes(); + expect((await f.command("start")).status, "MEDIA_FLOW_WORKER_START").toBe(200); + const card = await reach(f, device, HARBOUR); + await destination(f, card, "media-keep-copy", HARBOUR_TO); + device.resolve(card.id, "media-keep-copy"); + const receipt = await receiptOf(f, device, card.id); + expect(receipt.media, "MEDIA_FLOW_WORKER_KEPT").toMatchObject({ outcome: "kept", undo: { available: true } }); + await settled(f, card.id); + const kept = f.bytes(); + expect(kept[HARBOUR_TO], "MEDIA_FLOW_WORKER_COPY").toBe(sha(MEDIA_BYTES[HARBOUR]!)); + expect(kept[HARBOUR]).toBe(before[HARBOUR]!); + expect(kept[PINS]).toBe(before[PINS]!); + expect(f.text(KEPT), "MEDIA_FLOW_WORKER_KEPT_ENTRY").toContain(`- copy: \`${HARBOUR_TO}\``); + agree(await f.parity({ sync: false }), { pending: 1 }); + const undone = await f.undo(receipt.media.journalId); + expect(undone.body.mediaUndo, "MEDIA_FLOW_WORKER_UNDONE").toMatchObject({ outcome: "undone" }); + expect({ ...f.bytes(), [KEPT]: null }, "MEDIA_FLOW_WORKER_UNDO_BYTES").toEqual(before); + agree(await f.parity({ sync: true }), { pending: 1 }, "kept"); + await device.close(); +}); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 2bd69385e3..627ac6bf0c 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -10,6 +10,15 @@ prerequisites. Preparation can download dependencies; the proof uses `--network=none`, `--pull=never`, the normal test network guards and loopback HTTP/WebSocket clients. Missing prerequisites fail the selected runtime job. +The Claude UID 1000 cell of a default run then runs the media review flow's +worker scenario (#2783) in the same container: +`packages/ui-server/tests/media-review-flow.test.ts -t "in maintenance workers"`. +It runs every brain command the review server issues in a maintenance worker, +with that suite's test-only copied checkpoints rather than this Btrfs volume. +It applies Keep a permanent copy and undoes it, and holds the server, the CLI +and `brain sync` to one count. The fixture records the command and its exit +code in `native-fixture.json`. + `--apply-timing` adds one strict conversation after the cancellation checks (#2835), once the earlier turns' index refresh has finished. Claude calls its turn's `brain-ui` MCP `write_file` handler 20 times and `edit_file` 20 times, diff --git a/scripts/native-proof/fixture.py b/scripts/native-proof/fixture.py index d302f6a22f..6af9f14d44 100644 --- a/scripts/native-proof/fixture.py +++ b/scripts/native-proof/fixture.py @@ -145,6 +145,9 @@ def terminate(): run(["btrfs", "subvolume", "create", str(STORE / "brain")]) # The #2834 timing turn alone makes 220 tool calls, each one model request. run(["/usr/local/bin/bun", "run", "test", str(pathlib.Path(__file__).with_name("hosted-app.test.ts"))], timeout=HOSTED_TIMEOUT) + # #2783: the media review flow with every review CLI command in a maintenance worker, in this runtime. + if os.environ.get("BRAIN_NATIVE_PROOF_MEDIA_FLOW") == "1": + run(["/usr/local/bin/bun", "run", "test", "/repo/packages/ui-server/tests/media-review-flow.test.ts", "-t", "in maintenance workers"], timeout=120) except BaseException as error: failure = error record("failure", detail=str(error)) diff --git a/scripts/prove-native-host.ts b/scripts/prove-native-host.ts index 57775eb92b..9ad69e7fff 100644 --- a/scripts/prove-native-host.ts +++ b/scripts/prove-native-host.ts @@ -14,6 +14,8 @@ export function nativeHostDockerArgs(root: string, artifact: string, uid: string ...(retainIndexNamespace ? ["--env=BRAIN_NATIVE_PROOF_RETAIN_INDEX_NAMESPACE=1"] : []), ...(applyTiming ? ["--env=BRAIN_NATIVE_PROOF_APPLY_TIMING=1"] : []), ...(observationTiming ? ["--env=BRAIN_NATIVE_PROOF_OBSERVATION_TIMING=1"] : []), + // #2783: the media review flow's worker scenario, once per qualification, in the Claude UID 1000 cell. + ...(backend === "claude" && uid === "1000" && !retainIndexNamespace && !applyTiming && !observationTiming ? ["--env=BRAIN_NATIVE_PROOF_MEDIA_FLOW=1"] : []), "--cap-drop=ALL", ...(uid === "0" ? ["--cap-add=SETFCAP"] : []), ...["SYS_ADMIN", "MKNOD", "DAC_OVERRIDE", "FOWNER", "KILL", "CHOWN", "SETUID", "SETGID"].map(value => `--cap-add=${value}`), "--security-opt=no-new-privileges", `--security-opt=seccomp=${join(root, "scripts/native-proof/seccomp.json")}`, ...(apparmor ? ["--security-opt=apparmor=brain-kit-native-proof"] : []), From b39f55b1028daf7436a18cff980d78b158e96614 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 12:35:48 +0000 Subject: [PATCH 05/11] docs: describe count-only media reporting and the five review actions in sync, hygiene and the /sync skill The /sync skill no longer asks about each media file, unattended or not, and never lists them: it repeats the report's count line and points to hygiene review. The CLI reference drops the interactive media hand-over that #2780 removed, adds the count fields and the media review commands, and media.md says what each action leaves for the next sync, including that Move adds no rule and that Git never persists ignored or scratch bytes (#2783). Co-Authored-By: Claude Opus 5.5 --- .changeset/sync-skill-media-review.md | 5 +++ docs/cli.md | 16 +++++-- docs/media.md | 12 +++++ packages/core/skills/sync/SKILL.md | 65 ++++++++++++++++----------- 4 files changed, 70 insertions(+), 28 deletions(-) create mode 100644 .changeset/sync-skill-media-review.md diff --git a/.changeset/sync-skill-media-review.md b/.changeset/sync-skill-media-review.md new file mode 100644 index 0000000000..3ebb4e5f63 --- /dev/null +++ b/.changeset/sync-skill-media-review.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain": patch +--- + +The `/sync` skill no longer asks about media files or lists them. It leaves media untouched, repeats the report's `Media awaiting review: N` line, and points to hygiene review's five actions. diff --git a/docs/cli.md b/docs/cli.md index 8c06e6161d..1c24cb2119 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -153,7 +153,7 @@ when its artifact is null. | `audit` ⚖ | Staleness/propagation/index-lag/orphan/type-mismatch/marker/broken-link/repeated-text/duplicate-title audit | `{issues, errors, warnings, infos, mustFix, informational}`; module hygiene checks appended. TODO and VERIFY markers are one `info` finding per document and kind, with `count` and the first three as `examples`; `verification: unverified` in the frontmatter is one `verify` finding on its own. An unresolved wiki-link is a `broken-link` warning, resolved exactly as `validate` resolves it. `mustFix` is errors plus warnings, `informational` is infos. `--fix --json` returns `AuditFixResult[]`: deterministic suggestions with `canAutoFix` and optional `repair: { capability: "registry", path }` for an available registry repair only. It calls no provider, emits no replacement `fix`, applies nothing and grants no execution permission | | `accept-mtime` | Baseline file mtimes so silent-edit detection stops flagging mechanical edits | | | `tags` ⚖ | Tag hygiene report: variant groups with a proposed canonical tag, tags that repeat the document's type or directory, alias hits, out-of-vocabulary tags | read-only; reads frontmatter, not the index; configure with [`taxonomy.tags`](configuration.md#taxonomytags). `--apply` migrates the tags: every `aliases` entry and every variant group whose canonical is in `vocabulary` (`--groups`: all of them; `--redundant`: also drop redundant tags; `--only `: one tag; `--dry-run`: report only). It edits only the `tags:` entries on the raw text, never bumps `updated`, reindexes, and accepts the touched files' mtimes. A file edited while it runs is skipped, and `--only` merges only the collisions its own rename causes | -| `hygiene reconcile\|list\|next\|dismiss\|snooze\|resolve\|undo\|check` ⚖ | The content-hygiene log under `context/hygiene/`: `reconcile` refreshes the index, detects issues (audit checks, `brain validate`'s corpus checks, silent edits, index table rows, `--extra` candidates), joins reports of one problem into one finding with a stable ID, its sources and an evidence fingerprint, applies the open/snoozed/dismissed/resolved state machine and writes only the files that change; `list` reads the log; `next` reconciles and selects one open finding by severity, explicit urgency, age and ID with a structured priority reason and end-state counts (informational findings are counted but not shown); `dismiss` and `snooze` record a disposition that holds until its evidence fingerprint changes (or, for a snooze, it comes due). Wiki-link rows use indexed targets, including aliases and configured directory anchors; ambiguous/unresolved rows are skipped | `reconcile --fixed ` records the skill's auto-fixes in `last-run.md`; `reconcile --dry-run` writes no log file (the index is still refreshed); `list --state open\|snoozed\|dismissed\|resolved`; `dismiss --expect-fingerprint [--reason ]`; `snooze --until --expect-fingerprint `. A stale fingerprint is refused with exit `1` and nothing written; `brain validate` still reports what is dismissed. Sections of the log it does not own are kept as written, each file is replaced atomically, and while a check cannot run (a module's check throws, fact-drift cannot read a canonical file) nothing that was not detected again is resolved. `next --finding --dry-run --json` reads the current detected open finding by ID without writing Markdown; counts retain the existing log state. `next --json` exits `1` with a structured configuration blocker before any indexing or log writes when the config is invalid. See [selection mappings](integration-contract/package-api.md#hygiene-selection-additive-1026). The `content-hygiene` skill orchestrates reconciliation | +| `hygiene reconcile\|list\|next\|dismiss\|snooze\|resolve\|undo\|check` ⚖ | The content-hygiene log under `context/hygiene/`: `reconcile` refreshes the index, detects issues (audit checks, `brain validate`'s corpus checks, silent edits, index table rows, `--extra` candidates), joins reports of one problem into one finding with a stable ID, its sources and an evidence fingerprint, applies the open/snoozed/dismissed/resolved state machine and writes only the files that change; `list` reads the log; `next` reconciles and selects one open finding by severity, explicit urgency, age and ID with a structured priority reason and end-state counts (informational findings are counted but not shown); `dismiss` and `snooze` record a disposition that holds until its evidence fingerprint changes (or, for a snooze, it comes due). Wiki-link rows use indexed targets, including aliases and configured directory anchors; ambiguous/unresolved rows are skipped | `reconcile --fixed ` records the skill's auto-fixes in `last-run.md`; `reconcile --dry-run` writes no log file (the index is still refreshed); `list --state open\|snoozed\|dismissed\|resolved\|kept`; `dismiss --expect-fingerprint [--reason ]`; `snooze --until --expect-fingerprint `. A stale fingerprint is refused with exit `1` and nothing written; `brain validate` still reports what is dismissed. Sections of the log it does not own are kept as written, each file is replaced atomically, and while a check cannot run (a module's check throws, fact-drift cannot read a canonical file) nothing that was not detected again is resolved. `next --finding --dry-run --json` reads the current detected open finding by ID without writing Markdown; counts retain the existing log state. `next --json` exits `1` with a structured configuration blocker before any indexing or log writes when the config is invalid. Since 0.45.0, `next --defer =,…` skips findings left pending this pass, and `media `, `keep-copy` and `unkeep` are the media review effects hygiene review drives ([contract](integration-contract/cli.md)). See [selection mappings](integration-contract/package-api.md#hygiene-selection-additive-1026). The `content-hygiene` skill orchestrates reconciliation | | `registry` ⚖ | Regenerate the registry table of every `_index.md` with a `registry:` frontmatter block, from its children's frontmatter, between `` markers | `--check` writes nothing and lists stale indexes (exit 1), and is the only form that runs in an uninitialized directory; an index or child that cannot be read or parsed is reported under `invalid` and left as it is; `updated` is bumped only on a file whose table changed; `{indexes, written, stale, invalid}` | | `maintain` | Routine maintenance sequence: registry tables (as `brain registry`), incremental index, vector compaction (only when fewer than half the vector slots are live), audit snapshot (the same counts as `brain audit`, module hygiene checks included, with its must-fix and informational totals), stats recording (0.40.0+), tag report (counts only), git packing, scratch prune | exit 2 if any step failed (the tag report never fails it), and then stderr's last line names each failed step and the start of its result (`brain maintain: FAILED step(s): git (fatal: …)`, at most about 1,000 characters), so a scheduler that keeps only stderr's tail still records which step failed; the hosting container runs it daily. The git step runs git's non-destructive `loose-objects`, `incremental-repack` and `pack-refs` maintenance tasks when the brain is a git work tree (git's own gc counts loose objects, not bytes, so a content repo's large blobs can stay loose indefinitely); it never deletes a ref or expires a reflog; `--no-git` skips it. A brain with no chat server has no other periodic pass, so schedule it (cron) or the scratch area is pruned only when something writes into it | | `scratch clean\|prune` | Empty the scratch area (`.brain/scratch/`), or prune unlinked files to 7 days and 1 GB, preserving retained conversation links | `{action, removed: [{path, bytes, reason}], failed: [{path, reason}], bytes, files}`; exit 2 when a file could not be removed; `prune` also reports `{pinned: {files, bytes}, overageBytes, pinError?}` and accepts `--pins-file `; all prune callers honor managed pin data under `.brain/`. Missing/corrupt managed pins suspend deletion (exit 2); pinned overage is reported. `clean` explicitly removes pinned files too. `render`, `image`, `okf export` and the UI's mask tool prune after writing there, and the chat server prunes hourly | @@ -232,8 +232,8 @@ preserved without checking whether the heading exists. | `module enable\|disable ` | Reactivate or park a configured workflow, synchronize skills and owned instructions | preserves domain config and content; refuses legacy mixed instruction sections before writes; see [migration](modules.md#instruction-migration) | | `config check` | Validate config, print effective taxonomy summary | | | `config get ` | Read a resolved config value | lets skills query module config | -| `sync` ⚖ | `sync run`, then the `/sync` skill only for what needs judgment | In 0.40.0+, machine mode (`--json` or non-TTY stdout) emits one `{run, agent}` result; human mode prints the report and any agent answer. Hands over to a configured runner for unresolved conflicts, `UNKNOWN` leftovers, or interactive `MEDIA`/`LARGE` leftovers. Without an invocation, preserves the run's exit code (`0` complete, `1` failed, `3` needs judgment); a successful agent invocation exits `0`, an agent failure `2`. On 0.39.0, bare sync always prints text; use `sync run --json` for the mechanical envelope | -| `sync run` | The whole sync without an agent: reconcile stashes, `assess --fix`, `commit`, `pull`, `resolve`, `conclude`, `stash`, `push` (up to three re-pulls on a rejected push), `post-sync`, then a report | `status` `complete` (exit 0), `failed` (exit 1) or `needs-judgment` (exit 3: a conflict is left in progress, or a file holds conflict markers; nothing pushed). Media, unknown files and names that only look like secrets are listed as leftovers, never committed. `--json`: `{status, reason?, steps, leftovers: {unresolved, unknown, media}, judge, timings, report}`, where each `steps` key holds that verb's envelopes in run order | +| `sync` ⚖ | `sync run`, then the `/sync` skill only for what needs judgment | In 0.40.0+, machine mode (`--json` or non-TTY stdout) emits one `{run, agent}` result; human mode prints the report and any agent answer. Hands over to a configured runner for unresolved conflicts or `UNKNOWN` leftovers; media alone never starts it (in 0.45.0+, the report counts it as `Media awaiting review: N` for hygiene review). Without an invocation, preserves the run's exit code (`0` complete, `1` failed, `3` needs judgment); a successful agent invocation exits `0`, an agent failure `2`. On 0.39.0, bare sync always prints text; use `sync run --json` for the mechanical envelope | +| `sync run` | The whole sync without an agent: reconcile stashes, `assess --fix`, `commit`, `pull`, `resolve`, `conclude`, `stash`, `push` (up to three re-pulls on a rejected push), `post-sync`, then a report | `status` `complete` (exit 0), `failed` (exit 1) or `needs-judgment` (exit 3: a conflict is left in progress, or a file holds conflict markers; nothing pushed). Media, unknown files and names that only look like secrets are leftovers, never committed; the report counts media in one line and names no media file (0.45.0+). `--json`: `{status, reason?, steps, leftovers: {unresolved, unknown, media, mediaPending, mediaSetAside}, judge, timings, report}`, where each `steps` key holds that verb's envelopes in run order; `mediaPending` and `mediaSetAside` are additive in 0.45.0 ([contract](integration-contract/cli.md)) | | `sync ` | The steps on their own: `assess [--fix]`, `group`, `commit [--plan \| --plan-file ]`, `stash [--dry-run]`, `pull`, `resolve`, `conflicts`, `conclude`, `push`, `post-sync` | grouping is taxonomy-driven. `assess --fix` ignores artifacts and unmistakable secrets (`.env`, `.env.*`, `*.key`, `*.pem`) and holds other secret-shaped names back as `UNKNOWN`. `assess` classes a binary `MEDIA` and a file over `media.maxTrackedBytes` `LARGE`, each with its `bytes`; see [media.md](media.md). `resolve` merges each conflicted file by the strategy in [configuration.md](configuration.md#merge-strategies). `commit` leaves out, and exits 1 for, any file holding conflict markers | Sync assessment and grouping preserve literal Git paths, including Unicode, @@ -505,3 +505,13 @@ a separately confirmed Undo. Dismiss and Later are review dispositions; shows the confirmed dispositions and deferred backlog counts. The [review contract](integration-contract/package-api.md#human-started-hygiene-review-additive-1027) defines the HTTP operations, durable Action state and check-only restart recovery. + +Since 0.45.0, each media file `brain sync` counts as `Media awaiting review: N` +is a finding here, and the sync report never lists the files. Its card offers +*Persist here*, *Move to a final location…*, *Keep a permanent copy…* (for a +conversation-linked scratch file) and *Delete…*, each previewed before +anything is written and undoable from its receipt while the rollback data is +retained, and *Leave pending*, which skips the file for the rest of the pass +and still counts it. The review's count and the next sync's agree after each +choice and after each Undo. [media.md](media.md#what-brain-kit-does-about-it) +says what each choice leaves for the next sync. diff --git a/docs/media.md b/docs/media.md index dcd6ed6167..2d0b8b9c9d 100644 --- a/docs/media.md +++ b/docs/media.md @@ -85,6 +85,18 @@ A brain usually hits the pain well before those limits. scratch file whole for every request. A file too large for the files route shows no preview at all. After a change, the receipt stays above the next file with *Undo…* while its rollback data is retained. +- **What each choice leaves for the next sync.** *Persist here* adds an + exact `media.track` entry, so the next `brain sync` commits the file where it + is. *Move to a final location…* moves the file and rewrites the notes that + link to it, without adding a rule: the next sync commits it there when + `media.track` already covers that folder, and otherwise counts it again, + under its new path. *Keep a permanent copy…* copies a conversation-linked + scratch file to a tracked place, so the next sync commits the copy only. + *Delete…* removes the file, and *Leave pending* changes nothing. Undo puts + back every byte the change wrote; a sync that ran after it commits none of + them. Git never persists a file that `media.ignore` or `.gitignore` + ignores, or anything in the scratch area: the next sync leaves those files + out, and an original in scratch stays under ordinary scratch pruning. - **The template's `.gitignore`** has a commented media section to start from. ## Git LFS for large masters diff --git a/packages/core/skills/sync/SKILL.md b/packages/core/skills/sync/SKILL.md index e17e7efd73..97b6fa5b16 100644 --- a/packages/core/skills/sync/SKILL.md +++ b/packages/core/skills/sync/SKILL.md @@ -31,7 +31,8 @@ writable terminal. Do not substitute a shell write when a hosted tool refuses. `brain sync run` does the whole sync without you: it cleans and commits local changes, pulls, merges conflicted notes by rule, pushes, and reindexes. **You handle only what it hands back:** -a conflict no rule can merge, a file it could not classify, and media nobody has approved. +a conflict no rule can merge and a file it could not classify. Media is not yours to decide: +`run` leaves it untouched and counts it, and the person decides each file in hygiene review. Brain files are knowledge, so nothing here may silently drop content. ## Autonomy — no plans, no approval @@ -39,24 +40,24 @@ Brain files are knowledge, so nothing here may silently drop content. A sync is frequently unattended: on a schedule, from a container, or through an agent runner with nobody watching. It must therefore complete on its own, and these rules override any default cautiousness. They hold in an interactive session too — every decision below has a defined -conservative default, so there is nothing worth stopping to ask about. **The one exception is -a media decision** (a `MEDIA` or `LARGE` leftover): committing a binary is permanent in git's -history, so it is never a default. Interactively, ask; unattended, leave it untouched and report -it. +conservative default, so there is nothing worth stopping to ask about. Media needs no decision +here either: committing a binary is permanent in git's history, so `run` never commits one, and +the person decides each file in hygiene review, not in a sync. - **Never stop to plan.** Do not enter a plan-and-approve mode, write a plan document, or present a plan and wait for a go. There may be nobody to approve it — a sync that ends with "awaiting approval" is a failed sync. -- **Never ask questions**, except the media decision above. No interactive prompts, no "should I…" - in the output. Take the default, and note what was decided in the final report. +- **Never ask questions.** No interactive prompts, no "should I…" in the output, and never one + about a media file. Take the default, and note what was decided in the final report. - **Conservative default everywhere:** when two resolution options exist, pick the one that keeps more content (union / keep-both over overwrite) and touches less state. Never delete, reset, or rewrite published history to make a problem go away. The CLI may replay unpublished local commits on `origin/main` under `sync.pull`; never resolve a stopped rebase by hand as part of this skill. - **Truly unresolvable items** (binary conflicts, files over 100 KB, a stash entry `run` kept) - and **media nobody has approved** are the only allowed leftovers: leave them untouched and list - them in the final report. The only reasons to stop early are the ones `run` reports as `failed`. + are the only allowed leftovers besides media: leave them untouched and list them in the final + report. Media stays untouched too, reported only as `report`'s count line. The only reasons to + stop early are the ones `run` reports as `failed`. ## Step 1 — Run it @@ -64,8 +65,11 @@ it. brain sync run --json ``` -It prints one envelope: `{ status, reason?, steps, leftovers: { unresolved, unknown, media }, -judge, timings, report }`. Use `run`, never bare `brain sync`: bare sync is the workflow that +It prints one envelope: `{ status, reason?, steps, leftovers: { unresolved, unknown, media, +mediaPending, mediaSetAside }, judge, timings, report }`. `leftovers.media` lists the media +files with their sizes, for tools; `mediaPending` is the count `report` prints as +`Media awaiting review: N`, and `mediaSetAside` counts the files dismissed, snoozed or kept as +a permanent copy in review. Use `run`, never bare `brain sync`: bare sync is the workflow that handed you this work, and it hands its leftovers to an agent. `steps.pull` may report `rebased`, just like `merged` or `fast-forwarded`: remote @@ -75,8 +79,8 @@ Set `sync.pull: "merge"` for merge-only pulls. Existing merge/index state is handled first, and an existing rebase is left for its owner. Conflicts this workflow hands you are always merge conflicts: OURS is local and THEIRS remote. -- `status: "complete"` (exit 0) — pushed and reindexed. If `leftovers.unknown` and - `leftovers.media` are both empty, print `report` and stop. Otherwise go to Step 3. +- `status: "complete"` (exit 0) — pushed and reindexed. If `leftovers.unknown` is empty, print + `report` and stop, whatever media it counts. Otherwise go to Step 3. - `status: "needs-judgment"` (exit 3) — something only you can settle, listed in `leftovers.unresolved`: a conflict no rule could merge (the merge is still in progress and nothing was pushed), or a file holding conflict markers (left uncommitted; the rest may have @@ -147,17 +151,27 @@ sent to the judge and never ignored automatically. Read it. - Something the owner wrote or deliberately kept → commit it: `git commit --only -m "Add : " -- <path>`. -**MEDIA / LARGE** (`leftovers.media`, each with its `bytes`) — a binary (image, PDF, audio, -video, office file) or any file over `media.maxTrackedBytes`. Git keeps every version forever. - -- **Someone is there:** ask before tracking it, and name the size. Offer three answers: - track it (small final media a note uses), ignore it (iterations, renders, exports — add a - `media.ignore` glob in `brain.config.ts` or a `.gitignore` line so the question does not - come back), or keep it with Git LFS (large masters that must travel with the brain). -- **Unattended:** leave it untouched (not staged, not deleted, not ignored) and list it with its - size in the final report as awaiting a decision. -- A `media.track` glob records a standing "track", and a `media.ignore` glob a standing - "ignore"; files they match never come back as MEDIA or LARGE. +**MEDIA / LARGE** — a binary (image, PDF, audio, video, office file) or any file over +`media.maxTrackedBytes`. Git keeps every version forever, so it is never yours to decide, and +never a question: leave every media file untouched (not staged, not deleted, not ignored), +whether someone is there or not. `report` already counts them in one line, +`Media awaiting review: N`, with what is set aside and kept, and names no file; repeat that line, +and do not list the files. Each one is a finding in hygiene review (Actions), where the person +chooses, with a preview and an Undo: + +- **Persist here** — track the file where it is, with an exact `media.track` entry (or a broader + rule they approve with its matches); the next sync commits it. +- **Move to a final location…** — move it and update the notes that link to it; the next sync + commits it there if that folder is tracked. +- **Keep a permanent copy…** — for a file a conversation linked in the scratch area: copy it to a + tracked place, keeping the original where the conversation finds it. +- **Delete…** — remove it. +- **Leave pending** — skip it for the rest of this review; it still counts. + +Git never persists a file `media.ignore` or `.gitignore` ignores, nor anything in the scratch +area: the next sync leaves them uncommitted. A `media.track` glob records a standing "track" and +a `media.ignore` glob a standing "ignore"; files they match never come back as media awaiting +review. If you committed anything in this step, run `brain sync run --json` once more to push it and reindex. @@ -221,7 +235,8 @@ either side added. Report tersely, from `report` and what you did after it: commits created (one line each), conflicts resolved (strategy and a short description each, and which ones you merged by hand), -index status, final sync status, and every leftover with its reason. +index status, final sync status, every leftover with its reason, and `report`'s +`Media awaiting review` line as it stands, without naming a media file. ## Notes From ade7ea8e24793855f1c40eecd2b19ce9f01ebbe0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 12:36:39 +0000 Subject: [PATCH 06/11] test(ui-server): drop an unused import and helper from the media review flow suite Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/ui-server/tests/media-review-flow.test.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts index dba791ce75..38cc508567 100644 --- a/packages/ui-server/tests/media-review-flow.test.ts +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -9,7 +9,7 @@ * and the same selection. Offline and keyless. */ import { afterEach, expect, test } from "bun:test"; -import { readFileSync, writeFileSync } from "node:fs"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { ARGUS, CONFIG, CONFIG_TEXT, COUNTED, HARBOUR, HARBOUR_TO, KEPT, LOOM, LOOM_TO, MEDIA_BYTES, NOTE, NOTE_TEXT, PINS, PINS_TEXT, SHIELD, SKETCH, @@ -50,13 +50,6 @@ function agree(p: Parity, want: Want, selection: "selected" | "kept" = "selected for (const path of [...Object.keys(MEDIA_BYTES), "photos/", "inbox/", ".brain/"]) expect(p.sync.report, "MEDIA_FLOW_REPORT_NO_PATH").not.toContain(path); } -/** The pending card, which must be the media finding at `path`. */ -async function cardFor(f: MediaFlow, path: string) { - const r = await f.until(read => read.action?.status === "pending", "a pending card"); - expect(r.action.hygiene.finding.path, "MEDIA_FLOW_CARD").toBe(path); - expect(r.action.hygiene.finding.category).toBe("media"); - return r.action; -} /** Wait until the server has finished the decision on `cardId` and settled its next selection. */ const settled = (f: MediaFlow, cardId: string) => f.until(r => r.action?.id !== cardId && (r.review.status !== "active" || r.action?.status === "pending"), `card ${cardId} settled`); /** From 426644058915ce7c58c541fcf2ace0a26ed090ea Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 12:46:59 +0000 Subject: [PATCH 07/11] test(ui-server): type the media flow's kept-log comparisons and its worker client config Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/ui-server/tests/fixtures/media-flow-server.ts | 2 +- packages/ui-server/tests/media-review-flow.test.ts | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/fixtures/media-flow-server.ts b/packages/ui-server/tests/fixtures/media-flow-server.ts index ade09351c6..585c06f9ee 100644 --- a/packages/ui-server/tests/fixtures/media-flow-server.ts +++ b/packages/ui-server/tests/fixtures/media-flow-server.ts @@ -66,7 +66,7 @@ const gate = createWriterGate(db, brainPath); let broker: { socketPath: string; close(): void } | undefined; if (execution === "worker") { replaceNativeStartupAcquisitionForFixture(); broker = native.serve(); } const boundary = broker - ? createHostBoundary({ brainPath, exec: {}, dbPath, nativeManager: createNativeBrainManagerClient({ socketPath: broker.socketPath, leasePath: join(state, "native-leases.sqlite"), timeoutMs: NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: NATIVE_MANAGER_MAX_DELTA_BYTES }) }) + ? createHostBoundary({ brainPath, exec: {}, dbPath, nativeManager: createNativeBrainManagerClient({ socketPath: broker.socketPath, timeoutMs: NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: NATIVE_MANAGER_MAX_DELTA_BYTES }) }) : createHostBoundary({ brainPath, exec: {}, dbPath, workerHost: () => ({ ok: false, requirement: "the media flow fixture runs the CLI on the host" }) }); // As the app does at boot: qualify the worker boundary before any admission. const governed = await boundary.prepare(); diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts index 38cc508567..ab56e2376b 100644 --- a/packages/ui-server/tests/media-review-flow.test.ts +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -24,6 +24,9 @@ async function flow(media?: readonly string[], boot: Parameters<MediaFlow["boot" return f; } +/** The bytes with the kept log's set to `value`: Undo of a copy leaves the log, without its entry. */ +const withKept = (bytes: Record<string, string | null>, value: string | null): Record<string, string | null> => ({ ...bytes, [KEPT]: value }); + type Want = { pending: number; dismissed?: number; snoozed?: number; kept?: number }; /** * The CLI and the server report one count, one set-aside split and one @@ -137,7 +140,7 @@ async function actionRoundTrip(f: MediaFlow, path: string, optionId: string, to: expect(undone.body.mediaUndo, "MEDIA_FLOW_UNDONE").toMatchObject({ outcome: "undone" }); // Undo of a kept copy leaves the kept log without its entry (rev 5 §5.7). const keptLog = f.text(KEPT); - expect({ ...f.bytes(), [KEPT]: initial[KEPT] }, "MEDIA_FLOW_UNDO_BYTES").toEqual(initial); + expect(withKept(f.bytes(), initial[KEPT]), "MEDIA_FLOW_UNDO_BYTES").toEqual(initial); if (initial[KEPT] === null && keptLog !== null) expect(keptLog, "MEDIA_FLOW_UNDO_KEPT_ENTRY").not.toContain("### media-"); else expect(f.bytes()[KEPT]).toBe(initial[KEPT]!); // A sync after Undo commits none of it. @@ -253,7 +256,7 @@ test("restart and reconnect mid-pass keep the deferrals, set-aside dispositions expect(finished.review.status, "MEDIA_FLOW_PASS_COMPLETE").toBe("complete"); agree(await f.parity({ sync: true }), { pending: 2, dismissed: 1, snoozed: 1 }); // Nothing was written to the brain's media, config or references. - expect({ ...f.bytes(), [KEPT]: null }, "MEDIA_FLOW_DISPOSITIONS_NO_MEDIA_WRITE").toEqual(before); + expect(withKept(f.bytes(), null), "MEDIA_FLOW_DISPOSITIONS_NO_MEDIA_WRITE").toEqual(before); // The next pass forgets the deferrals and selects both deferred files again. const next = (await f.command("start")).body; @@ -409,7 +412,7 @@ test("in maintenance workers: the review's CLI runs behind the native manager bo agree(await f.parity({ sync: false }), { pending: 1 }); const undone = await f.undo(receipt.media.journalId); expect(undone.body.mediaUndo, "MEDIA_FLOW_WORKER_UNDONE").toMatchObject({ outcome: "undone" }); - expect({ ...f.bytes(), [KEPT]: null }, "MEDIA_FLOW_WORKER_UNDO_BYTES").toEqual(before); + expect(withKept(f.bytes(), null), "MEDIA_FLOW_WORKER_UNDO_BYTES").toEqual(before); agree(await f.parity({ sync: true }), { pending: 1 }, "kept"); await device.close(); }); From ff531e4eeb3648797ecb94f754e93769b8b8f781 Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 13:27:18 +0000 Subject: [PATCH 08/11] test(ui-react): load the media flow only for a flow scene, so other hygiene scenes start and stop as before Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ui-react/tests/fixtures/hygiene-browser-server.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts index 16dd2d08c6..f99621ce57 100644 --- a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts +++ b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts @@ -18,7 +18,7 @@ import { createInboxStream } from "../../../ui-server/src/inbox/stream.js"; import type { AppEnv } from "../../../ui-server/src/app-env.js"; import type { BrainClient } from "../../../ui-server/src/brain/client.js"; import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; -import { createMediaFlow, type MediaFlow } from "../../../ui-server/tests/helpers/media-flow.js"; +import type { MediaFlow } from "../../../ui-server/tests/helpers/media-flow.js"; const scratch = mkdtempSync(join(tmpdir(), "c5-server-")); const db = createUiDb(join(scratch, "ui.sqlite")); @@ -569,6 +569,8 @@ app.post("/fixture", async (c) => { const result: Record<string, unknown> = {}; if (p.mediaFlow) { if (flow) throw new Error("media flow already running"); + // Loaded only for a flow scene: every other scene starts and stops as before. + const { createMediaFlow } = await import("../../../ui-server/tests/helpers/media-flow.js"); flow = createMediaFlow(p.mediaFlow); await flow.boot(); if (p.mediaFlow.start !== false) await flow.command("start"); @@ -607,12 +609,12 @@ const server = Bun.serve({ }, }); console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}` })); -process.on("SIGTERM", async () => { +process.on("SIGTERM", () => { releaseHolds(); stream.close(); server.stop(true); db.close(); rmSync(scratch, { recursive: true, force: true }); - await flow?.close(); - process.exit(0); + if (!flow) process.exit(0); + void flow.close().finally(() => process.exit(0)); }); From b615e9057262b889b69e18fd31e60eb7fbe1a9c7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 13:28:59 +0000 Subject: [PATCH 09/11] test(ui-react): wait for a media receipt within the test's own limit, and sync once across the restart scene Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/browser/hygiene-media-flow.layout.tsx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx index 53aae30205..17ab9a66c4 100644 --- a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx +++ b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx @@ -57,6 +57,8 @@ const HARBOUR = ".brain/scratch/2026-07-12/harbour-dawn.png"; const NOTE = "notes/the-return.md", CONFIG = "brain.config.json", PINS = ".brain/scratch-pins/pins.json", KEPT = "context/hygiene/kept.md"; const TRACK_PLACES = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["places/**"] } }\n'; +/** An applied effect captures, runs the CLI and selects again before its receipt replicates; the test's own limit still bounds it. */ +const RECEIPT_MS = 10_000; const set = async (patch: Record<string, unknown>) => ((await commands.hygieneServer({ op: "set", id: fixture!.id, patch })) as { flow: Flow }).flow; /** Open a socket to the flow's server and route the root's decisions over it, as the app's connection does. */ @@ -151,7 +153,7 @@ async function agree(pending: number, options: { sync?: boolean; selected?: bool async function undo(prefix: RegExp, path: string) { await page.getByRole("button", { name: prefix }).click(); await page.getByRole("button", { name: "Confirm undo", exact: true }).click(); - await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Undone · ${name(path)} is awaiting review again`); + await expect.poll(() => receipt(), { timeout: RECEIPT_MS }).toContain(`Undone · ${name(path)} is awaiting review again`); } test("dark 320: Persist here from the card tracks exactly the file; Undo from the receipt restores the config's bytes", async () => { @@ -162,7 +164,7 @@ test("dark 320: Persist here from the card tracks exactly the file; Undo from th await ready(); expect(commit().textContent).toBe(`Persist ${name(SHIELD)}`); commit().click(); - await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Persisted · ${SHIELD}`); + await expect.poll(() => receipt(), { timeout: RECEIPT_MS }).toContain(`Persisted · ${SHIELD}`); const applied = await set({ flowBytes: [CONFIG] }); expect(applied.texts![CONFIG], "MEDIA_FLOW_BROWSER_PERSIST_CONFIG").toBe('{ "media": { "ignore": [".brain/scratch/**"], "track": ["photos/achilles-shield.png"] } }\n'); expect(applied.bytes![SHIELD]).toBe(before[SHIELD]); @@ -183,7 +185,7 @@ test("light 1280: Move… with its destination moves the file and rewrites its r await ready(); expect(region()!.textContent).toContain(NOTE); commit().click(); - await expect.poll(() => receipt(), { timeout: 5000 }).toContain("Moved"); + await expect.poll(() => receipt(), { timeout: RECEIPT_MS }).toContain("Moved"); const moved = await set({ flowBytes: [NOTE] }); expect(moved.bytes![LOOM], "MEDIA_FLOW_BROWSER_MOVE_SOURCE").toBeNull(); expect(moved.bytes!["places/ithaca/penelope-loom.png"], "MEDIA_FLOW_BROWSER_MOVE_DESTINATION").not.toBeNull(); @@ -200,7 +202,7 @@ test("dark 1280: Delete… removes exactly the file, and Undo from the receipt r await ready(); expect(commit().textContent).toBe(`Delete ${name(SKETCH)}`); commit().click(); - await expect.poll(() => receipt(), { timeout: 5000 }).toContain(`Deleted · ${SKETCH}`); + await expect.poll(() => receipt(), { timeout: RECEIPT_MS }).toContain(`Deleted · ${SKETCH}`); expect((await set({ flowBytes: true })).bytes, "MEDIA_FLOW_BROWSER_DELETED").toEqual({ ...before, [SKETCH]: null }); await agree(1, { sync: false }); await undo(/^Undo: Deleted/, SKETCH); @@ -216,7 +218,7 @@ test("light 320: Keep a permanent copy… of linked scratch copies it and leaves await destination("places/ithaca/harbour-dawn.png"); await ready(); commit().click(); - await expect.poll(() => receipt(), { timeout: 5000 }).toContain("Kept a permanent copy at places/ithaca/harbour-dawn.png · the original stays linked to its conversation"); + await expect.poll(() => receipt(), { timeout: RECEIPT_MS }).toContain("Kept a permanent copy at places/ithaca/harbour-dawn.png · the original stays linked to its conversation"); const kept = await set({ flowBytes: [CONFIG, KEPT] }); expect(kept.bytes!["places/ithaca/harbour-dawn.png"], "MEDIA_FLOW_BROWSER_KEEP_COPY").toBe(before[HARBOUR]); expect(kept.bytes![HARBOUR], "MEDIA_FLOW_BROWSER_KEEP_ORIGINAL").toBe(before[HARBOUR]); @@ -236,7 +238,7 @@ test("dark 320: Leave pending, then the host restarts mid-pass and the device re await page.getByRole("button", { name: "Leave pending", exact: true }).click(); await expect.poll(() => title() !== null && title() !== first).toBe(true); const second = title(); - await agree(2); + await agree(2, { sync: false }); // The host dies; the socket drops. The same state boots again on the same port. await set({ flowRestart: true }); await expect.poll(() => ui!.stores.inbox.getState().online).toBe(false); From b660dcd75666da80d43ec6ed6da04a449ac2aade Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 13:36:12 +0000 Subject: [PATCH 10/11] test(ui-server): read the CLI's eligibility of a kept card only where a scenario checks it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/browser/hygiene-media-flow.layout.tsx | 2 +- .../tests/fixtures/hygiene-browser-server.ts | 2 +- packages/ui-server/tests/helpers/media-flow.ts | 5 +++-- packages/ui-server/tests/media-review-flow.test.ts | 12 ++++++------ 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx index 17ab9a66c4..3f431e4d1e 100644 --- a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx +++ b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx @@ -138,7 +138,7 @@ async function reach(path: string) { async function agree(pending: number, options: { sync?: boolean; selected?: boolean } = {}) { // An Undo's receipt replicates before its request returns; the server's count settles with the request. await expect.poll(async () => ((await set({ flowRead: true })) as Flow & { flowRead: { review: { media?: Counts } } }).flowRead.review.media?.awaitingReview, { timeout: 5000 }).toBe(pending); - const { parity } = await set({ flowParity: options.sync === false ? "cli" : "sync" }); + const { parity } = await set({ flowParity: options.sync === false ? "cli" : "sync", flowEligibility: options.selected === false }); expect(parity!.server.media, "MEDIA_FLOW_BROWSER_SERVER_COUNT").toEqual({ awaitingReview: pending, setAside: 0, kept: 0 }); expect(parity!.cli.media, "MEDIA_FLOW_BROWSER_CLI_COUNT").toEqual(parity!.server.media); if (options.selected !== false) expect(parity!.cli.findingId, "MEDIA_FLOW_BROWSER_SELECTION").toBe(parity!.server.findingId); diff --git a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts index f99621ce57..d8be07aa3b 100644 --- a/packages/ui-react/tests/fixtures/hygiene-browser-server.ts +++ b/packages/ui-react/tests/fixtures/hygiene-browser-server.ts @@ -576,7 +576,7 @@ app.post("/fixture", async (c) => { if (p.mediaFlow.start !== false) await flow.command("start"); } if (flow && p.flowRestart) { const port = Number(new URL(flow.url).port); await flow.kill(); await flow.boot({ port }); } - if (flow && p.flowParity) result.parity = await flow.parity({ sync: p.flowParity === "sync" }); + if (flow && p.flowParity) result.parity = await flow.parity({ sync: p.flowParity === "sync", eligibility: !!p.flowEligibility }); if (flow && p.flowBytes) { result.bytes = flow.bytes(); result.texts = Object.fromEntries((p.flowBytes === true ? [] : p.flowBytes as string[]).map(path => [path, flow!.text(path)])); } if (flow && p.flowRemote) result.remote = flow.remoteFiles(); if (flow && p.flowRead) result.flowRead = await flow.read(); diff --git a/packages/ui-server/tests/helpers/media-flow.ts b/packages/ui-server/tests/helpers/media-flow.ts index c26b41cfb6..3b058b8c3d 100644 --- a/packages/ui-server/tests/helpers/media-flow.ts +++ b/packages/ui-server/tests/helpers/media-flow.ts @@ -218,13 +218,14 @@ export function createMediaFlow(options: { directory?: string; media?: readonly * With `sync`, an ordinary `brain sync` runs too, and commits and pushes * whatever the brain's rules track: use it where the flow has settled. */ - async function parity(options: { sync?: boolean } = {}): Promise<Parity> { + async function parity(options: { sync?: boolean; eligibility?: boolean } = {}): Promise<Parity> { const r = await read(); const deferred = (r.review.deferred ?? []) as Array<{ findingId: string; fingerprint: string }>; const next = cli("hygiene", "--json", "next", ...(deferred.length ? ["--defer", deferred.map(d => `${d.findingId}=${d.fingerprint}`).join(",")] : [])); const synced = options.sync === false ? null : sync(); const finding = r.action?.status === "pending" ? r.action.hygiene.finding : null; - const selected = finding ? cli("hygiene", "--json", "next", "--finding", finding.id, "--dry-run") : null; + // Only a card an Undo did not replace needs it: one more CLI read. + const selected = finding && options.eligibility ? cli("hygiene", "--json", "next", "--finding", finding.id, "--dry-run") : null; return { eligible: selected ? selected.finding?.id === finding.id && selected.finding.fingerprint === finding.fingerprint : null, sync: synced ? { pending: synced.run.leftovers.mediaPending, setAside: synced.run.leftovers.mediaSetAside, report: synced.run.report, agent: synced.agent, status: synced.run.status } : null, diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts index ab56e2376b..64a416fbb6 100644 --- a/packages/ui-server/tests/media-review-flow.test.ts +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -144,7 +144,7 @@ async function actionRoundTrip(f: MediaFlow, path: string, optionId: string, to: if (initial[KEPT] === null && keptLog !== null) expect(keptLog, "MEDIA_FLOW_UNDO_KEPT_ENTRY").not.toContain("### media-"); else expect(f.bytes()[KEPT]).toBe(initial[KEPT]!); // A sync after Undo commits none of it. - const p = await f.parity({ sync: true }); + const p = await f.parity({ sync: true, eligibility: true }); agree(p, want.initial, "kept"); for (const file of [path, ...(to ? [to] : [])]) expect(f.remoteFiles(), "MEDIA_FLOW_UNDO_NOT_COMMITTED").not.toContain(file); @@ -278,7 +278,7 @@ test("capacity: a capture that cannot fit the change journal refuses before any const receipt = (await f.until(r => r.action?.hygiene?.outcome && r.action.hygiene.outcome.status !== "applying", "a refused outcome")).action.hygiene.outcome; expect(receipt, "MEDIA_FLOW_CAPACITY_REFUSED").toMatchObject({ status: "refused", reason: "capture-capacity", media: { outcome: "refused", reason: "capture-capacity" } }); expect(f.bytes(), "MEDIA_FLOW_CAPACITY_NO_WRITE").toEqual(before); - agree(await f.parity({ sync: true }), { pending: 2 }, "kept"); + agree(await f.parity({ sync: true, eligibility: true }), { pending: 2 }, "kept"); await device.close(); }); @@ -299,7 +299,7 @@ test("stale premise: a config edited after the Move preview makes the apply stal expect(outcome, "MEDIA_FLOW_STALE_OUTCOME").toMatchObject({ status: "stale", media: { outcome: "stale", reason: "premise-changed" } }); expect(f.bytes(), "MEDIA_FLOW_STALE_NO_WRITE").toEqual(before); expect(f.text(NOTE), "MEDIA_FLOW_STALE_REFERENCE").toBe(NOTE_TEXT); - agree(await f.parity({ sync: false }), { pending: 2 }, "kept"); + agree(await f.parity({ sync: false, eligibility: true }), { pending: 2 }, "kept"); await device.close(); }); @@ -330,7 +330,7 @@ test("interruption: a host killed between the copy and its kept entry is compens expect(f.bytes(), "MEDIA_FLOW_INTERRUPTED_COPY_COMPENSATED").toEqual(before); const recovered = await f.until(r => r.action?.hygiene?.outcome?.media, "the recovered receipt"); expect(recovered.action.hygiene.outcome, "MEDIA_FLOW_INTERRUPTED_COPY_RECEIPT").toMatchObject({ status: "check_failed", media: { outcome: "compensated", action: "keep-copy" } }); - agree(await f.parity({ sync: true }), { pending: 1 }, "kept"); + agree(await f.parity({ sync: true, eligibility: true }), { pending: 1 }, "kept"); expect(f.remoteFiles(), "MEDIA_FLOW_INTERRUPTED_COPY_UNCOMMITTED").not.toContain(HARBOUR_TO); await device.close().catch(() => {}); }); @@ -350,7 +350,7 @@ test("interruption: a host killed after a Move wrote the file and its reference expect(f.text(NOTE)).toBe(NOTE_TEXT); const recovered = await f.until(r => r.action?.hygiene?.outcome?.media, "the recovered receipt"); expect(recovered.action.hygiene.outcome, "MEDIA_FLOW_INTERRUPTED_MOVE_RECEIPT").toMatchObject({ status: "check_failed", media: { outcome: "compensated", action: "move" } }); - agree(await f.parity({ sync: true }), { pending: 2 }, "kept"); + agree(await f.parity({ sync: true, eligibility: true }), { pending: 2 }, "kept"); expect(f.remoteFiles()).not.toContain(LOOM_TO); await device.close().catch(() => {}); }); @@ -413,6 +413,6 @@ test("in maintenance workers: the review's CLI runs behind the native manager bo const undone = await f.undo(receipt.media.journalId); expect(undone.body.mediaUndo, "MEDIA_FLOW_WORKER_UNDONE").toMatchObject({ outcome: "undone" }); expect(withKept(f.bytes(), null), "MEDIA_FLOW_WORKER_UNDO_BYTES").toEqual(before); - agree(await f.parity({ sync: true }), { pending: 1 }, "kept"); + agree(await f.parity({ sync: true, eligibility: true }), { pending: 1 }, "kept"); await device.close(); }); From 2f3e06c7d2b75db344404b5ffa322cb2f6c707c9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser <alain.schlesser@gmail.com> Date: Sun, 8 Nov 2026 14:54:20 +0000 Subject: [PATCH 11/11] test: run the native-runtime media flow as the app UID, and wait on real selections within each test's limit In the native proof container the suite runs as root, where bwrap cannot map a worker's user namespace (runtime_host run 42489817625). As for the hosted app, the flow's server, CLI and Git now run there as the app UID and own its files. The browser scenes waited on a real CLI selection with expect.poll's one-second default (layout run 42489817625, shard 2); each wait on server work now names its bound, inside the test's unchanged limit (#2783). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../browser/hygiene-media-flow.layout.tsx | 30 ++++++++++--------- .../ui-server/tests/helpers/media-flow.ts | 28 +++++++++++++---- scripts/native-proof/README.md | 3 +- scripts/native-proof/fixture.py | 2 ++ 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx index 3f431e4d1e..39c0bc3d57 100644 --- a/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx +++ b/packages/ui-react/tests/browser/hygiene-media-flow.layout.tsx @@ -59,6 +59,8 @@ const TRACK_PLACES = '{ "media": { "ignore": [".brain/scratch/**"], "track": ["p /** An applied effect captures, runs the CLI and selects again before its receipt replicates; the test's own limit still bounds it. */ const RECEIPT_MS = 10_000; +/** A selection, preview or reconnect waits on the real CLI and server, not on a frame. */ +const SERVER_MS = 5_000; const set = async (patch: Record<string, unknown>) => ((await commands.hygieneServer({ op: "set", id: fixture!.id, patch })) as { flow: Flow }).flow; /** Open a socket to the flow's server and route the root's decisions over it, as the app's connection does. */ @@ -75,7 +77,7 @@ async function connect(root: BrainUiRoot, url: string) { root.connection.handleServerMessage(p.message); }; ws.onclose = () => root.stores.inbox.getState().connectionLost(); - await expect.poll(() => root.stores.inbox.getState().online).toBe(true); + await expect.poll(() => root.stores.inbox.getState().online, { timeout: SERVER_MS }).toBe(true); } async function scene(mediaFlow: { media: string[]; config?: string }, width: number, theme: string) { @@ -104,9 +106,9 @@ async function scene(mediaFlow: { media: string[]; config?: string }, width: num document.body.append(h); const r = renderer = createRoot(h); flushSync(() => r.render(<BrainUiProvider root={root}><ActivityPage /><DesktopPalette /></BrainUiProvider>)); - await expect.poll(() => h.querySelector("[data-hygiene-id]")).not.toBeNull(); + await expect.poll(() => h.querySelector("[data-hygiene-id]"), { timeout: SERVER_MS }).not.toBeNull(); if (width >= 1280) await page.getByRole("button", { name: /^Open finding:/ }).click(); - await expect.poll(() => h.querySelector("[data-hygiene-media]")).not.toBeNull(); + await expect.poll(() => h.querySelector("[data-hygiene-media]"), { timeout: SERVER_MS }).not.toBeNull(); return flow; } const card = () => host!.querySelector<HTMLElement>("[data-hygiene-media]"); @@ -118,8 +120,8 @@ const receipt = () => host!.querySelector<HTMLElement>("[data-media-receipt]")?. const countLine = () => host!.querySelector("[data-hygiene-media-count]")?.textContent ?? null; const name = (path: string) => path.slice(path.lastIndexOf("/") + 1); async function ready() { - await expect.poll(() => status()).toBe("Preview ready"); - await expect.poll(() => region()?.dataset.mediaPreviewRegion).toBe("ready"); + await expect.poll(() => status(), { timeout: SERVER_MS }).toBe("Preview ready"); + await expect.poll(() => region()?.dataset.mediaPreviewRegion, { timeout: SERVER_MS }).toBe("ready"); } async function destination(value: string) { await page.getByRole("textbox", { name: /Destination/ }).fill(value); @@ -130,14 +132,14 @@ async function reach(path: string) { for (let i = 0; i < 4 && title() !== name(path); i++) { const from = title(); await page.getByRole("button", { name: "Leave pending", exact: true }).click(); - await expect.poll(() => title() !== null && title() !== from).toBe(true); + await expect.poll(() => title() !== null && title() !== from, { timeout: SERVER_MS }).toBe(true); } expect(title(), "MEDIA_FLOW_BROWSER_CARD").toBe(name(path)); } /** The server and the CLI agree on count and selection; with a sync, so does `brain sync`, and the card's count line. */ async function agree(pending: number, options: { sync?: boolean; selected?: boolean } = {}) { // An Undo's receipt replicates before its request returns; the server's count settles with the request. - await expect.poll(async () => ((await set({ flowRead: true })) as Flow & { flowRead: { review: { media?: Counts } } }).flowRead.review.media?.awaitingReview, { timeout: 5000 }).toBe(pending); + await expect.poll(async () => ((await set({ flowRead: true })) as Flow & { flowRead: { review: { media?: Counts } } }).flowRead.review.media?.awaitingReview, { timeout: SERVER_MS }).toBe(pending); const { parity } = await set({ flowParity: options.sync === false ? "cli" : "sync", flowEligibility: options.selected === false }); expect(parity!.server.media, "MEDIA_FLOW_BROWSER_SERVER_COUNT").toEqual({ awaitingReview: pending, setAside: 0, kept: 0 }); expect(parity!.cli.media, "MEDIA_FLOW_BROWSER_CLI_COUNT").toEqual(parity!.server.media); @@ -148,7 +150,7 @@ async function agree(pending: number, options: { sync?: boolean; selected?: bool expect(parity!.sync.report).toContain(`Media awaiting review: ${pending}`); for (const path of [LOOM, SHIELD, SKETCH, ARGUS, HARBOUR]) expect(parity!.sync.report).not.toContain(path); } - await expect.poll(() => countLine(), { timeout: 5000 }).toBe(`Media awaiting review: ${pending}`); + await expect.poll(() => countLine(), { timeout: SERVER_MS }).toBe(`Media awaiting review: ${pending}`); } async function undo(prefix: RegExp, path: string) { await page.getByRole("button", { name: prefix }).click(); @@ -179,7 +181,7 @@ test("light 1280: Move… with its destination moves the file and rewrites its r await scene({ media: [LOOM, ARGUS], config: TRACK_PLACES }, 1280, "light"); await reach(LOOM); // The preview loads the file's real bytes from the files route. - await expect.poll(() => card()!.querySelector<HTMLImageElement>("[data-media-frame] img")?.naturalWidth ?? 0).toBe(24); + await expect.poll(() => card()!.querySelector<HTMLImageElement>("[data-media-frame] img")?.naturalWidth ?? 0, { timeout: SERVER_MS }).toBe(24); await page.getByRole("radio", { name: "Move to a final location" }).click(); await destination("places/ithaca/penelope-loom.png"); await ready(); @@ -236,18 +238,18 @@ test("dark 320: Leave pending, then the host restarts mid-pass and the device re const flow = await scene({ media: [SHIELD, ARGUS] }, 320, "dark"); const first = title(); await page.getByRole("button", { name: "Leave pending", exact: true }).click(); - await expect.poll(() => title() !== null && title() !== first).toBe(true); + await expect.poll(() => title() !== null && title() !== first, { timeout: SERVER_MS }).toBe(true); const second = title(); await agree(2, { sync: false }); // The host dies; the socket drops. The same state boots again on the same port. await set({ flowRestart: true }); - await expect.poll(() => ui!.stores.inbox.getState().online).toBe(false); + await expect.poll(() => ui!.stores.inbox.getState().online, { timeout: SERVER_MS }).toBe(false); await connect(ui!, flow.url); - await expect.poll(() => title()).toBe(second); + await expect.poll(() => title(), { timeout: SERVER_MS }).toBe(second); expect((await set({ flowRead: true }) as Flow & { flowRead: { review: { deferred: unknown[] } } }).flowRead.review.deferred, "MEDIA_FLOW_BROWSER_RESTART_DEFERRAL").toHaveLength(1); await agree(2); await page.getByRole("button", { name: "Leave pending", exact: true }).click(); - await expect.poll(() => card()).toBeNull(); - await expect.poll(() => countLine()).toBe("Media awaiting review: 2"); + await expect.poll(() => card(), { timeout: SERVER_MS }).toBeNull(); + await expect.poll(() => countLine(), { timeout: SERVER_MS }).toBe("Media awaiting review: 2"); expect((await set({ flowBytes: true })).bytes![SHIELD]).not.toBeNull(); }); diff --git a/packages/ui-server/tests/helpers/media-flow.ts b/packages/ui-server/tests/helpers/media-flow.ts index 3b058b8c3d..22cc90cf68 100644 --- a/packages/ui-server/tests/helpers/media-flow.ts +++ b/packages/ui-server/tests/helpers/media-flow.ts @@ -76,8 +76,22 @@ export const MEDIA_BYTES: Record<string, Buffer> = { }; export const sha = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex"); +/** + * The native proof container runs this suite as root, where a worker cannot + * map its user namespace. There, as for the hosted app, the server, the CLI + * and Git run as the unprivileged app UID it names, and own the flow's files. + */ +const APP_UID = process.env.BRAIN_MEDIA_FLOW_UID; +if (APP_UID !== undefined && !/^[1-9][0-9]{0,5}$/.test(APP_UID)) throw new Error("BRAIN_MEDIA_FLOW_UID must name an unprivileged UID"); +const asApp = (argv: string[]) => APP_UID ? ["/usr/bin/setpriv", `--reuid=${APP_UID}`, `--regid=${APP_UID}`, "--clear-groups", "--inh-caps=-all", "--ambient-caps=-all", "--no-new-privs", ...argv] : argv; +function own(directory: string) { + if (!APP_UID) return; + const r = Bun.spawnSync(["chown", "-R", `${APP_UID}:${APP_UID}`, directory]); + if (r.exitCode !== 0) throw new Error(`chown ${directory}: ${r.stderr.toString()}`); +} + export function git(cwd: string, ...args: string[]): string { - const r = Bun.spawnSync(["git", "-C", cwd, ...args], { env: gitEnv(cwd) }); + const r = Bun.spawnSync(asApp(["git", "-C", cwd, ...args]), { env: gitEnv(cwd) }); if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`); return r.stdout.toString().trim(); } @@ -102,7 +116,8 @@ export function createMediaFlow(options: { directory?: string; media?: readonly const directory = options.directory ?? mkdtempSync(join(tmpdir(), "brain-media-flow-")); const root = join(directory, "brain"), remote = join(directory, "remote.git"), state = join(directory, "server"); mkdirSync(root); mkdirSync(state); - Bun.spawnSync(["git", "init", "-q", "--bare", "-b", "main", remote], { env: gitEnv(directory) }); + own(directory); + Bun.spawnSync(asApp(["git", "init", "-q", "--bare", "-b", "main", remote]), { env: gitEnv(directory) }); git(root, "init", "-q", "-b", "main"); for (const [k, v] of [["user.name", "Odysseus"], ["user.email", "odysseus@example.test"], ["commit.gpgsign", "false"]]) git(root, "config", k!, v!); put(root, ".gitignore", ".brain/\nbrain.db\nbrain.db-*\n.brain-index/\nnode_modules\n"); @@ -111,19 +126,21 @@ export function createMediaFlow(options: { directory?: string; media?: readonly put(root, "scripts/brain-cli.ts", `await import(${JSON.stringify(CORE_CLI)});\n`); put(root, "notes/ithaca.md", "---\ntitle: Ithaca\ntype: note\ncreated: 2026-07-12\nupdated: " + TODAY + "\ntags: [voyage]\n---\n# Ithaca\n\nThe island Odysseus sails home to.\n"); put(root, NOTE, NOTE_TEXT); + own(directory); git(root, "add", "-A"); git(root, "commit", "-qm", "Odysseus's brain"); git(root, "remote", "add", "origin", remote); git(root, "push", "-q", "-u", "origin", "main"); const present = options.media ?? Object.keys(MEDIA_BYTES); for (const path of present) put(root, path, options.bytes?.[path] ?? MEDIA_BYTES[path]!); // The conversation that linked the scratch file pins it; the pins exist with or without it. put(root, PINS, PINS_TEXT); + const home = join(directory, "home"); mkdirSync(home); + own(directory); let child: ChildProcess | undefined, url = "", stderr = "", hostExecution = "", governed: unknown = null; - const home = join(directory, "home"); mkdirSync(home); const env = { PATH: process.env.PATH ?? "", HOME: home, BRAIN_ROOT: root, GIT_CONFIG_NOSYSTEM: "1", TMPDIR: process.env.TMPDIR ?? tmpdir() }; function cliRun(args: string[]) { - const r = Bun.spawnSync([process.execPath, "--preload", PRELOAD, CORE_CLI, ...args], { cwd: root, env }); + const r = Bun.spawnSync(asApp([process.execPath, "--preload", PRELOAD, CORE_CLI, ...args]), { cwd: root, env }); return { code: r.exitCode ?? -1, stdout: r.stdout.toString(), stderr: r.stderr.toString() }; } /** The real offline CLI; exits 0 and 1 carry JSON. */ @@ -140,7 +157,8 @@ export function createMediaFlow(options: { directory?: string; media?: readonly if (boot.interrupt) writeFileSync(join(state, "interrupt.txt"), boot.interrupt); else rmSync(join(state, "interrupt.txt"), { force: true }); rmSync(join(state, "interrupted.flag"), { force: true }); stderr = ""; - const proc = spawn(process.execPath, ["--preload", PRELOAD, SERVER, root, state, String(boot.port ?? 0), String(boot.capBytes ?? 0), boot.execution ?? "host"], { cwd: REPO, env, stdio: ["ignore", "pipe", "pipe"] }); + const [command, ...argv] = asApp([process.execPath, "--preload", PRELOAD, SERVER, root, state, String(boot.port ?? 0), String(boot.capBytes ?? 0), boot.execution ?? "host"]); + const proc = spawn(command!, argv, { cwd: REPO, env, stdio: ["ignore", "pipe", "pipe"] }); child = proc; proc.stderr!.on("data", b => { stderr += String(b); }); const ready = await new Promise<{ url: string; hostExecution: string; governed: unknown }>((res, reject) => { diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 627ac6bf0c..fbd97fe514 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -13,7 +13,8 @@ HTTP/WebSocket clients. Missing prerequisites fail the selected runtime job. The Claude UID 1000 cell of a default run then runs the media review flow's worker scenario (#2783) in the same container: `packages/ui-server/tests/media-review-flow.test.ts -t "in maintenance workers"`. -It runs every brain command the review server issues in a maintenance worker, +Its server, CLI and Git run as the app UID (`BRAIN_MEDIA_FLOW_UID`), as the +hosted app does. It runs every brain command the review server issues in a maintenance worker, with that suite's test-only copied checkpoints rather than this Btrfs volume. It applies Keep a permanent copy and undoes it, and holds the server, the CLI and `brain sync` to one count. The fixture records the command and its exit diff --git a/scripts/native-proof/fixture.py b/scripts/native-proof/fixture.py index 6af9f14d44..b42121f578 100644 --- a/scripts/native-proof/fixture.py +++ b/scripts/native-proof/fixture.py @@ -147,6 +147,8 @@ def terminate(): run(["/usr/local/bin/bun", "run", "test", str(pathlib.Path(__file__).with_name("hosted-app.test.ts"))], timeout=HOSTED_TIMEOUT) # #2783: the media review flow with every review CLI command in a maintenance worker, in this runtime. if os.environ.get("BRAIN_NATIVE_PROOF_MEDIA_FLOW") == "1": + # As the hosted app does, its server, CLI and Git run as the unprivileged app UID. + os.environ["BRAIN_MEDIA_FLOW_UID"] = APP_UID run(["/usr/local/bin/bun", "run", "test", "/repo/packages/ui-server/tests/media-review-flow.test.ts", "-t", "in maintenance workers"], timeout=120) except BaseException as error: failure = error