Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(GBRA-130 A-24): phantom-redirect resumes after its last examined slug; per-phantom failures reported with code and fix
garrytan2d69b939b5ad
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 3b5848ed16..8507241380 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`. Patterns rows count under the per-source key `dream:patterns:source:<data.source_id or default>` (never their content key), and a patterns child `cancelled` with recorded tokens counts as a death; `patternsBreakerSkip` returns the phase skip (`dream_breaker_tripped`, paid reset `fix`, read-only `--list --json` verify) and `clearPatternsSourceDeaths` resets the source after a completed child (`test/dream-breaker-patterns-source.test.ts`).-- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase.+- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase. GBRA-130 A-24: the pass resumes after the last slug it examined (`slug > cursor`, op_checkpoints op `PHANTOM_REDIRECT_CURSOR_OP` = `phantom-redirect-cursor`, fingerprint the source id, via `rotationAfter`/`saveRotation`), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to `''` after a full pass and stays put on a dry run, an abort or a stop. Phantoms run as `ItemRun` items (`extract_facts.phantom_redirect`): an item error is a `failures[]` entry (`key`, `code`, `message`, `fix` `gbrain dream --phase extract_facts --source <id>`) and the next phantom still runs; a run-scoped error rethrows and `item_failures_systemic` sets `stopped`. `extract-facts.ts` turns them into `phantom_redirect_failed: <slug> (<code>); retry: <fix>` and `phantom_redirect_stopped: …` warnings. Pinned by `test/pathological/a24-phantom-redirect-cursor.test.ts` (both engines).- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 6305a33ae3..62ecfcad3a 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -875,6 +875,8 @@ export async function runExtractFacts(result.phantomsHeldLegacyRows = phantomResult.held_legacy_rows;result.phantomsLockBusy = phantomResult.lock_busy;result.phantomsMorePending = phantomResult.more_pending;+ for (const f of phantomResult.failures) result.warnings.push(`phantom_redirect_failed: ${f.key} (${f.code}); retry: ${f.fix}`);+ if (phantomResult.stopped) result.warnings.push(`phantom_redirect_stopped: ${phantomResult.stopped.message.slice(0, 300)}`);// ── Facts of soft-deleted pages ────────────────────────────────// Deleting a page removes the fence that is the facts' system of record,diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 70ad627524..799679945f 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -63,6 +63,8 @@ import { resolvePageWriteTarget } from '../write-through.ts';import { recordRenameAlias } from '../page-state/rename-alias.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { ItemRun } from '../item-failure.ts';+import { rotationAfter, saveRotation } from '../repair/rotation.ts';/** Tagged-union outcome of a single phantom-redirect attempt. */export type RedirectOutcome =@@ -94,8 +96,12 @@ export interface PhantomPassResult {held_legacy_rows: number;/** True iff the pass was skipped wholesale because the writer lock was busy. */lock_busy: boolean;- /** True iff more phantoms exist than the per-cycle cap — caller surfaces to operator. */+ /** True iff live root pages remain after this pass's window; the next pass resumes after the last slug examined. */more_pending: boolean;+ /** Root pages whose redirect threw an item-scoped error this pass; each is retried when the cursor next reaches it. */+ failures: Array<{ key: string; code: string; message: string; fix: string }>;+ /** Set when most examined pages failed (item_failures_systemic): the pass stopped and its cursor did not move. */+ stopped?: { code: string; message: string };/*** Canonical slugs whose disk fence was merged with phantom rows this pass.* `extract_facts`'s main reconcile loop UNIONs these into its slug set so@@ -113,6 +119,8 @@ export interface PhantomPassResult {}const DEFAULT_PHANTOM_LIMIT = 50;+/** op_checkpoints op (fingerprint: source id) holding the last root slug a pass examined; '' after a pass reaches the end. */+export const PHANTOM_REDIRECT_CURSOR_OP = 'phantom-redirect-cursor';const LOCK_TTL_MINUTES = 5;const LOCK_RETRY_INTERVAL_MS = 1000;const LOCK_TOTAL_TIMEOUT_MS = 30_000;@@ -129,6 +137,7 @@ export function emptyPhantomPassResult(): PhantomPassResult {held_legacy_rows: 0,lock_busy: false,more_pending: false,+ failures: [],touched_canonicals: [],};}@@ -694,42 +703,57 @@ export async function runPhantomRedirectPass(// Find unprefixed phantoms in this source. We over-fetch by 1 so// `more_pending` reflects whether the cap actually clipped work.// #6650: held phantoms are excluded before the cap, so they never use up- // the pass's candidate positions.+ // the pass's candidate positions. GBRA-130 A-24: a root page that is not a+ // phantom stays live, so the pass resumes after the last slug the previous+ // pass examined and wraps at the end; otherwise 50+ root notes would fill+ // the window every run and a phantom sorting after them would never be seen.const held = [...holdSlugs].filter(slug => !slug.includes('/'));result.held_legacy_rows = held.length;+ const after = await rotationAfter(engine, PHANTOM_REDIRECT_CURSOR_OP, sourceId) ?? '';const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pagesWHERE source_id = $1AND deleted_at IS NULLAND slug NOT LIKE '%/%'AND slug <> ALL($3::text[])+ AND slug > $4ORDER BY slug ASCLIMIT $2`,- [sourceId, limit + 1, held],+ [sourceId, limit + 1, held, after],);result.more_pending = rows.length > limit;const touchedSet = new Set<string>();+ const run = new ItemRun('extract_facts.phantom_redirect');+ let examined: string | null = null;for (let i = 0; i < Math.min(rows.length, limit); i++) {// #1972: bail between phantoms on abort (each is independently committed).if (isAborted(signal)) break;const slug = rows[i].slug;const page = await engine.getPage(slug, { sourceId });+ examined = slug;if (!page) continue;result.scanned += 1;let redirectResult: RedirectResult;try {redirectResult = await tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun);+ run.succeed();} catch (err) {- const msg = err instanceof Error ? err.message : String(err);- process.stderr.write(`[gbrain] phantom-redirect: ${slug} failed (${msg}); skipping\n`);+ const { failure, systemic } = run.record(slug, err);+ process.stderr.write(`[gbrain] phantom-redirect: ${slug} failed (${failure.code}: ${failure.message}); skipping\n`);logPhantomEvent({phantom_slug: slug,outcome: 'drift',source_id: sourceId,- reason: `exception: ${msg.slice(0, 200)}`,+ reason: `exception: ${failure.message.slice(0, 200)}`,});+ result.failures.push({ key: slug, code: failure.code, message: failure.message,+ fix: `gbrain dream --phase extract_facts --source ${sourceId}` });+ if (systemic) {+ result.stopped = { code: 'item_failures_systemic', message: systemic.message };+ break;+ }redirectResult = { outcome: 'drift' };}@@ -750,6 +774,8 @@ export async function runPhantomRedirectPass(}}result.touched_canonicals = Array.from(touchedSet).sort();+ const next = !isAborted(signal) && rows.length <= limit ? '' : examined;+ if (!dryRun && !result.stopped && next !== null && next !== after) await saveRotation(engine, PHANTOM_REDIRECT_CURSOR_OP, sourceId, next);} finally {try {await lock.release();diff --git a/test/pathological/a24-phantom-redirect-cursor.test.ts b/test/pathological/a24-phantom-redirect-cursor.test.tsnew file mode 100644index 0000000000..d9c0e129fe--- /dev/null+++ b/test/pathological/a24-phantom-redirect-cursor.test.ts@@ -0,0 +1,163 @@+/**+ * GBRA-130 A-24: the extract_facts phantom-redirect pass+ * (src/core/cycle/phantom-redirect.ts) selected the first `limit` live root+ * pages by slug every run, with no cursor. A root page that is not a phantom+ * (any root note with prose) stays live and unprefixed, so a flat vault with+ * 50+ root notes filled the window forever and a phantom sorting after them+ * was never examined.+ *+ * Authoring gate: (1) protects "every live root page is examined within+ * ceil(n / limit) passes": the pass resumes after the last slug it examined+ * and wraps at the end; one phantom whose redirect throws is reported with a+ * typed code and fix while the rest of the pass continues; a run-scoped error+ * stops the pass and leaves the cursor where it was; a systemic pass (most+ * examined phantoms failing) stops without moving the cursor. (2) Reverting+ * the cursor makes the 60-note case red (`zed` is never redirected);+ * reverting the ItemRun adoption makes the run cases red (the old catch+ * turned a lost connection into `drift` and kept going). (3)+ * test/phantom-redirect.test.ts covers the predicate and single redirects,+ * never more root pages than the cap. (4) No production seam: failures are+ * injected by wrapping the engine.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PHANTOM_REDIRECT_CURSOR_OP, runPhantomRedirectPass } from '../../src/core/cycle/phantom-redirect.ts';+import { rotationAfter } from '../../src/core/repair/rotation.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'default';+const NOTES = Array.from({ length: 60 }, (_, i) => `aaa-note-${String(i + 1).padStart(2, '0')}`);+const fence = (claim: string) => `## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${claim} | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+<!--- gbrain:facts:end -->+`;++interface Brain { engine: BrainEngine; brainDir: string; put(slug: string, body: string, type?: string): Promise<void> }++function brain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-a24-'));+ const brainDir = join(root, 'brain');+ mkdirSync(brainDir, { recursive: true });+ return withEnv({ GBRAIN_AUDIT_DIR: join(root, 'audit'), GBRAIN_HOME: join(root, 'home'), GBRAIN_PHANTOM_REDIRECT_LIMIT: '50' }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ const put = async (slug: string, body: string, type = 'note') => {+ await engine.putPage(slug, { type: type as never, title: slug, compiled_truth: body, timeline: '', frontmatter: {} });+ const file = join(brainDir, `${slug}.md`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ };+ await run({ engine, brainDir, put });+ } finally { await close(); rmSync(root, { recursive: true, force: true }); }+ });+}++async function phantom(b: Brain, slug: string) {+ await b.put(`people/${slug}-example`, `# ${slug}-example\n`, 'person');+ await b.put(slug, `# ${slug}\n\n${fence(`Founded acme-example (${slug})`)}`, 'person');+}++async function live(engine: BrainEngine, slug: string): Promise<boolean> {+ const [row] = await engine.executeRaw<{ deleted: boolean }>('SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);+ return row ? !row.deleted : false;+}++/** The engine whose residue check (the first query a phantom-shaped page reaches) throws `error()` for the listed page ids, or for every page when none are listed. */+function failingResidue(engine: BrainEngine, error: () => unknown, pageIds?: Set<number>): BrainEngine {+ return new Proxy(engine, { get(target, prop) {+ const value = Reflect.get(target, prop);+ if (prop === 'executeRaw' && typeof value === 'function') {+ return (sql: string, params?: unknown[]) => /FROM timeline_entries WHERE page_id/.test(sql) && (!pageIds || pageIds.has(Number(params?.[0])))+ ? Promise.reject(error()) : (value as Function).call(target, sql, params);+ }+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+}++const pass = (engine: BrainEngine, brainDir: string) => runPhantomRedirectPass(engine, brainDir, SOURCE, false);+const cursor = (engine: BrainEngine) => rotationAfter(engine, PHANTOM_REDIRECT_CURSOR_OP, SOURCE);+const contentError = () => Object.assign(new Error('value too long for type character varying(64)'), { code: '22001' });++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-24 phantom redirect: the pass resumes after the last slug it examined (${backend})`, () => {+ test('A-24 item: a phantom after 60 root prose notes is redirected by the second pass, and no note changes', () => brain(databaseUrl, async b => {+ for (const slug of NOTES) await b.put(slug, `# ${slug}\n\nA root note with real prose.\n`);+ await phantom(b, 'zed');+ const before = await snapshotItems(b.engine, SOURCE);++ const first = await expectUnitNotAborted(() => pass(b.engine, b.brainDir));+ const afterFirst = await cursor(b.engine);+ const second = await expectUnitNotAborted(() => pass(b.engine, b.brainDir));+ const afterSecond = await cursor(b.engine);+ const third = await expectUnitNotAborted(() => pass(b.engine, b.brainDir));+ expect({ zedLive: await live(b.engine, 'zed'), redirected: [first.redirected, second.redirected, third.redirected] })+ .toEqual({ zedLive: false, redirected: [0, 1, 0] });+ expect({ scanned: first.scanned, not_phantom: first.not_phantom, more_pending: first.more_pending, cursor: afterFirst })+ .toEqual({ scanned: 50, not_phantom: 50, more_pending: true, cursor: 'aaa-note-50' });+ expect({ scanned: second.scanned, more_pending: second.more_pending, cursor: afterSecond }).toEqual({ scanned: 11, more_pending: false, cursor: '' });+ expect(third.scanned).toBe(50);+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE), { expectProgress: ['zed', 'people/zed-example'], progressFields: ['deleted_at', 'content_hash'] });+ }), 180_000);++ test('A-24 item: a phantom whose redirect throws is reported with its code and fix, and the phantom after it still redirects', () => brain(databaseUrl, async b => {+ for (const slug of NOTES.slice(0, 3)) await b.put(slug, `# ${slug}\n\nA root note with real prose.\n`);+ await phantom(b, 'bbb-bad');+ await phantom(b, 'zed');+ const [bad] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, 'bbb-bad']);+ const before = await snapshotItems(b.engine, SOURCE);++ const result = await expectUnitNotAborted(() => pass(failingResidue(b.engine, contentError, new Set([Number(bad!.id)])), b.brainDir));+ expect(result.redirected).toBe(1);+ expect(result.failures.length).toBe(1);+ expectItemFailure(result.failures[0], { key: 'bbb-bad', code: 'invalid_data', fix: /gbrain dream --phase extract_facts --source default/ });+ expect(await live(b.engine, 'bbb-bad')).toBe(true);+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE), { expectProgress: ['zed', 'people/zed-example'], progressFields: ['deleted_at', 'content_hash'] });+ }), 120_000);++ test('A-24 recovery: once the cause clears, the next pass redirects the phantom that failed', () => brain(databaseUrl, async b => {+ await phantom(b, 'bbb-bad');+ const [bad] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, 'bbb-bad']);+ const failed = await expectUnitNotAborted(() => pass(failingResidue(b.engine, contentError, new Set([Number(bad!.id)])), b.brainDir));+ expect(failed.failures.map(f => f.key)).toEqual(['bbb-bad']);+ const before = await snapshotItems(b.engine, SOURCE);+ const result = await expectUnitNotAborted(() => pass(b.engine, b.brainDir));+ expect({ redirected: result.redirected, failures: result.failures }).toEqual({ redirected: 1, failures: [] });+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE), { expectProgress: ['bbb-bad', 'people/bbb-bad-example'], progressFields: ['deleted_at', 'content_hash'] });+ }), 120_000);++ for (const { name, error } of runScopedErrors()) {+ test(`A-24 run: a run-scoped ${name} at a phantom stops the pass and leaves the cursor where it was`, () => brain(databaseUrl, async b => {+ for (const slug of NOTES.slice(0, 3)) await b.put(slug, `# ${slug}\n\nA root note with real prose.\n`);+ await phantom(b, 'bbb-bad');+ await phantom(b, 'zed');+ const before = await snapshotItems(b.engine, SOURCE);+ const injected = error();+ let thrown: unknown;+ await pass(failingResidue(b.engine, () => injected), b.brainDir).catch(e => { thrown = e; });+ expect(thrown).toBe(injected);+ expect(await cursor(b.engine)).toBeNull();+ expect(await live(b.engine, 'zed')).toBe(true);+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE));+ }), 120_000);+ }++ test('A-24 breaker: when most examined phantoms fail the pass stops item_failures_systemic and the cursor does not move', () => brain(databaseUrl, async b => {+ for (const slug of ['p1', 'p2', 'p3', 'p4', 'p5', 'p6']) await phantom(b, slug);+ const before = await snapshotItems(b.engine, SOURCE);+ const result = await expectUnitNotAborted(() => pass(failingResidue(b.engine, contentError), b.brainDir));+ expect(result.stopped?.code).toBe('item_failures_systemic');+ expect(result.redirected).toBe(0);+ expect(await cursor(b.engine)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE));+ }), 120_000);+ });+}