Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6543): doctor truth, head blocker probe, implied --no-pull (PR 2: B2 C1 C2 D1 D2 D3 D5 F1)
garrytan8ac19f10b7da
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex f49588dd3a..42b3a003f2 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1377,6 +1377,18 @@ More: [docs/guides/bootstrap.md#harness_hook_duplicates](../../docs/guides/bootsMore: [docs/guides/bootstrap.md#harness_hook_unowned](../../docs/guides/bootstrap.md#harness_hook_unowned)+### head_blocked++<a id="head_blocked"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The queued write at the head of a managed source cannot be claimed by any consumer, and its blocker needs an operator; a managed sync drain stops `drain_stalled` with `cause: head_blocked` and `blocked_by` names the predicate. | #6543: the drain used to wait the whole no-progress window and print a constant `claimable here: no`. The head probe evaluates each predicate of the claim query for the head itself. Only intervention-required blockers stop the drain, after one governor tick of confirmation: a refresh fence no refresh process holds, or a running request ahead held by a process that reports restart_required. Live blockers (a foreground publication, a lapsed lease, a refresh or recovery making progress) keep the progress-aware wait. | Run next.fix: for refresh_fence resume the refresh (gbrain sources refresh <source> --resume); for zombie_publication restart the named gbrain process on the brain host. Then rerun the same sync. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --json` | 1 | no |++Reasons: `refresh_fence`, `zombie_publication`.++More: [docs/guides/write-refusals.md#head-blocked](../../docs/guides/write-refusals.md#head-blocked)+### held_failed<a id="held_failed"></a>diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex b70805e33f..54e67e4d8a 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -23,9 +23,13 @@ command drains the whole backlog:gbrain sync --source <id> --no-pull --json```-`--no-pull` is required on managed brains: the checkout is fast-forwarded by+Managed sync never pulls: the checkout is fast-forwarded by`gbrain sources refresh <id>`, never by sync. Sync then catches the index up-to whatever the checkout holds.+to whatever the checkout holds. The CLI implies `--no-pull` on a managed brain+(single source, `--all` and serve-delegated runs alike) and prints one stderr+line naming `gbrain sources refresh <id>`; `--json` stdout stays one document.+An explicit pull through the library or MCP (`sync_brain` with+`no_pull: false`) still refuses with `writer_coordinator_required`.The run prints one line before the first write and a progress line aboutevery 10 seconds on stderr:@@ -485,7 +489,7 @@ vars — incident-time escape hatches, not everyday knobs.`--include-gitignored` for those).8. **A managed brain pulls only through `gbrain sources refresh`.** Managed- sync refuses to pull (`gbrain sync` needs `--no-pull`) and a cycle asked to+ sync never pulls (the CLI implies `--no-pull`) and a cycle asked topull syncs the checkout as it is, because a Git merge rewrites files thataccepted writes may be publishing into. To take new upstream commits, runon the owner host:diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 0d60532d80..2abced10cc 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1438,7 +1438,20 @@ with "still pending publication" or "the canonical writer ... is held", checkEvery applying kind waits for each publication with the CLI write wait: `--wait <seconds>`, then`GBRAIN_WRITE_WAIT_MS`, then `persistence.write_wait_ms`, else 30 seconds. That includes the doctor-remediation run and the replay of a restore a previous `extractor-facts` apply left pending. A malformed+remediation run and the replay of a restore a previous `extractor-facts` apply left pending.++A write that is accepted but still pending when its wait ends does not stop the run while a consumer+on this host is publishing (#6543). The run keeps the receipt, leaves its saved position before that+item, and admits the remaining items without a per-item wait. At most half the principal's+outstanding-request cap (`persistence.limits.principal_outstanding`, at most 64) stays unresolved at+once; past that the run waits for earlier receipts first. All receipts settle against one shared wait:+the run gives up only when nothing it admitted has published for the write wait. A preview-bound kind+(`--expect`) settles every earlier receipt before its last item, so its approved set is kept until+every admitted item is accounted for. When the run still stops, `pending` lists the receipts (item and+`request_id`) and rerunning the same apply command replays them; a crash leaves the position before+the first unresolved receipt, so the rerun does the same. `--wait 0` waits for nothing: it admits what+it can and stops with `pending`. With no live consumer on this host, or one that reports+`restart_required`, the run stops at the first pending write as before and its `fix` names the owner. A malformed`GBRAIN_WRITE_WAIT_MS` refuses the apply with `invalid_write_wait` before anything is written; a previewnever reads it.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 22f98dc7cb..7134668384 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -473,6 +473,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| <a id="preparation_systemic"></a><a id="drain-preparation-systemic"></a>`preparation_systemic` | `preparation_systemic` | `blocked` | The run's breaker tripped: more `preparation_stalled` receipts than a source should hold (the `sync.hold_escalate_count` / `sync.hold_escalate_pct` rule over this run's screened imports) or five stalled entries in a row with no page committed between them. The run stopped with one diagnostic instead of holding every file: the write owner, not the files, is the likely cause. `breaker` carries the rule, the counts, the last step and the fix; exit 1. | `gbrain sources writer status --source <source> --json`, fix what it names or upgrade gbrain, then rerun the same sync: it re-freezes the stopped entry under a fresh request and schedules the files this run held for a re-screen. || <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. || <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest, with or without `--retry-failed`. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |+| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock) or `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, `effect_recovery`, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |## Unbound sources on Postgresdiff --git a/llms-full.txt b/llms-full.txtindex 4ae3aad621..eeb6bd8a1e 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6352,9 +6352,13 @@ command drains the whole backlog:gbrain sync --source <id> --no-pull --json```-`--no-pull` is required on managed brains: the checkout is fast-forwarded by+Managed sync never pulls: the checkout is fast-forwarded by`gbrain sources refresh <id>`, never by sync. Sync then catches the index up-to whatever the checkout holds.+to whatever the checkout holds. The CLI implies `--no-pull` on a managed brain+(single source, `--all` and serve-delegated runs alike) and prints one stderr+line naming `gbrain sources refresh <id>`; `--json` stdout stays one document.+An explicit pull through the library or MCP (`sync_brain` with+`no_pull: false`) still refuses with `writer_coordinator_required`.The run prints one line before the first write and a progress line aboutevery 10 seconds on stderr:@@ -6814,7 +6818,7 @@ vars — incident-time escape hatches, not everyday knobs.`--include-gitignored` for those).8. **A managed brain pulls only through `gbrain sources refresh`.** Managed- sync refuses to pull (`gbrain sync` needs `--no-pull`) and a cycle asked to+ sync never pulls (the CLI implies `--no-pull`) and a cycle asked topull syncs the checkout as it is, because a Git merge rewrites files thataccepted writes may be publishing into. To take new upstream commits, runon the owner host:diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 5e7683d733..ce1f95e5eb 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -320,6 +320,7 @@ test/scripts/test-env-opt-ins-guard.test.ts check-test-env-opt-ins 5 readFileSyntest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 7 readFileSynctest/search/graph-signals-wire-integration.test.ts v0.40.4 — source-grep regression guard 1 source-surface-helper+test/serve-behavior-notice-6543.test.ts (file-level) 3 readFileSynctest/serve-http-admin-route-guard.test.ts (file-level) 6 readFileSynctest/serve-http-github-webhook.test.ts handler wiring (source pin) 1 source-surface-helpertest/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 source-surface-helperdiff --git a/src/commands/doctor/checks/frontmatter-keys.ts b/src/commands/doctor/checks/frontmatter-keys.tsindex 7ef487a12b..36aa1c3a9c 100644--- a/src/commands/doctor/checks/frontmatter-keys.ts+++ b/src/commands/doctor/checks/frontmatter-keys.ts@@ -18,13 +18,13 @@ export async function staleFrontmatterKeysCheck(engine: BrainEngine, sourceIds?:const count = counts.reduce((sum, row) => sum + row.n, 0);const details = { count, sources: counts, source_ids: counts.map(row => row.source_id), repair: 'frontmatter-keys', docs };if (!count) return { name: 'stale_frontmatter_keys', status: 'ok', details, message: 'No stored frontmatter carries a parser-reserved key (type, title, tags, slug).' };- const first = counts[0].source_id;+ const preview = ['gbrain', 'repair', 'frontmatter-keys', ...(counts.length === 1 ? ['--source', counts[0].source_id] : [])];return { name: 'stale_frontmatter_keys', status: 'warn', details,message: `${count} page(s) store a parser-reserved key (type, title, tags, slug) inside their frontmatter, left by an older import: `- + `${counts.map(row => `${row.source_id}: ${row.n}`).join(', ')}. Writes compare and render around these keys since v0.60.176.0, so this is hygiene, not a wedge. `- + `Preview the sweep on the brain host: gbrain repair frontmatter-keys --source ${first} — it lists the pages and prints the apply command; each swept page `+ + `${counts.map(row => `${row.source_id}: ${row.n}`).join(', ')}. Writes compare and render around these keys since v0.60.177.0, so this is hygiene, not a wedge. `+ + `Preview the sweep on the brain host: ${preview.join(' ')}${counts.length > 1 ? ` (every source; one at a time: ${counts.map(row => `gbrain repair frontmatter-keys --source ${row.source_id}`).join(', ')})` : ''} — it lists the pages and prints the apply command; each swept page `+ `advances its knowledge_revision once (a client holding an older revision gets one revision_conflict).`,- fix: agentFix(['gbrain', 'repair', 'frontmatter-keys', '--source', first],+ fix: agentFix(preview,'Read-only preview: lists the pages carrying reserved keys, saves the set under a hash and prints the apply command.', 'stale_frontmatter_keys', { docs }) };} catch (error) {return checkError('stale_frontmatter_keys', 'count stored frontmatter reserved keys', error, { details: { count: 'unknown', docs } });diff --git a/src/commands/doctor/checks/queue-assets.ts b/src/commands/doctor/checks/queue-assets.tsindex a58d352d43..7a33549593 100644--- a/src/commands/doctor/checks/queue-assets.ts+++ b/src/commands/doctor/checks/queue-assets.ts@@ -161,57 +161,79 @@ async function runImageAssets(ctx: DoctorContext): Promise<Check[]> {if (engine) {progress.heartbeat('image_assets');try {- const rows = await engine.executeRaw<{ storage_path: string; source_local_path: string | null; metadata: unknown }>(- `SELECT f.storage_path, f.metadata, s.local_path AS source_local_path FROM files f LEFT JOIN sources s ON s.id = COALESCE(f.source_id, 'default') WHERE f.mime_type LIKE 'image/%' LIMIT 1000`+ const rows = await engine.executeRaw<{ storage_path: string; source_local_path: string | null; page_source_path: string | null; metadata: unknown }>(+ `SELECT f.storage_path, f.metadata, s.local_path AS source_local_path, p.source_path AS page_source_path FROM files f+ LEFT JOIN sources s ON s.id = COALESCE(f.source_id, 'default') LEFT JOIN pages p ON p.id = f.page_id+ WHERE f.mime_type LIKE 'image/%' ORDER BY f.id LIMIT 1000`);let vanished = 0;let foreign = 0;let remote = 0;+ let unrooted = 0;+ let caseOnly = 0;const vanishedPaths: string[] = [];+ const ambiguousPaths: string[] = [];const fs = await import('node:fs');+ const { join } = await import('node:path');const { resolveImageAssetPath, imageAssetStorageLane } = await import('../../doctor-asset-paths.ts');+ const { resolveRecordedImageFile } = await import('../../../core/image-asset-resolver.ts');+ const listings = new Map<string, string[] | null>();// storage_path is repo-relative for sync-ingested assets. Prefer the- // owning source's root; sync.repo_path is only a legacy fallback.- const repoRoot = (await engine.getConfig('sync.repo_path')) ?? process.cwd();+ // owning source's root; sync.repo_path is only a legacy fallback, and a+ // row with neither is not checkable here (never joined onto the cwd).+ const repoRoot = await engine.getConfig('sync.repo_path');for (const r of rows) {// #4910: an explicit non-git lane (supabase/s3/local backend) means// storage_path is a bucket key, never a source-relative file. Only// `gbrain files verify` can probe those; unmarked rows keep the stat.if (imageAssetStorageLane(r.metadata) === 'backend') { remote++; continue; }+ const root = r.source_local_path ?? repoRoot;+ if (!root) { unrooted++; continue; }// #1835: Windows drive paths (D:/…) translate to the WSL automount// (/mnt/d/…) under WSL, and are SKIPPED (not "missing") on hosts// where they cannot exist (macOS / plain Linux) — never joined onto// repoRoot, which produced a false "restore from git" WARN.- const resolved = resolveImageAssetPath(r.storage_path, r.source_local_path, repoRoot);+ const resolved = resolveImageAssetPath(r.storage_path, root, root);if (resolved.abs === null) {foreign++;continue;}- try {- fs.statSync(resolved.abs);- } catch {- vanished++;- if (vanishedPaths.length < 5) vanishedPaths.push(r.storage_path);+ // #6543 D3: a relative path resolves through the shared case-insensitive resolver (exact first; the page's+ // recorded source_path is a second candidate); an absolute or translated path is stat'ed as it is.+ if (resolved.abs !== join(root, r.storage_path)) {+ try { fs.statSync(resolved.abs); } catch { vanished++; if (vanishedPaths.length < 5) vanishedPaths.push(r.storage_path); }+ continue;}+ const located = resolveRecordedImageFile(root, [r.storage_path, r.page_source_path], listings);+ if (located.status === 'found') { if (located.caseMismatch) caseOnly++; continue; }+ if (located.status === 'ambiguous') { if (ambiguousPaths.length < 5) ambiguousPaths.push(`${r.storage_path} (${located.matches.join(' | ')})`); continue; }+ vanished++;+ if (vanishedPaths.length < 5) vanishedPaths.push(r.storage_path);}- const checked = rows.length - foreign - remote;+ const ambiguous = ambiguousPaths.length;+ const checked = rows.length - foreign - remote - unrooted;const foreignNote = (foreign > 0? ` (${foreign} Windows-drive path(s) skipped — not resolvable on this platform)`: '') + (remote > 0? ` (${remote} storage-backend object(s) not checked locally — run \`gbrain files verify\`)`- : '');+ : '') + (unrooted > 0+ ? ` (${unrooted} image(s) not checkable here: their source has no local path)`+ : '') + (caseOnly > 0+ ? ` (${caseOnly} found under a different letter case than recorded)`+ : '') + (rows.length === 1000 ? ' (the first 1000 image rows by id were checked)' : '');if (rows.length === 0) {checks.push({ name: 'image_assets', status: 'ok', message: 'No image assets indexed yet' });} else if (checked === 0) {checks.push({ name: 'image_assets', status: 'ok', message: `No local image assets to check${foreignNote}` });- } else if (vanished === 0) {+ } else if (vanished === 0 && ambiguous === 0) {checks.push({ name: 'image_assets', status: 'ok', message: `${checked} image(s) all present on disk${foreignNote}` });} else {checks.push({name: 'image_assets',status: 'warn',- message: `${vanished} of ${checked} image(s) missing from disk (e.g. ${vanishedPaths.join(', ')})${foreignNote}. ` +- `Fix: restore from git, or \`gbrain sync --skip-failed\` to acknowledge.`,+ message: (vanished > 0 ? `${vanished} of ${checked} image(s) missing from disk (e.g. ${vanishedPaths.join(', ')}). ` : '')+ + (ambiguous > 0 ? `${ambiguous} image path(s) are ambiguous: more than one file matches when letter case is ignored (${ambiguousPaths.join(', ')}); rename one so the recorded path names a single file. ` : '')+ + `${foreignNote.trim()}${foreignNote ? ' ' : ''}Fix: restore missing files from git, or delete the pages whose file is gone.`,});}} catch {diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.tsindex 9d67e8acee..3d0f75ee1b 100644--- a/src/commands/doctor/checks/sync-failures.ts+++ b/src/commands/doctor/checks/sync-failures.ts@@ -6,6 +6,7 @@ import { resolveHoursEnv } from '../../../core/env-number.ts';import { makeRemediationStep } from '../../../core/remediation-step.ts';import { classifyManagedSyncOrphans } from '../../../core/persistence/managed-sync-orphans.ts';import { readManagedMode } from '../../../core/persistence/ownership.ts';+import { legacyLedgerNote } from '../../../core/persistence/legacy-sync-failures.ts';export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean } = {}): Promise<Check | null> {// #5452: sync refuses an archived source, so its failures cannot be cleared and are not a live health signal.@@ -44,7 +45,8 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourconst recovery = requiresManagedRetry? `${resumable.length || !orphans.length ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.` : ''}${orphanNote}`.trim(): "Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.";- return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}`,+ const legacyNote = managedBrain ? legacyLedgerNote(unresolvedLegacy) : '';+ return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}${legacyNote}`,remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length ? { details: { orphans } } : {}),...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.` }) };}diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 99cbbaac7c..97200a791a 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -246,6 +246,7 @@ export async function runServe(console.error(`[gbrain serve] ignoring GBRAIN_SURFACE="${resolved.invalidEnv}" (use verbs | starter | full)`);}console.error(`[gbrain serve] surface=${surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);+ void (await import('../core/serve-behavior-notice.ts')).logServeBehaviorNotice(engine, loadConfig());// #6383: the pool stall line (Postgres only; the watch reports nothing for an engine without pool numbers).if (engine.kind === 'postgres') new PoolStallWatch(engine, (line) => console.error(line)).start();// #4768: stdio read-only access ceiling. HTTP refuses it: per-token grantsdiff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 1d5138aceb..e32a37afff 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -99,9 +99,10 @@ Options:checkpoint; unchanged pages are not admitted again.--watch Re-sync continuously on an interval.--interval N Watch-mode interval in seconds (default 60).- --no-pull Skip 'git pull' before the sync. Required on managed- brains: 'gbrain sources refresh <id>' moves the- checkout, and sync catches the index up to it.+ --no-pull Skip 'git pull' before the sync. Implied on managed+ brains, which never pull during sync: 'gbrain sources+ refresh <id>' moves the checkout, and sync catches the+ index up to it.--no-bulk Managed Postgres sync: publish one page per transactioninstead of bulk groups (each page keeps its own writerequest either way). Persist withdiff --git a/src/commands/sync/managed-no-pull.ts b/src/commands/sync/managed-no-pull.tsnew file mode 100644index 0000000000..89879e3474--- /dev/null+++ b/src/commands/sync/managed-no-pull.ts@@ -0,0 +1,15 @@+import type { BrainEngine } from '../../core/engine.ts';+import { readManagedMode } from '../../core/persistence/ownership.ts';++/**+ * #6543 C1: managed sync never runs `git pull` (its only use of `noPull` was the refusal), so a CLI sync on a managed+ * brain implies `--no-pull` and says once, on stderr, how to take fresh Git content. Set before the single-source,+ * `--all` and serve-delegated paths read the flags. An unreadable managed state implies nothing; the sync then refuses+ * with its own error. The library and MCP refusal of an explicit pull stays in `resolveManagedSyncContext`.+ */+export async function implyManagedNoPull(engine: BrainEngine, flags: { noPull: boolean; dryRun: boolean }, sourceId: string | null): Promise<void> {+ if (flags.noPull || flags.dryRun || !await readManagedMode(engine).catch(() => false)) return;+ flags.noPull = true;+ process.stderr.write(`[sync] managed brain: importing ${sourceId ? `source ${sourceId}'s` : "each source's"} checkout at its local HEAD without git pull (--no-pull is implied); `+ + `to fast-forward from the remote first, run gbrain sources refresh ${sourceId ?? '<id>'}\n`);+}diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex da0f4ad571..7ba1ff0503 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -121,11 +121,12 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}}-/** #6288: a successful managed sync clears this source's recorded failures its imported commit already settles; best effort. */+/** #6288: a successful managed sync clears this source's recorded failures its imported commit already settles (#6543 D5: legacy ledger rows too); best effort. */async function clearSettledFailures(engine: BrainEngine, sourceId: string): Promise<void> {try {const { clearSettledManagedSyncFailures, readManagedSyncImported } = await import('../../core/persistence/sync-failures.ts');const imported = await readManagedSyncImported(engine, sourceId);if (imported) await clearSettledManagedSyncFailures(engine, imported);+ if (imported) await (await import('../../core/persistence/legacy-sync-failures.ts')).settleLegacySyncFailures(engine, imported);} catch { }}diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex b3d8aa5058..92a9f06475 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -24,6 +24,8 @@ import { composeAbortSignals } from '../../core/sync-reconcile.ts';import { acknowledgeFailures, unacknowledgedSyncFailures } from '../../core/sync.ts';import type { SyncResult, SyncOpts } from '../sync.ts';import { printSyncHelp, parseSyncFlags, parseSyncFanoutFlags } from './args.ts';+import { implyManagedNoPull } from './managed-no-pull.ts';+import { legacyLedgerRows } from '../../core/persistence/legacy-sync-failures.ts';import type { SyncFlags, SyncFanoutFlags } from './args.ts';import { manageGitignoreAtGitRoot } from './gitignore.ts';import { partitionMissingPathSources } from './missing-path.ts';@@ -103,6 +105,7 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {const cli = await resolveCliSyncSource(engine, args, { repoPath, syncAll, dryRun, jsonOut, noEmbed });const { sourceId, companyPolicy, embeddingCredentialError } = cli;noEmbed = cli.noEmbed;+ await implyManagedNoPull(engine, flags, syncAll ? null : sourceId);// --skip-failed: acknowledge pre-existing unacked failures BEFORE the sync// runs, not only ones the current run produces. Without this, the common@@ -832,8 +835,10 @@ async function runSingleSourceSync(for (const command of new Set(other.map(f => managedSyncRetryCommand(f)))) slog(` ${command}`);}}+ const legacyRows = managedBrain ? legacyLedgerRows(sourceId).length : 0;+ if (legacyRows) slog(`${legacyRows} legacy ledger row(s) of this source were recorded by the pre-managed sync and are not retried by a managed sync; this run settles every one whose file it imports.`);if (failures.length === 0) {- slog('No local ledger entries; checking the durable sync cursor for unfinished or failed writes.');+ slog(legacyRows ? 'No managed sync failures recorded; checking the durable sync cursor for unfinished or failed writes.' : 'No local ledger entries; checking the durable sync cursor for unfinished or failed writes.');} else {slog(`Retrying ${failures.length} previously-failed file(s)...`);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 215c8b656f..2b6e7997c2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -473,6 +473,15 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },+ // #6543 fix wave PR 2 (GBRA-84). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps these rows to the release (0.60.186.0 placeholder) at the merge slot.+ { since: '0.60.184.0', text: 'On a managed brain, `gbrain sync` (one source, `--all`, and a sync handed to `gbrain serve`) now implies `--no-pull` and prints one stderr line naming `gbrain sources refresh <id>` for taking upstream commits, instead of refusing with `writer_coordinator_required` until `--no-pull` was typed. Nothing changes on stdout or in `--json`; `--dry-run` and the library/MCP refusal of an explicit pull are unchanged.' },+ { since: '0.60.184.0', text: 'A managed sync drain whose queued head no consumer can claim now stops within one governor tick with `drain_stalled`, `cause: head_blocked`, when the blocker needs an operator (a refresh fence no refresh process holds: `next.fix` is `gbrain sources refresh <id> --resume`; a running request ahead held by a process that reports `restart_required`: restart it), instead of waiting the 5-10 minute no-progress window. `drain.stall` gains `blocked_by` and `consumer`, the stall line prints `consumer=` and `blocked_by=`, and `claimable here` is read for the head itself (`unknown` when the read fails; it used to print a constant `no`). `gbrain sources writer status` names the blocker of each queued head (`blocked_by`, `claimable_here`) and adds `cancel_command` only when this caller may cancel the blocking request.' },+ { since: '0.60.184.0', text: '`gbrain repair <kind> --apply` no longer stops at the first write that is accepted but still pending publication while a consumer on this host is publishing: it keeps the receipt (the saved position stays before it), admits the remaining items without a per-item publication wait (at most half the principal outstanding-request cap unresolved at once) and settles them against one shared wait (the write wait with nothing publishing). A run that still stops lists the receipts in `pending` and the same command resumes; `--wait 0` still waits for nothing. With no live consumer, or one that reports `restart_required`, the run stops at the first pending write as before and names the owner.' },+ { since: '0.60.184.0', text: '`[persistence] phase=` log lines about one write request now carry `request_id`, `operation`, `source`, `slug`, `principal` and `elapsed_ms`, and their 30-second repeat suppression is per request: two requests failing the same phase log two lines.' },+ { since: '0.60.184.0', text: '`gbrain serve` now logs the behavior changes this brain has not been told about once per process at startup, on stderr. It reads the notice state without marking it delivered, so the CLI, stdio and HTTP notices still show once each.' },+ { since: '0.60.184.0', text: 'Importing an image no longer writes `type` or `title` into its frontmatter (the keys `gbrain repair frontmatter-keys` strips since 0.60.177.0). Doctor `stale_frontmatter_keys` names 0.60.177.0 and, on a brain with several sources, its fix is the all-sources `gbrain repair frontmatter-keys`, with the per-source commands listed.' },+ { since: '0.60.184.0', text: '`gbrain embed --stale --images` and doctor `image_assets` find an image whose recorded path differs from the file on disk only in letter case (an exact match still wins), import it under the real-case path, and refuse a case-fold match that is ambiguous or resolves outside the source root instead of importing or counting it. `image_assets` reports case-only, ambiguous and unrooted counts.' },+ { since: '0.60.184.0', text: 'On a managed brain, a successful `gbrain sync --source <id>` settles legacy rows the pre-managed sync left in `sync-failures.jsonl` one at a time (the imported commit holds the file and a live page claims it, or the file is gone and no page claims it); rows on an unknown commit, sentinel rows, held files and files it did not index stay. Doctor `sync_failures` says how many unresolved rows are legacy and which command settles them, and `gbrain sync --retry-failed` names them instead of saying the ledger is empty.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0c8dad8811..9a87e46893 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.tsindex 710a90bc20..3bb5037f17 100644--- a/src/core/embed-stale-images.ts+++ b/src/core/embed-stale-images.ts@@ -14,18 +14,20 @@* (`importManagedFile`, the same coordinated path `gbrain import` takes) instead* of the legacy writer, which a managed brain refuses. A page whose* `source_path` was never recorded is looked up by its slug (an image slug is- * its repo-relative path) and the import records `source_path`. A sweep that+ * its repo-relative path) and the import records `source_path`. #6543 D3: the+ * recorded path resolves through the shared case-insensitive resolver+ * (`image-asset-resolver.ts`), so a lower-cased slug finds `IMG_1453.PNG` and the+ * import records the real-case path; two case-fold matches refuse. A sweep that* finds no file for any candidate is a failure (non-zero exit) that names the* paths it tried; `missing_samples` names them on a partial sweep too. Plain* `embed --stale` runs this sweep first on a multimodal install* (`runStaleImageSweepFirst`), inside the run's cost cap.*/-import { existsSync } from 'fs';import { execFileSync } from 'child_process';-import { join } from 'path';import type { BrainEngine } from './engine.ts';import { importImageFile } from './import-file.ts';+import { resolveRecordedImageFile, type DirectoryListings, type RecordedImageFile } from './image-asset-resolver.ts';import { importManagedFile } from './persistence/import-mutations.ts';import { readManagedMode } from './persistence/managed-mode.ts';import { safeChunksFilter } from './search/safe-chunks.ts';@@ -75,23 +77,26 @@ export async function embedStaleImages(const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);const managed = await readManagedMode(engine);const gitRoots = new Map<string, string | null>();+ const listings: DirectoryListings = new Map();const cap = opts.costCap;for (const row of rows) {// Fix wave 13 P1.18: the approved cap stops the sweep before the next image; a refused image is not a failure.if (cap?.hit()) break;const root = row.local_path ?? (row.source_id === 'default' ? repoPath : null);// An image slug is the lower-cased repo-relative path, so it names the file when the importer never recorded source_path.- const sourcePath = row.source_path ?? row.slug;- const located = root ? locateSourceFile(root, sourcePath, gitRoots) : null;- const file = located?.found ?? null;- if (!file) {+ const located = root ? locateSourceFile(root, [row.source_path, row.slug], gitRoots, listings) : null;+ if (located?.status === 'ambiguous') { fail(row, `ambiguous case-insensitive match for ${located.tried}: ${located.matches.join(', ')}; rename one, then rerun (nothing was imported)`); continue; }+ if (located?.status === 'outside_root') { fail(row, `${located.tried} resolves outside source ${row.source_id}'s root ${root}; not imported`); continue; }+ if (located?.status !== 'found') {result.missingFile++;- if (result.missing_samples.length < SAMPLE_CAP) result.missing_samples.push(`${row.source_id}:${row.slug}: no file at ${located ? located.direct : `<source ${row.source_id} has no local path>`}`);+ if (result.missing_samples.length < SAMPLE_CAP) result.missing_samples.push(`${row.source_id}:${row.slug}: no file at ${located ? located.tried : `<source ${row.source_id} has no local path>`}`);continue;}+ // The real-case path the file has on disk: the import and the recorded source_path use it.+ const { abs: file, relative: sourcePath } = located;// A managed brain imports through the source's owner (the coordinated importer, as `gbrain import` does); the legacy writer refuses it.// The owner reads only files inside the source root: a subpath-scoped page found under the git root is reported, not copied in.- if (managed && file !== located!.direct) { fail(row, `${file} is outside source ${row.source_id}'s root ${root}; a managed brain imports only files inside the source root`); continue; }+ if (managed && located.viaGitRoot) { fail(row, `${file} is outside source ${row.source_id}'s root ${root}; a managed brain imports only files inside the source root`); continue; }try {const run = () => managed ? importManagedFile(engine, file, sourcePath, { sourceId: row.source_id }) : importImageFile(engine, file, sourcePath, { sourceId: row.source_id });const imported = cap ? await cap.metered(run) : await run();@@ -164,18 +169,20 @@ export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]return result;}-/** A page's source_path is relative to its source checkout (`direct`), or to the git root for subpath-scoped syncs; `found` is whichever exists. */-function locateSourceFile(root: string, sourcePath: string, gitRoots: Map<string, string | null>): { direct: string; found: string | null } {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- source_path is the repo-relative path the importer recorded for this page, joined under the source's own checkout- const direct = join(root, sourcePath);- if (existsSync(direct)) return { direct, found: direct };+/**+ * A page's recorded path is relative to its source checkout, or to the git root for subpath-scoped syncs; the shared+ * resolver (#6543 D3) tries the checkout first, then the git root. A miss reports the path tried under the checkout.+ */+function locateSourceFile(root: string, candidates: Array<string | null>, gitRoots: Map<string, string | null>, listings: DirectoryListings): RecordedImageFile & { viaGitRoot?: boolean } {+ const direct = resolveRecordedImageFile(root, candidates, listings);+ if (direct.status !== 'missing') return direct;if (!gitRoots.has(root)) {try {gitRoots.set(root, execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());} catch { gitRoots.set(root, null); }}const gitRoot = gitRoots.get(root);- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same recorded repo-relative path, joined under the checkout's git root- const viaGit = gitRoot ? join(gitRoot, sourcePath) : null;- return { direct, found: viaGit && existsSync(viaGit) ? viaGit : null };+ if (!gitRoot || gitRoot === root) return direct;+ const viaGit = resolveRecordedImageFile(gitRoot, candidates, listings);+ return viaGit.status === 'missing' ? direct : { ...viaGit, viaGitRoot: true };}diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex e23cbe639d..2a34c85a67 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -76,6 +76,7 @@ export const ERROR_CATALOGUE = {sync_drain_preparation_systemic: { code: 'preparation_systemic', docs: 'docs/guides/write-refusals.md#preparation_systemic' },sync_drain_write_capacity: { code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' },sync_drain_connection_lost: { code: 'connection_lost', docs: 'docs/guides/write-refusals.md#drain-connection-lost' },+ sync_drain_head_blocked: { code: 'drain_stalled', docs: 'docs/guides/write-refusals.md#head-blocked' },// D8 `gbrain setup <harness>` (src/commands/setup.ts).setup_harness_unsupported: { code: 'setup_harness_unsupported', docs: 'docs/guides/repair.md#setup-harness-unsupported' },setup_owner_conflict: { code: 'setup_owner_conflict', docs: 'docs/guides/repair.md#setup-owner-conflict' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1d1834c163..246e360502 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -222,6 +222,13 @@ export const CODES = {host_identity_mismatch: { class: 'host_only', summary: "This process's `host.json` identity differs from the identity that owns the binding although both resolve on this machine, so writes that need the owner read it as another host.", why: "Host identity is a file under the persistence home: a job worker or container launched with a different `HOME` or `GBRAIN_HOME` mints a new `host.json` and sees the binding as another host's (`owner_unavailable`, `host_mismatch`), so its maintenance writes never reach the owner. The check names both files and the environment each was minted under (`minted_under`, `unknown` for a file minted before it was recorded); re-deriving the identity would re-own every existing binding, so the fix is the environment, never the file.", docs: 'docs/guides/troubleshooting.md#host-identity-mismatch', suggestion: 'Set GBRAIN_HOME on the supervisor of the process to the owner\'s home (the value the check prints; config appends .gbrain itself) and restart it; never edit or delete a host.json.', fix: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: names both host.json paths, the HOME and GBRAIN_HOME each was minted under and the GBRAIN_HOME value to set.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'] } } },harness_hook_duplicates: { class: 'caller', summary: "A harness hook carrier wires one Claude Code event more than once with this install's own entries (marked or not), so the hook fires twice per event.", why: "Claude Code can drop the `_gbrain` marker when it rewrites settings.json; installs before wave 11 then appended a second set on every re-run.", docs: 'docs/guides/bootstrap.md#harness_hook_duplicates', fix: { argv: ['gbrain', 'doctor', '--only', 'bootstrap_harness_health', '--json'], consent: [], actor: 'agent', why: "Names the carrier, the duplicated events and the re-run (with the install's own flags) that converges them, read-only.", requires_exclusive: false } },harness_hook_unowned: { class: 'caller', summary: "A hook entry looks like gbrain's harness hook but is not this install's exact command, so gbrain left it in place.", why: "An unmarked entry is deleted only when its command is exactly what this install (or its receipt) wrote; an edited command or another install's launcher is never removed, and removal is not reported complete while it remains.", docs: 'docs/guides/bootstrap.md#harness_hook_unowned', fix: { argv: ['gbrain', 'bootstrap', 'harness', '--status'], consent: [], actor: 'agent', why: 'Shows each hook carrier with the events holding entries that are not this install\'s, read-only.', requires_exclusive: false } },+ head_blocked: { class: 'server', retryable: false, actor: 'host_admin',+ summary: "The queued write at the head of a managed source cannot be claimed by any consumer, and its blocker needs an operator; a managed sync drain stops `drain_stalled` with `cause: head_blocked` and `blocked_by` names the predicate.",+ why: "#6543: the drain used to wait the whole no-progress window and print a constant `claimable here: no`. The head probe evaluates each predicate of the claim query for the head itself. Only intervention-required blockers stop the drain, after one governor tick of confirmation: a refresh fence no refresh process holds, or a running request ahead held by a process that reports restart_required. Live blockers (a foreground publication, a lapsed lease, a refresh or recovery making progress) keep the progress-aware wait.",+ reasons: ['refresh_fence', 'zombie_publication'],+ docs: 'docs/guides/write-refusals.md#head-blocked',+ suggestion: 'Run next.fix: for refresh_fence resume the refresh (gbrain sources refresh <source> --resume); for zombie_publication restart the named gbrain process on the brain host. Then rerun the same sync.',+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: names the blocker of every queued head (predicate, ids, owner) and, when the caller may cancel the blocking request, the cancel-write-request command.', requires_exclusive: false } },held_failed: { class: 'unavailable', summary: "A managed atom origin (a page or transcript) failed atom extraction 3 times on the same content, so the drain stopped retrying it; doctor `extract_atoms_held_failed` lists it with its last request id.", why: "Every automatic attempt is a paid model call. After MAX_DETERMINISTIC_FAILURES completed failures of one content the origin leaves the atom backlog instead of being paid for every cycle; editing the content starts a new count, and an explicit retry runs it again.", fix: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_held_failed', '--json'], consent: [], actor: 'agent', why: 'Lists the held atom origins with their last request id, failure and retry command, read-only.', requires_exclusive: false } },held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },diff --git a/src/core/image-asset-resolver.ts b/src/core/image-asset-resolver.tsnew file mode 100644index 0000000000..d5baf3925f--- /dev/null+++ b/src/core/image-asset-resolver.ts@@ -0,0 +1,62 @@+/**+ * #6543 D3: resolves a recorded image path (`pages.source_path`, `files.storage_path`, or the lower-cased slug) to the+ * file under one source root. Shared by doctor `image_assets` and the `embed --stale --images` sweep.+ *+ * - The exact recorded path wins (candidates in order).+ * - Otherwise a bounded case-insensitive walk (one memoised `readdir` per path segment) finds the file and returns+ * its real-case source-relative path, so the import and the recorded `source_path` use the case on disk.+ * - Two entries that fold to the same segment refuse as `ambiguous`; nothing is chosen.+ * - Containment is checked separately on the real path: a symlink that leaves the root is `outside_root`, and an+ * absolute or `..` candidate is never joined. Only the given root is read, so one source never resolves another's file.+ */+import { existsSync, readdirSync, realpathSync } from 'node:fs';+import { isAbsolute, join, sep } from 'node:path';++export type RecordedImageFile =+ | { status: 'found'; abs: string; relative: string; caseMismatch: boolean }+ | { status: 'missing'; tried: string }+ | { status: 'ambiguous'; tried: string; matches: string[] }+ | { status: 'outside_root'; tried: string };++/** Directory listings read so far (`null`: unreadable); pass one map across a sweep so each directory is read once. */+export type DirectoryListings = Map<string, string[] | null>;++export function resolveRecordedImageFile(root: string, candidates: Array<string | null | undefined>, listings: DirectoryListings = new Map()): RecordedImageFile {+ const paths = [...new Set(candidates.filter((path): path is string => !!path))]+ .filter(path => !isAbsolute(path) && !path.split(/[\\/]/).includes('..'));+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- absolute and `..` candidates were dropped above; containment is re-checked on the real path+ const tried = join(root, paths[0] ?? '');+ let realRoot: string | null = null;+ const contained = (abs: string): boolean => {+ try {+ realRoot ??= realpathSync(root);+ const real = realpathSync(abs);+ return real.startsWith(realRoot.endsWith(sep) ? realRoot : realRoot + sep);+ } catch { return false; }+ };+ const found = (relative: string, caseMismatch: boolean): RecordedImageFile => {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- a filtered candidate or entries read from the root's own directories+ const abs = join(root, relative);+ return contained(abs) ? { status: 'found', abs, relative, caseMismatch } : { status: 'outside_root', tried: abs };+ };+ for (const relative of paths) {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- filtered candidate under the source root+ if (existsSync(join(root, relative))) return found(relative, false);+ }+ for (const relative of paths) {+ const real: string[] = [];+ let directory = root;+ for (const segment of relative.split(/[\\/]/).filter(Boolean)) {+ if (!listings.has(directory)) {+ try { listings.set(directory, readdirSync(directory)); } catch { listings.set(directory, null); }+ }+ const hits = (listings.get(directory) ?? []).filter(entry => entry.toLowerCase() === segment.toLowerCase());+ if (hits.length > 1) return { status: 'ambiguous', tried: join(root, relative), matches: hits.map(hit => [...real, hit].join('/')) };+ if (hits.length === 0) { real.length = 0; break; }+ real.push(hits[0]!);+ directory = join(directory, hits[0]!);+ }+ if (real.length) return found(real.join('/'), real.join('/') !== relative);+ }+ return { status: 'missing', tried };+}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex a4122be13e..0915a8057b 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1929,8 +1929,6 @@ export async function importImageFile(const filename = basename(relativePath);const frontmatter: Record<string, unknown> = {- type: 'image',- title: filename,mime_type: decoded.mime,bytes: buf.byteLength,...exif,diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 4de9695b6c..06d1136c0e 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -63,6 +63,14 @@ function failureLogText(row: WriteRequest): string | undefined {return row.error_message || extra ? `${row.error_message ?? ''}${extra}`.replaceAll('"', "'") : undefined;}+/** #6543 F1: the identity of the request a consumer line is about; control characters, spaces and quotes become `_`. */+function requestLogFields(row: Pick<WriteRequest, 'request_id' | 'operation' | 'source_id' | 'slug' | 'principal_kind' | 'created_at'>): string {+ const clean = (value: unknown) => String(value ?? '').replace(/[\x00-\x20"\x7f-\x9f]/g, '_').slice(0, 200);+ const elapsed = Date.now() - new Date(row.created_at).getTime();+ return ` request_id=${clean(row.request_id)} operation=${clean(row.operation)} source=${clean(row.source_id)} slug=${clean(row.slug)}`+ + ` principal=${clean(row.principal_kind)}${Number.isFinite(elapsed) ? ` elapsed_ms=${Math.max(0, elapsed)}` : ''}`;+}+function errorDetail(error: unknown): string | undefined {const message = (error as { message?: unknown } | null)?.message;if (typeof message !== 'string' || !message.trim()) return undefined;@@ -201,6 +209,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private unobserveCheckout: (() => void) | undefined;private phaseAttempts = 0;private lastLog: { key: string; at: number } | undefined;+ private readonly requestLogs = new Map<string, number>();private lastPhaseError: string | undefined;private preparationAttempts = 0;private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();@@ -620,7 +629,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private track(row: WriteRequest, done: () => void, key: string): void {let progressed = false;const root: RootHold = {};- const task = this.executeOrGroup(row, root).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {+ const task = this.executeOrGroup(row, root).then(result => { progressed = result; }).catch(error => this.report(error, row)).finally(() => {if (!progressed) this.rootRetryAfter.set(key, Date.now() + (root.retryAfterMs ?? this.opts.pollMs ?? 250));else { this.progressWake = true; this.publishedSinceMaintenance++; }this.active.delete(task);@@ -685,12 +694,12 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return { ceilingMs,onOverdue: () => {if (clock) clock.waitingOn = 'publication_deadline';- this.log('publication', 'publication_deadline', `request ${row.request_id}: publishing past the ${ceilingMs} ms ceiling; its transaction's server-side timeouts end it on Postgres`);+ this.log('publication', 'publication_deadline', `request ${row.request_id}: publishing past the ${ceilingMs} ms ceiling; its transaction's server-side timeouts end it on Postgres`, '', row);},onStuck: settled => {this.stuckPublications.set(row.id, { request_id: row.request_id, stuck_at: new Date().toISOString() });void settled.then(() => { this.stuckPublications.delete(row.id); });- this.log('publication', 'restart_required', `request ${row.request_id}: the publication has not settled past the ceiling and its grace; restart this process (its root stays held until then)`);+ this.log('publication', 'restart_required', `request ${row.request_id}: the publication has not settled past the ceiling and its grace; restart this process (its root stays held until then)`, '', row);} };}status() {@@ -768,7 +777,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}finally { clearTimeout(timer); this.abort.signal.removeEventListener('abort', stop); this.phaseObservation = undefined; }}- private report(error: unknown): void {+ private report(error: unknown, row?: WriteRequest): void {if (this.stopping && error === this.abort.signal.reason) return;if (error instanceof PhaseDeadlineError) {// The timer already logged deadline_exceeded for this phase: record it under the phase, hand it to onError@@ -782,15 +791,24 @@ export class PersistenceConsumer implements PersistenceConsumerLike {this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };if (this.opts.onError) this.opts.onError(error);- else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error), this.lastPhaseError ? this.lastPhaseTiming : undefined);+ else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error), this.lastPhaseError ? this.lastPhaseTiming : undefined, row);this.lastPhaseError = undefined;this.lastPhaseTiming = undefined;}- private log(phase: string, code: string, detail?: string, timing = ''): void {+ /** #6543 F1: a line about one request is throttled per request (30 s per phase and code); other lines keep the shared throttle. */+ private log(phase: string, code: string, detail?: string, timing = '', row?: WriteRequest): void {const key = `${phase}:${code}`, at = Date.now();- if (this.lastLog && (at - this.lastLog.at < 1000 || this.lastLog.key === key && at - this.lastLog.at < 30_000)) return;- this.lastLog = { key, at };- if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}`+ if (row) {+ const requestKey = `${key}:${row.id}`;+ if (at - (this.requestLogs.get(requestKey) ?? -Infinity) < 30_000) return;+ if (this.requestLogs.size >= 256) for (const [stale, loggedAt] of this.requestLogs) if (at - loggedAt >= 30_000) this.requestLogs.delete(stale);+ if (this.requestLogs.size >= 256) return;+ this.requestLogs.set(requestKey, at);+ } else {+ if (this.lastLog && (at - this.lastLog.at < 1000 || this.lastLog.key === key && at - this.lastLog.at < 30_000)) return;+ this.lastLog = { key, at };+ }+ if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}${row ? requestLogFields(row) : ''}`+ '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');}/** #5373: tracks work that outlived its claim until it settles; the returned promise never rejects. */@@ -848,7 +866,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {this.zombies.set(row.id, { request_id: row.request_id, operation: row.operation, step: clock.step, waiting_on: clock.waitingOn,claimed_at: new Date(clock.claimedAt).toISOString(), abandoned_at: at, outlived_ceiling_at: at });void settled.then(() => { this.zombies.delete(row.id); });- this.log('preparation', 'ceiling_exceeded', `request ${row.request_id}${claimTripleText(clock)}${this.restartRequired() ? ' restart_required' : ''}`);+ this.log('preparation', 'ceiling_exceeded', `request ${row.request_id}${claimTripleText(clock)}${this.restartRequired() ? ' restart_required' : ''}`, '', row);await floorPreparationAttempts(this.statements, row.id, this.policy.maxAttempts).catch(error => this.report(error));});}@@ -870,7 +888,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {try {const previous = claimStateOf({ state: 'running', claim_phase: row.previous_claim_phase, execution_token: previousToken(row.previous_claim_phase) });const done = await finishPreparationStalled(this.engine, row, { step: previous?.step ?? null, waiting_on: previous?.waiting_on ?? 'unknown', limit: policy.maxAttempts }, false);- this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText({ step: previous?.step ?? null, waitingOn: previous?.waiting_on ?? 'unknown' })}`);+ this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText({ step: previous?.step ?? null, waitingOn: previous?.waiting_on ?? 'unknown' })}`, '', row);return this.settled(done);} finally { this.preparing.delete(row.id); this.executing.delete(row.id); }}@@ -881,7 +899,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return this.prepare(this.engine.kind === 'postgres' && singleWrite(row)&& await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,row, this.config, budget !== undefined && preparationKind(row) === 'foreground' ? signal : undefined, clock);- }, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded', `request ${row.request_id}${claimTripleText(clock)}`); } });+ }, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded', `request ${row.request_id}${claimTripleText(clock)}`, '', row); } });const stop = () => prep.abort({ code: 'consumer_stopping' });this.abort.signal.addEventListener('abort', stop, { once: true });const lease = startClaimLease(@@ -897,7 +915,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.statements, row, releaseReason()); return false; }if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);- this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText(clock)}`);+ this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText(clock)}`, '', row);return this.settled(done);}await releaseUnpublishedClaim(this.statements, row, 'preparation_deadline', { charge: true });@@ -923,10 +941,10 @@ export class PersistenceConsumer implements PersistenceConsumerLike {enterClaimPhase(clock, 'publishing');await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });const { done, settled } = await boundPublication(() => this.publishSingle(row, prepared), this.publicationBound(row, await readPublicationCeilingMs(this.engine), clock));- if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done));+ if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done), '', row);if (done.state === 'queued' && done.blocked_reason === 'writer_lock_unavailable') {root.retryAfterMs = INSPECT_OWNER_RETRY_MS;- this.log('publication', 'writer_lock_unavailable', `request ${row.request_id}: this process cannot open source ${row.source_id}'s worktree lock${lockOpenOsError(row.worktree_id) ? ` (${lockOpenOsError(row.worktree_id)})` : ''}; left for an owner process`);+ this.log('publication', 'writer_lock_unavailable', `request ${row.request_id}: this process cannot open source ${row.source_id}'s worktree lock${lockOpenOsError(row.worktree_id) ? ` (${lockOpenOsError(row.worktree_id)})` : ''}; left for an owner process`, '', row);}if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);@@ -947,7 +965,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const current = await getWriteRequestById(this.engine, row.id);if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {const done = await finishUnpublishedFailure(this.engine, current, error, preparationActive ? 'preparation' : 'publication');- if (done.state === 'failed') this.log(preparationActive ? 'preparation' : 'publication', done.error_code ?? 'storage_error', failureLogText(done));+ if (done.state === 'failed') this.log(preparationActive ? 'preparation' : 'publication', done.error_code ?? 'storage_error', failureLogText(done), '', row);return this.settled(done);}throw error;diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex d58c9f39f8..2efaa4f9d8 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -13,6 +13,7 @@ import type { WriteRequestState } from './types.ts';import { preparationBudgetMs } from './preparation-budget.ts';import { readWriteSwitchSnapshot } from './switches.ts';import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT } from './connector-errors.ts';+import { readQueuedHeadBlockers } from './head-blocker.ts';export const WRITER_NEXT_ACTIONS: Record<string, string> = {unexpected_staging_bytes: 'Keep the worktree blocked and retain its staging files and recovery capacity. Compare the recorded staging size and hash, then reconcile unexpected bytes explicitly before retrying; never discard unverified staging files.',@@ -150,10 +151,10 @@ export async function readWriterDiagnostics(engine: BrainEngine) {GROUP BY w.id ORDER BY w.id`);const counters = await engine.executeRaw<Counter>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters ORDER BY key`);// #6278: the operation and intent kind say which budget applies and tell a sync member from a maintenance write; the owner process comes from the live claim's stamp.- const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; source_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null;+ const blockers = await engine.executeRaw<{ id: string; request_id: string; worktree_id: string | null; source_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null;operation: string; intent_kind: string | null; preparation_attempts: number | null } & Omit<ClaimRow, 'state'>>(`SELECT request_id,worktree_id,source_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started,- operation,intent->>'kind' AS intent_kind,preparation_attempts+ operation,intent->>'kind' AS intent_kind,preparation_attempts,id::text AS idFROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,MIN(created_at) AS oldest_request_at,@@ -180,6 +181,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {const tracked = (engine as { getPoolDiagnostics?: () => { tracked?: unknown } | null }).getPoolDiagnostics?.()?.tracked ?? null;const claimStates = blockers.map(row => claimStateOf({ state: row.state, claim_phase: row.claim_phase, execution_token: row.execution_token, claim_lapsed: row.claim_lapsed, publication_started: row.publication_started }));const backends = await readOwnerBackends(engine, claimStates.flatMap(state => state?.owner ? [state.owner] : []));+ const headBlockers = await readQueuedHeadBlockers(engine, blockers, hostId);// C-NEW-4: the consumer is per process, so this is the answering process's own ingress, never proof the brain's owner is down.const local = persistenceConsumerStatus(engine);const local_process_ingress = { ...local, scope: local.state === 'not_running'@@ -189,7 +191,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {local_process_ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits), preparation_policy,recent_failures: failures.map(row => ({ ...row, next_action: row.error_detail?.origin === 'database_guard' ? DATABASE_REFUSAL_HINT : DATABASE_TRIGGER_HINT })),backend_visibility: backends.visibility,- blockers: blockers.map(({ claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }, index) => {+ blockers: blockers.map(({ id: rowId, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }, index) => {const health = writeHealth(row);const advice = writerNextAction(row.blocked_reason ?? row.error_code);// #6176: a running request names the phase its claim is in and how long it has held it; #6278: its step, wait cause, owner@@ -205,7 +207,10 @@ export async function readWriterDiagnostics(engine: BrainEngine) {...(budget === null ? {} : { budget_ms: budget }), stall, ...claimPool(engine, state, ownerRow), pool_tracked_subset: tracked,owner_live: ownerRow ? ownerRow.liveness === 'live' : null, owner_mode: ownerRow?.mode ?? null,next: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? ownerRow.liveness === 'live' : null }) } : undefined;- return { ...row, preparation_attempts: row.preparation_attempts ?? 0, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT- ? `${WRITER_INSPECTION_HINT} ${advice}` : advice };+ // #6543 (B2): a queued head names what keeps it unclaimed, and the cancel command only when this caller may cancel the blocking request.+ const head = headBlockers.get(rowId);+ const adviceText = health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT ? `${WRITER_INSPECTION_HINT} ${advice}` : advice;+ return { ...row, preparation_attempts: row.preparation_attempts ?? 0, ...health, ...(claim ? { claim } : {}), ...head?.fields,+ next_action: head?.advice ? `${head.advice} ${adviceText}` : adviceText };}) };}diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.tsnew file mode 100644index 0000000000..535892a580--- /dev/null+++ b/src/core/persistence/head-blocker.ts@@ -0,0 +1,204 @@+/**+ * #6543 (B2): why the queued head of a root is not claimable, one predicate of `claimableWriteSql` at a time, so a drain stop,+ * the stall line and `sources writer status` name what blocks it instead of a constant "claimable here: no".+ *+ * Blockers are classified. Intervention-required ones stop the drain (`drain_stalled`, `cause: head_blocked`) after one+ * governor tick of confirmation: a durable refresh fence no live refresh process holds, or a running row ahead whose owner+ * reports `restart_required` (a zombie publication). Every other blocker is live and transient (a foreground publication,+ * a refresh or recovery making progress, a lapsed lease the next consumer reclaims), so the drain keeps its progress-aware wait.+ */+import type { BrainEngine } from '../engine.ts';+import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';+import { claimStateOf } from './claim-phase.ts';+import { claimableWriteSql, EARLIER_HEAD, foregroundPrioritySql, SYNC_KIND } from './journal.ts';++export type HeadBlockerPredicate = 'worktree_owner' | 'refresh_fence' | 'effect_recovery' | 'withdrawal_mirror' | 'request_recovery'+ | 'zombie_publication' | 'lease' | 'root_hold';+export interface HeadBlocker {+ predicate: HeadBlockerPredicate;+ /** The refresh id for a fence, the request ids of blocking requests, the effect ids of blocking effects, or the worktree id. */+ ids: string[];+ /** The fence state, the blocking request's state, or the worktree state (`other_host` when another host owns it). */+ state: string | null;+ /** The process behind the blocker when one is known: a refresh process (`live` from its lock) or a claim's stamped owner. */+ owner: { kind: string | null; pid: number | null; live: boolean | null; restart_required: boolean } | null;+ /** True when only an operator clears it; the drain stops on these and keeps waiting on the rest. */+ intervention: boolean;+}+/** A blocking request this caller may cancel: not publishing, no recovery record; `cancel-write-request` is scoped to its principal. */+export interface HeadBlockerCancel { request_id: string; principal_kind: string; principal_id: string }+export type HeadBlockerRead = { status: 'claimable' } | { status: 'blocked'; blocker: HeadBlocker; cancel: HeadBlockerCancel | null } | { status: 'unknown' };++interface RowRef { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean;+ publication_started: boolean; recovery: boolean; principal_kind: string; principal_id: string }+interface ProbeRow { id: string; worktree_id: string | null; owner_host_id: string | null; worktree_state: string | null; claimable: boolean;+ fence: { id: string; state: string } | null; effect_recovery: string[] | null; mirrors: string[] | null; request_recovery: string[] | null;+ earlier: RowRef[] | null; ahead: RowRef[] | null }++const REF = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'claim_phase',${alias}.claim_phase,+ 'execution_token',${alias}.execution_token::text,'claim_lapsed',COALESCE(${alias}.claim_expires_at<now(),false),'publication_started',COALESCE(${alias}.publication_started,false),+ 'recovery',${alias}.recovery IS NOT NULL,'principal_kind',${alias}.principal_kind,'principal_id',${alias}.principal_id)`;++/**+ * One read for queued requests (internal ids): each comes back `claimable` for a consumer on `hostId`, `blocked` with the first+ * predicate that fails in `claimableWriteSql` order, or `unknown` when none matched. Rejects when the read fails; callers print `unknown`.+ */+export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostId: string | null,+ opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<Map<string, HeadBlockerRead>> {+ const out = new Map<string, HeadBlockerRead>();+ if (!ids.length) return out;+ const priority = foregroundPrioritySql();+ const rows = await engine.executeRaw<ProbeRow>(`SELECT r.id::text AS id, r.worktree_id::text AS worktree_id, w.owner_host_id::text AS owner_host_id, w.state AS worktree_state,+ (${claimableWriteSql(priority)}) AS claimable,+ (SELECT jsonb_build_object('id',f.id::text,'state',f.state) FROM persistence_worktree_refreshes f+ WHERE f.worktree_id=r.worktree_id AND f.state IN ('fenced','merged','recovery_required') LIMIT 1) AS fence,+ (SELECT array_agg(e.id::text) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,+ (SELECT array_agg(m.id::text) FROM persistence_effects m WHERE m.worktree_id=r.worktree_id AND m.kind='withdrawal-mirror' AND m.state IN ('queued','running')+ AND (NOT (m.data ? 'targets') OR m.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug)))) AS mirrors,+ (SELECT array_agg(b.request_id::text) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,+ (SELECT jsonb_agg(${REF('e')} ORDER BY e.sequence) FROM persistence_requests e+ WHERE ((r.worktree_id IS NOT NULL AND e.worktree_id=r.worktree_id) OR (r.worktree_id IS NULL AND e.worktree_id IS NULL AND e.source_incarnation=r.source_incarnation))+ AND ${EARLIER_HEAD('e', 'r', priority, "'{}'::text[]")}) AS earlier,+ (SELECT jsonb_agg(${REF('a')} ORDER BY a.sequence) FROM persistence_requests a WHERE (${priority}) AND ${SYNC_KIND('r')}+ AND a.worktree_id=r.worktree_id AND a.sequence>r.sequence AND a.state IN ('running','recovering') AND NOT ${SYNC_KIND('a')}) AS ahead+ FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id+ WHERE r.id=ANY($3::uuid[]) AND r.state='queued'`, [hostId, [], ids], opts);+ let consumers: Awaited<ReturnType<typeof import('./consumer-heartbeat.ts').listHostConsumers>> | null = null;+ for (const row of rows) {+ if (row.claimable) { out.set(row.id, { status: 'claimable' }); continue; }+ const blocked = (blocker: HeadBlocker, cancel: HeadBlockerCancel | null = null) => out.set(row.id, { status: 'blocked', blocker, cancel });+ if (row.worktree_id && (row.owner_host_id !== hostId || row.worktree_state !== 'active')) {+ blocked({ predicate: 'worktree_owner', ids: [row.worktree_id], state: row.owner_host_id !== hostId ? 'other_host' : row.worktree_state, owner: null, intervention: false });+ continue;+ }+ if (row.fence && row.worktree_id) {+ const live = await refreshOwnerLive(row.worktree_id);+ blocked({ predicate: 'refresh_fence', ids: [row.fence.id], state: row.fence.state, owner: { kind: 'refresh', pid: null, live, restart_required: false },+ intervention: row.fence.state === 'recovery_required' || live === false });+ continue;+ }+ if (row.effect_recovery?.length) { blocked({ predicate: 'effect_recovery', ids: row.effect_recovery, state: null, owner: null, intervention: false }); continue; }+ if (row.mirrors?.length) { blocked({ predicate: 'withdrawal_mirror', ids: row.mirrors, state: null, owner: null, intervention: false }); continue; }+ if (row.request_recovery?.length) { blocked({ predicate: 'request_recovery', ids: row.request_recovery, state: null, owner: null, intervention: false }); continue; }+ const ref = row.earlier?.[0] ?? row.ahead?.[0];+ if (!ref) { out.set(row.id, { status: 'unknown' }); continue; }+ const claim = claimStateOf({ state: ref.state, claim_phase: ref.claim_phase, execution_token: ref.execution_token, claim_lapsed: ref.claim_lapsed, publication_started: ref.publication_started });+ if (claim?.owner && hostId && consumers === null) {+ const { listHostConsumers } = await import('./consumer-heartbeat.ts');+ consumers = await listHostConsumers(engine, hostId, { signal: opts.signal }).catch(() => []);+ }+ const heartbeat = claim?.owner ? consumers?.find(c => c.pid === claim.owner!.pid && (claim.owner!.nonce === undefined || c.nonce === claim.owner!.nonce)) ?? null : null;+ const owner = claim?.owner ? { kind: claim.owner.kind, pid: claim.owner.pid, live: heartbeat ? heartbeat.liveness === 'live' : null, restart_required: heartbeat?.restart_required === true } : null;+ const predicate: HeadBlockerPredicate = owner?.restart_required ? 'zombie_publication' : claim?.phase === 'publication_transaction' ? 'lease' : 'root_hold';+ const cancellable = ref.state !== 'recovering' && !ref.publication_started && !ref.recovery;+ blocked({ predicate, ids: [ref.request_id], state: ref.state, owner, intervention: predicate === 'zombie_publication' },+ cancellable ? { request_id: ref.request_id, principal_kind: ref.principal_kind, principal_id: ref.principal_id } : null);+ }+ for (const id of ids) if (!out.has(id)) out.set(id, { status: 'unknown' });+ return out;+}++/** Whether a refresh process holds the worktree's refresh lock: true held, false free, null when the lock cannot be probed here. */+async function refreshOwnerLive(worktreeId: string): Promise<boolean | null> {+ try {+ const { refreshLockPath } = await import('./worktree-refresh.ts');+ const { tryAcquireNativeLock } = await import('./native-lock.ts');+ const lock = await tryAcquireNativeLock(refreshLockPath(worktreeId));+ if (!lock) return true;+ await lock.release();+ return false;+ } catch { return null; }+}++/** `blocked_by=` for the stall line and the summary. */+export function headBlockerText(blocker: HeadBlocker): string {+ const owner = blocker.owner?.pid ? `${blocker.owner.kind ?? 'owner'} pid ${blocker.owner.pid}${blocker.owner.restart_required ? ' restart_required' : ''}`+ : blocker.predicate === 'refresh_fence' ? blocker.owner?.live === true ? 'refresh running' : blocker.owner?.live === false ? 'no live refresh' : null : null;+ return `${blocker.predicate}(${[blocker.state, blocker.ids.join(','), owner].filter(Boolean).join(' ')})`;+}++/** The predicate's recovery contract, as the drain's JSON `next` (fix) and the writer-status advice carry it. */+export function headBlockerAction(blocker: HeadBlocker, sourceId: string, resumeCommand: string): Action {+ const status = ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'];+ if (blocker.predicate === 'refresh_fence') {+ return { argv: ['gbrain', 'sources', 'refresh', sourceId, '--resume'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Refresh ${blocker.ids[0]} left the checkout fenced (${blocker.state})${blocker.owner?.live === false ? ' and no refresh process holds its lock' : ''}, so nothing on the source's worktree is claimed. `+ + `Resuming it finishes (or names why it cannot finish) the refresh and lifts the fence; then rerun: ${resumeCommand}`,+ verify: { argv: status } };+ }+ if (blocker.predicate === 'zombie_publication') {+ const who = `the gbrain ${blocker.owner?.kind ?? 'owner'} process${blocker.owner?.pid ? ` (pid ${blocker.owner.pid})` : ''}`;+ return { argv: status, consent: [], actor: 'host_admin', requires_exclusive: false,+ why: `Request ${blocker.ids[0]} ahead of the head is held by ${who}, which reports restart_required; its root stays held until that process exits. Status names it, read-only.`,+ user_message: `Restart ${who} on the brain host, then run: ${resumeCommand}`, verify: { argv: status } };+ }+ return { argv: status, consent: [], actor: 'agent', requires_exclusive: false,+ why: `The head waits on ${headBlockerText(blocker)}, which is making progress on its own. Rerun status (read-only) to see it clear.`, verify: { argv: status } };+}++/** The drain's `next` for a `head_blocked` stop. */+export function headBlockedNext(blocker: HeadBlocker, headRequestId: string | null, stalledSeconds: number, sourceId: string, resumeCommand: string):+ { command: string; safe_to_loop: false; retry_after_ms: 0; why: string; fix: RenderedAction } {+ const action = headBlockerAction(blocker, sourceId, resumeCommand);+ return { command: action.argv!.join(' '), safe_to_loop: false, retry_after_ms: 0, fix: renderAction(action, cliRenderContext()),+ why: `The queued write at the head of this source (${headRequestId ?? 'unknown request'}) cannot be claimed by any consumer: it is blocked by ${headBlockerText(blocker)}, `+ + `which no amount of waiting clears${stalledSeconds ? ` (quiet ${stalledSeconds}s)` : ''}. The cursor and accepted writes are intact. ${action.user_message ?? action.why}` };+}++/**+ * `consumer=` for the stall line: this process's own consumer, or the live full/promoted heartbeat row on this host+ * (`serve pid=N last_heartbeat_ago=3s`, plus `restart_required`), or `none`. Never rejects (`unknown`).+ */+export async function describeHostConsumer(engine: BrainEngine, opts: { signal?: AbortSignal } = {}): Promise<string> {+ try {+ const { persistenceConsumerStatus } = await import('./service.ts');+ const status = persistenceConsumerStatus(engine) as { state: string; consumer_election?: { mode: string } };+ const mode = status.consumer_election?.mode ?? (status.state === 'open' ? 'full' : null);+ if (mode === 'full' || mode === 'promoted') return `self(${mode})`;+ const { existingLocalHostId } = await import('./identity.ts');+ const host = existingLocalHostId();+ const { listHostConsumers } = await import('./consumer-heartbeat.ts');+ const rows = host ? await listHostConsumers(engine, host, opts) : [];+ const owner = rows.find(row => !row.self && (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');+ const text = owner ? `${owner.kind} pid=${owner.pid} last_heartbeat_ago=${Math.round(owner.renewed_age_ms / 1000)}s${owner.restart_required ? ' restart_required' : ''}` : null;+ if (mode) return text ? `self(${mode}→${text})` : `self(${mode})`;+ return text ?? 'none';+ } catch { return 'unknown'; }+}++/** `claimable_here` and `blocked_by` for a head: a queued head is probed (a failed read is `null`, printed `unknown`); any other head is not claimable. */+export async function headClaimability(engine: BrainEngine, head: { id: string | null; state: string | null }, hostId: string | null,+ opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<{ claimable_here: boolean | null; blocked_by: HeadBlocker | null }> {+ if (!head.id || head.state !== 'queued') return { claimable_here: false, blocked_by: null };+ const read = await readHeadBlockers(engine, [head.id], hostId, opts).then(found => found.get(head.id!) ?? { status: 'unknown' as const }, () => ({ status: 'unknown' as const }));+ return read.status === 'claimable' ? { claimable_here: true, blocked_by: null } : read.status === 'blocked' ? { claimable_here: false, blocked_by: read.blocker } : { claimable_here: null, blocked_by: null };+}++/**+ * Writer status: the blocker of each root's first queued request (`claimable_here`, `blocked_by`, advice naming the predicate's recovery),+ * plus `cancel_command` only when the blocking request can still be cancelled and belongs to this host's CLI writer principal.+ */+export async function readQueuedHeadBlockers(engine: BrainEngine, rows: Array<{ id: string; worktree_id: string | null; source_id: string | null; state: string }>,+ hostId: string | null): Promise<Map<string, { fields: { claimable_here: boolean | null; blocked_by?: HeadBlocker; cancel_command?: string }; advice: string | null }>> {+ const heads = new Map<string, { id: string; source: string | null }>();+ for (const row of rows) if (row.state === 'queued' && !heads.has(row.worktree_id ?? `db:${row.source_id}`)) heads.set(row.worktree_id ?? `db:${row.source_id}`, { id: row.id, source: row.source_id });+ const out = new Map<string, { fields: { claimable_here: boolean | null; blocked_by?: HeadBlocker; cancel_command?: string }; advice: string | null }>();+ if (!heads.size) return out;+ const reads = await readHeadBlockers(engine, [...heads.values()].map(head => head.id), hostId).catch(() => null);+ let principal: { kind: string; id: string } | null | undefined;+ for (const { id, source } of heads.values()) {+ const read = reads?.get(id) ?? { status: 'unknown' as const };+ if (read.status !== 'blocked') { out.set(id, { fields: { claimable_here: read.status === 'claimable' ? true : null }, advice: null }); continue; }+ if (read.cancel && principal === undefined) {+ const { readLocalWriter } = await import('./identity.ts');+ principal = await readLocalWriter(engine, 'cli').then(local => ({ kind: 'local_cli', id: local.id }), () => null);+ }+ const cancel = read.cancel && principal && read.cancel.principal_kind === principal.kind && read.cancel.principal_id === principal.id+ ? `gbrain cancel-write-request ${read.cancel.request_id}` : null;+ const action = headBlockerAction(read.blocker, source ?? '<source>', `gbrain sync --source ${source ?? '<source>'}`);+ out.set(id, { fields: { claimable_here: false, blocked_by: read.blocker, ...(cancel ? { cancel_command: cancel } : {}) },+ advice: `Blocked by ${headBlockerText(read.blocker)}: ${action.user_message ?? action.why}${read.blocker.predicate === 'refresh_fence' ? ` Run: ${action.argv!.join(' ')}.` : ''}`+ + `${cancel ? ` Cancelling the blocking request (it has not started publishing) also frees the head; a sync rerun admits it again: ${cancel}` : ''}` });+ }+ return out;+}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex edaa0f88ae..120d40c67e 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -476,7 +476,7 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissio* database-only incarnation) is matched by the caller with columns the pending indexes cover,* so each probe is an index range scan rather than a walk of every pending row.*/-const EARLIER_HEAD = (earlier: string, r: string, priority: string, laneRoots: string) => `${earlier}.sequence<${r}.sequence+export const EARLIER_HEAD = (earlier: string, r: string, priority: string, laneRoots: string) => `${earlier}.sequence<${r}.sequenceAND ${earlier}.state IN ('queued','running','recovering') AND NOT ${PASSES_QUEUED_SYNC(earlier, r, priority, laneRoots)}`;/*** The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN@@ -486,7 +486,7 @@ const EARLIER_HEAD = (earlier: string, r: string, priority: string, laneRoots: s* unfinished withdrawal mirror of its page (of every page, for an untargeted* mirror), so the mirror never rewrites a file under an accepted request.*/-const SYNC_KIND = (row: string) => `COALESCE(${row}.intent->>'kind','') LIKE 'managed_sync_%'`;+export const SYNC_KIND = (row: string) => `COALESCE(${row}.intent->>'kind','') LIKE 'managed_sync_%'`;/** Whether sync row `sync` names the page of request `write`: its slug, page id or rename source. */const NAMES_PAGE = (sync: string, write: string) => `(${sync}.source_id=${write}.source_id AND (${sync}.slug=${write}.slugOR ${sync}.page_id=${write}.page_id OR ${sync}.intent->'renameFrom'->>'slug'=${write}.slug))`;diff --git a/src/core/persistence/legacy-sync-failures.ts b/src/core/persistence/legacy-sync-failures.tsnew file mode 100644index 0000000000..13626dee66--- /dev/null+++ b/src/core/persistence/legacy-sync-failures.ts@@ -0,0 +1,57 @@+/**+ * #6543 D5 (+ #6518): rows the pre-managed sync left in the local ledger (`sync-failures.jsonl`) on a managed brain.+ * A managed sync never retries them, so without this they stayed `auto_skipped` forever.+ *+ * - `settleLegacySyncFailures` runs after a successful managed sync of one source. It reconciles each legacy row on its+ * own with the #6288 settle rule (`unsettledReason`: the imported commit holds the file and a live page claims it with+ * no hold, or the file is gone and no page claims it). A row recorded on a commit this checkout does not have (a+ * replaced source), a sentinel row, and any row whose evidence cannot be read are kept, as are files the sync did not+ * index or that are held. Mirror rows (`managed_cursor_key`) whose durable failure is gone are pruned only after the+ * durable lookup succeeded, and only rows written before that lookup began.+ * - `legacyLedgerRows` / `legacyLedgerNote` are what `--retry-failed` and doctor `sync_failures` print about them.+ */+import type { BrainEngine } from '../engine.ts';+import { clearFailures, clearManagedSyncFailure, loadSyncFailures, unacknowledgedSyncFailures, type SyncFailure } from '../sync-failure-ledger.ts';+import { syncGit } from './sync-discovery.ts';+import { unsettledReason, type ManagedSyncImported } from './sync-failures.ts';++/** Unacknowledged legacy (pre-managed) ledger rows, optionally for one source. */+export function legacyLedgerRows(sourceId?: string, entries: SyncFailure[] = loadSyncFailures()): SyncFailure[] {+ return unacknowledgedSyncFailures(entries).filter(row => !row.managed_cursor_key && (sourceId === undefined || row.source_id === sourceId));+}++/** Doctor's suffix for the legacy rows among the unresolved failures of a managed brain; empty when there are none. */+export function legacyLedgerNote(rows: SyncFailure[]): string {+ if (!rows.length) return '';+ const sources = [...new Set(rows.map(row => row.source_id))].sort();+ return ` ${rows.length} of these are legacy ledger row(s) recorded by the pre-managed sync (${sources.join(', ')}), which a managed sync does not retry: `+ + `the next successful ${sources.map(id => `gbrain sync --source ${id}`).join(' / ')} settles every one whose file it imported; `+ + 'the rest name files it did not index, held files, or a replaced source, and stay listed.';+}++export async function settleLegacySyncFailures(engine: BrainEngine, run: ManagedSyncImported): Promise<{ settled: number; prunedMirrors: number }> {+ const lookupStarted = new Date().toISOString();+ const entries = loadSyncFailures().filter(row => row.source_id === run.sourceId);+ const settled: string[] = [];+ const commits = new Map<string, boolean>();+ for (const row of legacyLedgerRows(run.sourceId, entries)) {+ if (!row.commit || row.path.startsWith('<')) continue;+ if (!commits.has(row.commit)) {+ let known = false;+ try { known = syncGit(run.gitRoot, ['cat-file', '-t', row.commit]).trim() === 'commit'; } catch { /* not in this checkout */ }+ commits.set(row.commit, known);+ }+ if (!commits.get(row.commit)) continue;+ const reason = await unsettledReason(engine, run, { source_id: row.source_id, source_incarnation: run.incarnation, path: row.path } as Parameters<typeof unsettledReason>[2])+ .catch(() => 'unknown');+ if (!reason) settled.push(row.path);+ }+ if (settled.length) clearFailures(run.sourceId, settled);+ const mirrors = entries.filter(row => row.managed_cursor_key && row.ts < lookupStarted);+ if (!mirrors.length) return { settled: settled.length, prunedMirrors: 0 };+ const durable = new Set((await engine.executeRaw<{ fingerprint: string }>(+ "SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint = ANY($1::text[])", [mirrors.map(row => row.managed_cursor_key!)])).map(row => row.fingerprint));+ const stale = mirrors.filter(row => !durable.has(row.managed_cursor_key!));+ for (const row of stale) clearManagedSyncFailure(row.managed_cursor_key!);+ return { settled: settled.length, prunedMirrors: stale.length };+}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 4c946a11c0..1d16e151c5 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -26,6 +26,7 @@ import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.tsimport { clearDrainStep, DrainPassAbandoned, readDrainStep } from './drain-step.ts';import { PUBLICATION_CEILING_DEFAULT_MS, readPublicationCeilingMs } from './publication-deadline.ts';import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';+import { describeHostConsumer, headBlockedNext, headBlockerText, headClaimability, type HeadBlocker } from './head-blocker.ts';export type DrainOutcome = 'synced' | 'resumable' | 'blocked';/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */@@ -79,9 +80,13 @@ export interface DrainStall {blocked_reason: string | null;head_request_id: string | null;head_state: string | null;- claimable_here: boolean;+ /** #6543 (B2): whether a consumer here could claim the head now; null when the probe could not read it (printed `unknown`). */+ claimable_here: boolean | null;owner_is_this_host: boolean | null;stalled_seconds: number;+ /** #6543 (B2): the predicate keeping a queued head unclaimed, and this host's consumer as the stall line names it. */+ blocked_by?: HeadBlocker | null;+ consumer?: string | null;/** #6278: the head claim's phase, step and wait cause (null when its owner stamped none). */phase?: DrainClaim['phase'];step?: string | null;@@ -92,7 +97,7 @@ export interface DrainStall {* (`restart_required`, a root barrier past the ceiling); `preparation_overdue` is kept for an owner on another host.* #6423: `no_admission` is a pass that admitted nothing and left no unfinished request for the whole no-progress window.*/- cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'no_admission';+ cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'no_admission' | 'head_blocked';/** #6405/#6423: the in-pass governor ended a pass that never returned (the pass was aborted and its late result is ignored). */in_pass?: boolean;/** #6317: the head owner as the stamp names it, so the stop can say which process to restart. */@@ -266,7 +271,7 @@ export interface StallProbe {*/fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'>; claim?: DrainClaim | null } | null>;/** #6278: the source's head while a pass runs (its oldest running request, else its oldest queued one); null when nothing is unfinished. Bounded; may reject. */- head?(): Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null } | null>;+ head?(): Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null; claimable_here?: boolean | null; blocked_by?: HeadBlocker | null; consumer?: string } | null>;/** #6317: the head owner's heartbeat row on this host, or null (no row: an older owner, PGLite, the table absent, or another host). Never rejects. */owner?(claim: DrainClaim): Promise<DrainOwnerRow | null>;/** #6317: whether a consumer here could reclaim a lapsed head: this process's own, or a live full row on this host. Never rejects. */@@ -301,7 +306,8 @@ export interface DrainInput {* #6278: the line the drain prints while nothing commits, naming the head's step, wait cause and allowance. #6317: past the* allowance it names the owner (kind, pid), the last statement and the ceiling the drain waits for (B2, C3).*/-function stallText(index: number, total: number | null, stalledMs: number, claim: DrainClaim | null, headState: string | null): string {+function stallText(index: number, total: number | null, stalledMs: number, claim: DrainClaim | null, headState: string | null,+ seen: { blocked_by?: HeadBlocker | null; consumer?: string | null } = {}): string {const live = !!claim && !claim.lapsed && claim.phase === 'preparing';const overdue = live && stalledMs >= claim.allowance_ms;const owner = claim?.owner_pid !== null && claim?.owner_pid !== undefined ? `${claim.owner_kind ?? 'owner'} pid ${claim.owner_pid}` : null;@@ -309,7 +315,8 @@ function stallText(index: number, total: number | null, stalledMs: number, claim+ `${claim?.waiting_on && claim.waiting_on !== 'unknown' ? ` (waiting on ${claim.waiting_on})` : ''}${claim?.lapsed ? ' (claim lapsed: owner missing)' : ''}`+ `${overdue && owner ? ` · held by ${owner}` : ''}${overdue && claim.last_sql ? ` · last_sql ${claim.last_sql.label}${claim.last_sql.age_ms === null ? '' : ` ${Math.round(claim.last_sql.age_ms / 1000)}s ago`}` : ''}`+ `${live ? overdue ? ` · past the ${formatDuration(Math.round(claim.allowance_ms / 1000))} allowance; the root is freed at the ${formatDuration(Math.round(claim.ceiling_ms / 1000))} ceiling`- : ` · allowed ${formatDuration(Math.round(claim.allowance_ms / 1000))}` : ''}`;+ : ` · allowed ${formatDuration(Math.round(claim.allowance_ms / 1000))}` : ''}`+ + `${seen.consumer ? ` · consumer=${seen.consumer}` : ''}${seen.blocked_by ? ` · blocked_by=${headBlockerText(seen.blocked_by)}` : ''}`;}/** Re-enter `pass` until the managed cursor is done, the caller stops it, or it is blocked. */@@ -340,7 +347,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {if (tickAt - lastCommitAt < every || tickAt - lastLine < every) return;if (stall) {lastLine = tickAt;- serr(stallText(index, total, Math.max(tickAt - stall.since, stall.claim?.step_age_ms ?? 0), stall.claim, stall.stallInfo.head_state));+ serr(stallText(index, total, Math.max(tickAt - stall.since, stall.claim?.step_age_ms ?? 0), stall.claim, stall.stallInfo.head_state, stall.stallInfo));return;}if (!inPass || !input.probe?.head || readingHead) return;@@ -349,7 +356,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {Promise.resolve().then(() => probe.head!()).then(head => {if (!head || !inPass || stall || clock() - lastCommitAt < every || tickAt - lastLine < every) return;lastLine = tickAt;- serr(stallText(index, total, head.claim?.step_age_ms ?? clock() - lastCommitAt, head.claim, head.head_state));+ serr(stallText(index, total, head.claim?.step_age_ms ?? clock() - lastCommitAt, head.claim, head.head_state, head));}).catch(() => undefined).finally(() => { readingHead = false; });}, every) : null;stallLine?.unref?.();@@ -387,12 +394,13 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {const passSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;clearDrainStep();const running = Promise.resolve().then(() => input.pass(passSignal, onProgress));- let timer: ReturnType<typeof setInterval> | null = null, probing = false, key: string | null = null, keySince = passStartedAt;+ let timer: ReturnType<typeof setInterval> | null = null, probing = false, key: string | null = null, keySince = passStartedAt, blockedKey: string | null = null;+ const governEvery = input.governMs ?? Math.min(every, GOVERN_EVERY_MS), blockerAfter = input.governMs ?? GOVERN_EVERY_MS;const stopped = new Promise<{ stall: DrainStall }>(resolve => {const stop = (stall: DrainStall) => { if (timer) clearInterval(timer); timer = null; controller.abort(new DrainPassAbandoned(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };timer = setInterval(() => {const quietSince = Math.max(lastCommitAt, passStartedAt);- if (probing || clock() - quietSince < Math.min(noProgressMs, ceilingMs)) return;+ if (probing || clock() - quietSince < Math.min(noProgressMs, ceilingMs, blockerAfter)) return;probing = true;const head = input.probe?.head? Promise.race([Promise.resolve().then(() => input.probe!.head!()), new Promise<never>((_, reject) => setTimeout(() => reject(new Error('head read timed out')), Math.min(GOVERN_PROBE_MS, noProgressMs)).unref?.())])@@ -404,7 +412,14 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {const head = read.ok ? read.value : null, claim = head?.claim ?? null;const step = readDrainStep();const base = { request_id: head?.request_id ?? 'none', state: head?.head_state ?? 'none', blocked_reason: null, head_request_id: head?.request_id ?? null,- head_state: head?.head_state ?? null, claimable_here: false, owner_is_this_host: null, in_pass: true } as const;+ head_state: head?.head_state ?? null, claimable_here: !read.ok ? null : head?.claimable_here === undefined ? false : head.claimable_here, owner_is_this_host: null, in_pass: true,+ blocked_by: head?.blocked_by ?? null, consumer: head?.consumer ?? null };+ // #6543 (B2): an intervention-required blocker on a queued head, read on two ticks in a row, stops the drain now; live blockers keep the wait below.+ const blocker = head?.head_state === 'queued' && head.blocked_by?.intervention ? head.blocked_by : null;+ const seen = blocker ? `${head!.request_id}|${blocker.predicate}|${blocker.ids.join(',')}` : null;+ if (blocker && seen === blockedKey) { stop({ ...base, stalled_seconds: Math.round(quiet / 1000), cause: 'head_blocked' }); return; }+ blockedKey = seen;+ if (quiet < Math.min(noProgressMs, ceilingMs)) return;if (claim && !claim.lapsed && claim.phase === 'publishing') {const age = claim.step_age_ms ?? quiet;if (age < ceilingMs) return;@@ -423,7 +438,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {waiting_on: claim?.waiting_on ?? null, cause: read.ok && !head ? 'no_admission' : claim?.lapsed ? 'owner_missing' : 'no_progress',owner_pid: claim?.owner_pid ?? null, owner_kind: claim?.owner_kind ?? null, owner_nonce: claim?.owner_nonce ?? null, last_sql: sql });}).finally(() => { probing = false; });- }, input.governMs ?? Math.min(every, GOVERN_EVERY_MS));+ }, governEvery);timer.unref?.();});running.catch(() => undefined);@@ -516,6 +531,9 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {if (!stall || stall.key !== print.key) stall = { key: print.key, since: clock(), passes: 0, claim, stallInfo: print.stall };else {stall.claim = claim; stall.stallInfo = print.stall;+ if (print.stall.blocked_by?.intervention && clock() - stall.since >= (input.governMs ?? GOVERN_EVERY_MS)) {+ return finish(result, 'blocked', 'drain_stalled', { stall: { ...print.stall, stalled_seconds: Math.round((clock() - stall.since) / 1000), cause: 'head_blocked' } });+ }// #6278: a live preparation (its owner still renews) is allowed its budget plus grace; renewals themselves never count as// progress (the key ignores lease columns). A lapsed claim or an unstamped head keeps the plain no-progress window.const live = !!claim && !claim.lapsed && claim.phase !== null;@@ -619,10 +637,10 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallPlet budgets: Promise<{ syncMs: number; maintenanceMs: number; ceilingMs: number }> | undefined;const describe = async (requestId: string, row: NonNullable<Awaited<ReturnType<typeof read>>>['row']): Promise<Omit<DrainStall, 'stalled_seconds'>> => {const { localHostId } = await import('./identity.ts');- const { hasClaimableWrite } = await import('./journal.ts');const host = localHostId();return { request_id: requestId, state: row.state, blocked_reason: row.blocked_reason, head_request_id: row.head_id, head_state: row.head_state,- claimable_here: await hasClaimableWrite(engine, host).catch(() => false), owner_is_this_host: row.owner_host_id === null ? null : row.owner_host_id === host };+ ...await headClaimability(engine, { id: row.head_id, state: row.head_state }, host, { timeoutMs: HEAD_READ_TIMEOUT_MS }), consumer: await describeHostConsumer(engine),+ owner_is_this_host: row.owner_host_id === null ? null : row.owner_host_id === host };};return {async blockedHead(result) {@@ -667,7 +685,11 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallPJOIN LATERAL (SELECT e.id, e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests eWHERE e.worktree_id = b.worktree_id AND e.state IN ('queued','running','recovering') ORDER BY (e.state <> 'running'), e.sequence LIMIT 1) h ON trueWHERE b.source_id = $1`, [sourceId], { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) });- return row ? { head_state: row.head_state, request_id: row.head_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))) } : null;+ if (!row) return null;+ const { localHostId } = await import('./identity.ts');+ const bound = { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) };+ return { head_state: row.head_state, request_id: row.head_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))),+ ...await headClaimability(engine, { id: row.head_request_id, state: row.head_state }, localHostId(), bound), consumer: await describeHostConsumer(engine, { signal: bound.signal }) };} } : {}),};}@@ -842,6 +864,11 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: swhy: `The drain could not read its write's state from the database${wait ? ` (${wait.reason}: ${wait.why})` : ''}. The accepted write keeps its request ID. Fix database access, then rerun.`,...(docs ? { docs } : {}) };}+ // #6543 (B2): a queued head no consumer can claim until an operator clears its blocker; `fix` carries the predicate's recovery.+ if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'head_blocked' && d.stall.blocked_by) {+ return { ...headBlockedNext(d.stall.blocked_by, d.stall.head_request_id, d.stall.stalled_seconds, sourceId, resumeCommand), ...estimate, code: 'drain_stalled', cause: 'head_blocked',+ docs: ERROR_CATALOGUE.sync_drain_head_blocked.docs };+ }// #6317 (B2): a live same-host owner stopped the drain at the ceiling or on its own wedged verdict; the fix is to wait for the ceiling// (the root is freed there and the next pass holds the entry) or, past it, to restart the named process.if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'owner_wedged_here') {@@ -929,7 +956,8 @@ export function formatDrainSummary(result: SyncResult, resumeCommand: string, soelse if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`+ `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}${d.stall.step ? `, step=${d.stall.step}` : ''}${d.stall.waiting_on ? `, waiting_on=${d.stall.waiting_on}` : ''}`+ `${d.stall.last_sql ? `, last_sql=${d.stall.last_sql.label}${d.stall.last_sql.age_ms === null ? '' : ` (${Math.round(d.stall.last_sql.age_ms / 1000)}s ago)`}` : ''}`- + `${d.stall.cause ? `, cause=${d.stall.cause}` : ''}${d.stall.owner_pid ? `, owner=${d.stall.owner_kind ?? 'process'} pid ${d.stall.owner_pid}` : ''}; claimable here: ${d.stall.claimable_here ? 'yes' : 'no'}.`);+ + `${d.stall.cause ? `, cause=${d.stall.cause}` : ''}${d.stall.owner_pid ? `, owner=${d.stall.owner_kind ?? 'process'} pid ${d.stall.owner_pid}` : ''}; claimable here: ${d.stall.claimable_here === null ? 'unknown' : d.stall.claimable_here ? 'yes' : 'no'}`+ + `${d.stall.blocked_by ? `, blocked_by=${headBlockerText(d.stall.blocked_by)}` : ''}${d.stall.consumer ? `, consumer=${d.stall.consumer}` : ''}.`);const next = drainNext(result, resumeCommand, sourceId);if (next) lines.push(` Next: ${next.command}${next.safe_to_loop ? ' (safe to rerun in a loop)' : ''}`, ` Why: ${next.why}`);return lines;diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.tsindex 3c208c2203..9ba3fa1291 100644--- a/src/core/persistence/sync-failures.ts+++ b/src/core/persistence/sync-failures.ts@@ -80,7 +80,7 @@ function blobAt(gitRoot: string, commit: string, path: string): string | null {* failure is settled when its file exists there and the database holds a live page for it with no hold on the path, or* when the file is gone there and no live page claims it.*/-async function unsettledReason(engine: BrainEngine, run: ManagedSyncImported, failure: ManagedSyncFailure): Promise<string | null> {+export async function unsettledReason(engine: BrainEngine, run: ManagedSyncImported, failure: Pick<ManagedSyncFailure, 'source_id' | 'source_incarnation' | 'path'>): Promise<string | null> {if (failure.source_id !== run.sourceId || failure.source_incarnation !== run.incarnation) return 'source_changed';if (failure.path.startsWith('<')) return 'no_recorded_file';const gitPath = syncGitPath(run, failure.path);diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 79d24c1b3d..b3d9966702 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -137,7 +137,7 @@ async function configuredMs(engine: BrainEngine, flag: number | undefined, env:return Math.floor(raw);}-function refreshLockPath(worktreeId: string): string { return join(persistenceHome(), 'locks', `refresh-${worktreeId}.lock`); }+export function refreshLockPath(worktreeId: string): string { return join(persistenceHome(), 'locks', `refresh-${worktreeId}.lock`); }async function readActiveRefresh(engine: BrainEngine, worktreeId: string): Promise<WorktreeRefreshRow | null> {const [row] = await engine.executeRaw<WorktreeRefreshRow>(`SELECT * FROM persistence_worktree_refreshesdiff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 717b76e875..80d121fd1e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -32,6 +32,8 @@ import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricinimport { shellQuote, type Action } from '../agent-output.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { RepairKindSpec } from './registry.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';+import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'] as const;export type RepairKind = typeof REPAIR_KINDS[number];@@ -149,6 +151,8 @@ export interface RepairResult {failed: RepairFailedItem[];complete: boolean;stopped?: { reason: string; message: string; fix?: Action };+ /** #6543 (D1): accepted repairs still unpublished when the run stopped; the cursor stays before the first, and a rerun replays the same requests. */+ pending?: Array<{ item: string; request_id: string }>;apply_command: string;/** Kinds with a report hook: items repaired by this run (dry run: 0). `complete` keeps its meaning (every pending item was attempted). */repaired?: number;@@ -262,7 +266,9 @@ function writerHeld(error: unknown): error is OperationError {export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;- spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number }): Promise<RepairResult> {+ spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;+ /** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */+ publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {const { repairSpec, explicitKindRequired } = await import('./registry.ts');const spec = opts.spec ?? repairSpec(handler.kind);if (spec?.explicit_only && opts.explicit !== true) throw explicitKindRequired(handler.kind);@@ -313,30 +319,65 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst runId = storedRunId ?? randomUUID();if (!storedRunId) await writeCursor(ctx.engine, handler.kind, scope, resumed, runId, opts.expect);let llmSpent = 0;+ // #6543 (D1): accepted-but-pending items; the cursor stays before the first of them, and every stop settles them first.+ const unresolved: PendingRepair[] = [];+ const settleMs = ctx.writeWaitMs ?? 5_000, window = admits ? await repairAdmissionWindow(ctx.engine) : 1;+ let latest: RepairCursor | null = null;+ const cursorNow = () => unresolved.length ? unresolved[0].index ? pending[unresolved[0].index - 1].cursor : resumed : latest;+ const advance = (cursor: RepairCursor) => { latest = cursor; return writeCursor(ctx.engine, handler.kind, scope, cursorNow(), runId, opts.expect); };+ const settle = async (target: number): Promise<boolean> => {+ if (!unresolved.length) return true;+ for (const done of await settleRepairReceipts(ctx.engine, unresolved, target, settleMs, now)) {+ unresolved.splice(unresolved.findIndex(open => open.request_id === done.request_id), 1);+ if (done.state === 'committed') {+ result.applied++;+ if (result.outcomes) result.outcomes = { ...result.outcomes, committed_after_wait: (result.outcomes.committed_after_wait ?? 0) + 1 };+ } else if (done.error_code === 'revision_conflict') result.skipped++;+ else result.failed.push({ item: `${done.item.source_id}:${done.item.slug}`, source_id: done.item.source_id, slug: done.item.slug, reason: done.error_code ?? done.state,+ message: redactConnectionInfo(done.error_message ?? `The write ended ${done.state}.`), retry: 'next_full_scan' });+ }+ if (latest) await writeCursor(ctx.engine, handler.kind, scope, cursorNow(), runId, opts.expect);+ return unresolved.length <= target;+ };+ const pendingStop = (why: string) => {+ result.pending = unresolved.map(({ item, request_id }) => ({ item: `${item.source_id}:${item.slug}`, request_id }));+ const [first] = unresolved;+ return { reason: 'write_pending', message: (unresolved.length === 1 ? `The repair of ${first.item.source_id}:${first.item.slug} was accepted and is still pending publication`+ : `${unresolved.length} repairs were accepted and are still pending publication (first: ${first.item.source_id}:${first.item.slug})`)+ + `${why}. Rerun \`${result.apply_command}\` to resume; the same ${unresolved.length === 1 ? 'request is' : 'requests are'} replayed.` };+ };+ const stopAfterSettle = async (stopped: NonNullable<RepairResult['stopped']>): Promise<RepairResult> => {+ if (!await settle(0)) stopped = { ...stopped, message: `${stopped.message} ${pendingStop('').message}` };+ result.stopped = stopped;+ return finish();+ };for (const [index, item] of pending.entries()) {const remaining = pending.length - index;- if (opts.deadline !== undefined && now() >= opts.deadline) {- result.stopped = { reason: 'time_budget', message: `Stopped before ${item.source_id}:${item.slug}: this run reached its time budget (${remaining} item(s) still pending). `- + `The next run resumes; rerun \`${result.apply_command}\` to continue now.` };+ // A preview-bound kind may retire its approved set with its last item, so every earlier receipt settles before that item runs.+ const lastApproved = !!opts.expect && index === plan.items.length - 1;+ if (unresolved.length && (unresolved.length >= window || lastApproved) && !await settle(lastApproved ? 0 : window - 1)) {+ result.stopped = pendingStop(settleMs ? `; nothing published for ${Math.round(settleMs / 1000)}s` : '');return finish();}+ if (opts.deadline !== undefined && now() >= opts.deadline) {+ return stopAfterSettle({ reason: 'time_budget', message: `Stopped before ${item.source_id}:${item.slug}: this run reached its time budget (${remaining} item(s) still pending). `+ + `The next run resumes; rerun \`${result.apply_command}\` to continue now.` });+ }const allowanceLeft = opts.maxLlmUsd !== undefined ? opts.maxLlmUsd - llmSpent : undefined;if (llm && allowanceLeft !== undefined && (llmSpent >= opts.maxLlmUsd! || (item.llm_usd !== undefined && item.llm_usd > allowanceLeft + 1e-9))) {- result.stopped = { reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance `+ return stopAfterSettle({ reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance `+ `${llmSpent >= opts.maxLlmUsd! ? 'is used up' : `cannot cover its estimate ($${item.llm_usd!.toFixed(4)})`} `- + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` };- return finish();+ + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` });}const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) : undefined;if (full) {const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES;const needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;- result.stopped = { reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `- + `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` };- return finish();+ return stopAfterSettle({ reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `+ + `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` });}try {- const applied = await handler.apply({ ...ctx, sourceId: item.source_id }, item, { embed: opts.embed === true, runId,+ const applied = await handler.apply({ ...ctx, sourceId: item.source_id, ...(unresolved.length ? { writeWaitMs: 0 } : {}) }, item, { embed: opts.embed === true, runId,...(llm && opts.maxLlmUsd !== undefined ? { llmAllowanceUsd: opts.maxLlmUsd - llmSpent } : {}),...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });if (llm && typeof applied === 'object' && applied.llm_usd) {@@ -353,9 +394,8 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sif (typeof applied === 'object' ? applied.applied : applied) result.applied++;else result.skipped++;if (typeof applied === 'object' && applied.stop) {- await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId, opts.expect);- result.stopped = applied.stop;- return finish();+ await advance(item.cursor);+ return stopAfterSettle(applied.stop);}} catch (error) {// A page edited since planning is left for the next full scan.@@ -371,17 +411,32 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s}continue;}+ const receipt = acceptedPendingReceipt(error);+ if (receipt) {+ // #6543 (D1): an accepted write publishes whether or not this run waits; keep going while a consumer here publishes.+ unresolved.push({ index, item, request_id: receipt.request_id });+ const owner = await (opts.publicationOwner ?? (() => repairPublicationOwner(ctx.engine)))();+ if (owner.alive) { await advance(item.cursor); continue; }+ await writeCursor(ctx.engine, handler.kind, scope, cursorNow(), runId, opts.expect);+ result.stopped = { ...pendingStop(`, and nothing here publishes it (${owner.owner})`),+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', item.source_id, '--json'], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: `No consumer on this host publishes the accepted repairs (${owner.owner}). Status names the owner, read-only; restart it, then rerun ${result.apply_command}.` } };+ return finish();+ }if (error instanceof OperationError && error.code === 'write_pending') {result.stopped = { reason: 'write_pending', message: `The repair of ${item.source_id}:${item.slug} was accepted and is still pending publication. `+ `Rerun \`${result.apply_command}\` to resume; the same request is replayed.` };return finish();}if (!writerHeld(error)) throw error;- result.stopped = { reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `- + `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` };- return finish();+ return stopAfterSettle({ reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `+ + `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` });}- await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId, opts.expect);+ await advance(item.cursor);+ }+ if (!await settle(0)) {+ result.stopped = pendingStop(settleMs ? `; nothing published for ${Math.round(settleMs / 1000)}s` : '');+ return finish();}result.complete = pending.length === plan.items.length;if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null, null, opts.expect);diff --git a/src/core/repair/settle.ts b/src/core/repair/settle.tsnew file mode 100644index 0000000000..c9e7e968fa--- /dev/null+++ b/src/core/repair/settle.ts@@ -0,0 +1,65 @@+/**+ * #6543 (D1): a repair apply no longer stops at the first accepted-but-pending write. Once one item is pending, later items+ * are admitted without a publication wait, at most `repairAdmissionWindow` receipts stay unresolved at once (outstanding-capacity+ * backpressure), and the receipts settle against one shared wait budget: the configured write wait with no receipt turning+ * terminal. A run stops at the first pending write, as before, only when no consumer here publishes (none running, or the+ * one running reports `restart_required`).+ */+import type { BrainEngine } from '../engine.ts';+import { readJournalLimits } from '../persistence/limits.ts';+import { isTerminalWriteState } from '../persistence/types.ts';+import type { RepairItem } from './core.ts';++export interface PendingRepair { index: number; item: RepairItem; request_id: string }+export interface SettledRepair extends PendingRepair { state: string; error_code: string | null; error_message: string | null }++/** Unresolved receipts one run keeps at once: half the principal's outstanding-request cap, at most 64. */+export async function repairAdmissionWindow(engine: BrainEngine): Promise<number> {+ const limits = await readJournalLimits(engine);+ return Math.max(1, Math.min(64, Math.floor(limits.principalOutstanding / 2)));+}++/**+ * Waits until at most `target` receipts remain unresolved, or none turned terminal for `budgetMs`. Returns the receipts that+ * turned terminal (committed or not); the rest stay pending and keep their request ids.+ */+export async function settleRepairReceipts(engine: BrainEngine, unresolved: readonly PendingRepair[], target: number, budgetMs: number,+ now: () => number = Date.now): Promise<SettledRepair[]> {+ const open = new Map(unresolved.map(pending => [pending.request_id, pending]));+ const settled: SettledRepair[] = [];+ let progressAt = now(), delay = 50;+ for (;;) {+ const rows = await engine.executeRaw<{ request_id: string; state: string; error_code: string | null; error_message: string | null }>(+ `SELECT DISTINCT ON (request_id) request_id::text AS request_id, state, error_code, error_message FROM persistence_requests+ WHERE request_id=ANY($1::uuid[]) ORDER BY request_id, sequence DESC`, [[...open.keys()]]);+ for (const row of rows) {+ const pending = open.get(row.request_id);+ if (!pending || !isTerminalWriteState(row.state as never)) continue;+ open.delete(row.request_id);+ settled.push({ ...pending, state: row.state, error_code: row.error_code, error_message: row.error_message });+ progressAt = now(); delay = 50;+ }+ const left = budgetMs - (now() - progressAt);+ if (open.size <= target || left <= 0) return settled;+ await new Promise(resolve => setTimeout(resolve, Math.min(delay, left)));+ delay = Math.min(delay * 2, 500);+ }+}++/** Who publishes this run's admissions: this process's consumer or a live full one on this host; dead when none does or it reports restart_required. */+export async function repairPublicationOwner(engine: BrainEngine): Promise<{ alive: boolean; owner: string }> {+ const { persistenceConsumerStatus } = await import('../persistence/service.ts');+ const local = persistenceConsumerStatus(engine) as { state: string; restart_required?: boolean; consumer_election?: { mode: string } };+ const mode = local.consumer_election?.mode;+ if (local.state === 'open' && (!mode || mode === 'full' || mode === 'promoted')) {+ return local.restart_required ? { alive: false, owner: 'this process, which reports restart_required' } : { alive: true, owner: 'this process' };+ }+ const { existingLocalHostId } = await import('../persistence/identity.ts');+ const { listHostConsumers } = await import('../persistence/consumer-heartbeat.ts');+ const host = existingLocalHostId();+ const rows = host ? await listHostConsumers(engine, host).catch(() => []) : [];+ const row = rows.find(r => !r.self && (r.mode === 'full' || r.mode === 'promoted') && r.liveness === 'live');+ if (!row) return { alive: false, owner: 'no live consumer on this host' };+ const owner = `the ${row.kind} process (pid ${row.pid})`;+ return row.restart_required ? { alive: false, owner: `${owner}, which reports restart_required` } : { alive: true, owner };+}diff --git a/src/core/serve-behavior-notice.ts b/src/core/serve-behavior-notice.tsnew file mode 100644index 0000000000..28bfdf4558--- /dev/null+++ b/src/core/serve-behavior-notice.ts@@ -0,0 +1,56 @@+/**+ * #6543 C2: `gbrain serve` writes the behavior changes an upgrade turned on to its own log (stderr) once per process,+ * so an operator who only watches the serve log sees them too. Read-only toward delivery: the brain baseline is read+ * with `persist: false`, and the CLI/stdio markers and the HTTP `config` row are never claimed, so the next CLI command+ * and every MCP client still get their own notice. The serve log keeps its own marker under+ * GBRAIN_HOME/notices/behavior-changes/ (`<notice id>.<brain key>.serve_log.shown`) so a restart of the same release+ * does not repeat it. Never throws.+ */+import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { gbrainPath, type GBrainConfig } from './config.ts';+import {+ BEHAVIOR_NOTICE_CODE, BEHAVIOR_NOTICE_ID, behaviorBrainKey, behaviorChangesNotice, brainBaseline, chainDisclosure, compareReleases, currentBrainId,+} from './behavior-change-notice.ts';++let loggedThisProcess = false;++export async function logServeBehaviorNotice(+ engine: BrainEngine,+ cfg: GBrainConfig | null,+ opts: { write?: (line: string) => void; now?: number } = {},+): Promise<boolean> {+ if (loggedThisProcess) return false;+ loggedThisProcess = true;+ try {+ const brainKey = behaviorBrainKey(cfg, await currentBrainId());+ const dir = gbrainPath('notices', 'behavior-changes');+ const prefix = `${BEHAVIOR_NOTICE_CODE}@`, suffix = `.${brainKey}.serve_log.shown`;+ let after = await brainBaseline(engine, brainKey, { persist: false, now: opts.now });+ try {+ for (const name of readdirSync(dir)) {+ if (!name.startsWith(prefix) || !name.endsWith(suffix)) continue;+ const release = name.slice(prefix.length, -suffix.length);+ if (/^\d+(\.\d+)*$/.test(release) && compareReleases(release, after) > 0) after = release;+ }+ } catch { /* no markers yet */ }+ const notice = behaviorChangesNotice(await chainDisclosure(engine, cfg), { after });+ if (!notice) return false;+ try {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, `${BEHAVIOR_NOTICE_ID}${suffix}`), `${new Date(opts.now ?? Date.now()).toISOString()}\n`, { mode: 0o600, flag: 'wx' });+ } catch (e) {+ if ((e as NodeJS.ErrnoException)?.code === 'EEXIST') return false;+ }+ (opts.write ?? (line => process.stderr.write(line)))(`[gbrain serve] notice=${notice.code}: ${notice.why}\n`);+ return true;+ } catch {+ return false;+ }+}++/** Test seam: forget this process's look. */+export function __resetServeBehaviorNoticeForTests(): void {+ loggedThisProcess = false;+}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 61543b7033..9a8a190fd2 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6123,7 +6123,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/image-asset-resolver-6543.test.ts b/test/image-asset-resolver-6543.test.tsnew file mode 100644index 0000000000..562d089e8b--- /dev/null+++ b/test/image-asset-resolver-6543.test.ts@@ -0,0 +1,147 @@+/**+ * #6543 D3: one case-insensitive resolver for recorded image paths, shared by doctor `image_assets` and the #6539+ * `embed --stale --images` sweep. The exact recorded path wins; otherwise a bounded case-insensitive walk finds the+ * file and returns its real-case source-relative path separately from the containment verdict. Two case-fold matches+ * refuse (nothing imported or rewritten); a symlink out of the source root never resolves; one source's root never+ * resolves another source's file.+ *+ * Case-sensitive filesystem only (Linux CI); darwin and win32 skip, since their default filesystems fold case.+ *+ * Regression that fails it: the sweep reporting `IMG_1453.PNG` missing because the slug is lower-case, the managed+ * import recording the lower-case slug as source_path, doctor counting a case-only difference as missing, or a+ * case-fold choice made silently between two files.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resolveRecordedImageFile } from '../src/core/image-asset-resolver.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { embedStaleImages } from '../src/core/embed-stale-images.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { buildChecks } from '../src/commands/doctor.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';++const caseSensitive = process.platform === 'linux';+const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-6543-d3-'));+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const env = { GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' };+const origFetch = globalThis.fetch;+let engine: PGLiteEngine;++function dir(...parts: string[]): string {+ const path = join(home, ...parts); mkdirSync(path, { recursive: true }); return path;+}++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);++beforeEach(() => {+ globalThis.fetch = (async (url: unknown, init?: { body?: string }) => {+ if (!String(url).includes('voyageai.com')) return origFetch(url as string, init as RequestInit);+ const n = (init?.body ? JSON.parse(init.body) as { inputs?: unknown[] } : {}).inputs?.length ?? 1;+ return new Response(JSON.stringify({ data: Array.from({ length: n }, (_, index) => ({ embedding: Array.from({ length: 1024 }, () => 0.1), index })),+ model: 'voyage-multimodal-3', usage: { total_tokens: 10 * n } }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+ __setEmbedTransportForTests((async (args: { values: unknown[] }) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.1)) })) as never);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test-key', VOYAGE_API_KEY: 'test-key' } });+});+afterEach(() => { globalThis.fetch = origFetch; __setEmbedTransportForTests(null); resetGateway(); });++afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});++describe.skipIf(!caseSensitive)('resolveRecordedImageFile', () => {+ test('a lower-case slug finds IMG_1453.PNG and returns the real-case relative path', () => {+ const root = dir(`r-${randomUUID()}`);+ mkdirSync(join(root, 'Media', 'Launches'), { recursive: true });+ writeFileSync(join(root, 'Media', 'Launches', 'IMG_1453.PNG'), PNG);+ expect(resolveRecordedImageFile(root, [null, 'media/launches/img_1453.png'])).toEqual({+ status: 'found', abs: join(root, 'Media', 'Launches', 'IMG_1453.PNG'), relative: 'Media/Launches/IMG_1453.PNG', caseMismatch: true });+ });++ test('the exact recorded path wins over a case variant', () => {+ const root = dir(`r-${randomUUID()}`);+ writeFileSync(join(root, 'a.png'), PNG); writeFileSync(join(root, 'A.PNG'), PNG);+ expect(resolveRecordedImageFile(root, ['A.PNG', 'a.png'])).toMatchObject({ status: 'found', relative: 'A.PNG', caseMismatch: false });+ });++ test('two case-fold matches and no exact one refuse as ambiguous', () => {+ const root = dir(`r-${randomUUID()}`);+ writeFileSync(join(root, 'Shot.png'), PNG); writeFileSync(join(root, 'SHOT.png'), PNG);+ const resolved = resolveRecordedImageFile(root, ['shot.png']);+ expect(resolved.status).toBe('ambiguous');+ expect(resolved.status === 'ambiguous' ? [...resolved.matches].sort() : []).toEqual(['SHOT.png', 'Shot.png']);+ });++ test('a symlink out of the source root never resolves, exactly or case-insensitively', () => {+ const outside = dir(`outside-${randomUUID()}`);+ writeFileSync(join(outside, 'Secret.png'), PNG);+ const root = dir(`r-${randomUUID()}`);+ symlinkSync(outside, join(root, 'Linked'));+ expect(resolveRecordedImageFile(root, ['Linked/Secret.png']).status).toBe('outside_root');+ expect(resolveRecordedImageFile(root, ['linked/secret.png']).status).toBe('outside_root');+ expect(resolveRecordedImageFile(root, ['../' + outside.split('/').at(-1) + '/Secret.png']).status).toBe('missing');+ });++ test('one source root never resolves another source\'s file', () => {+ const a = dir(`a-${randomUUID()}`), b = dir(`b-${randomUUID()}`);+ writeFileSync(join(b, 'Only-B.png'), PNG);+ expect(resolveRecordedImageFile(a, ['only-b.png']).status).toBe('missing');+ expect(resolveRecordedImageFile(b, ['only-b.png'])).toMatchObject({ status: 'found', relative: 'Only-B.png' });+ });+});++async function managedSource(files: Record<string, Buffer>, legacyImages: string[]) {+ const sourceId = `d${randomUUID().replace(/-/g, '').slice(0, 20)}`;+ const root = dir(sourceId);+ execFileSync('git', ['-C', root, 'init', '-q']);+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+ execFileSync('git', ['-C', root, 'add', '-A']);+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'initial']);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [sourceId, root]);+ for (const path of legacyImages) expect((await importImageFile(engine, join(root, path), path, { sourceId, noEmbed: true })).status).toBe('imported');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, root };+}++describe.skipIf(!caseSensitive)('#6543 D3 managed sweep and doctor share the resolver', () => {+ test('the sweep finds a case-mismatched image by slug, imports it under the real case and records that source_path; doctor counts it present', async () => withEnv(env, async () => {+ const { sourceId } = await managedSource({ 'Media/Launches/IMG_1453.PNG': PNG }, ['Media/Launches/IMG_1453.PNG']);+ await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE source_id=$1', [sourceId]);+ await engine.executeRaw('UPDATE files SET storage_path=lower(storage_path) WHERE source_id=$1', [sourceId]);+ const swept = await embedStaleImages(engine, { sourceId, dryRun: false });+ expect(swept).toMatchObject({ candidates: 1, rebuilt: 1, missingFile: 0, failures: 0 });+ const [page] = await engine.executeRaw<{ slug: string; source_path: string | null }>('SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);+ expect(page).toEqual({ slug: 'media/launches/img_1453.png', source_path: 'Media/Launches/IMG_1453.PNG' });+ const check = (await buildChecks(engine, [])).find(c => c.name === 'image_assets')!;+ expect(check.message).not.toMatch(/missing from disk/);+ expect(check.message).not.toContain('--skip-failed');+ }), 120_000);++ test('two case-fold candidates refuse: nothing imported, source_path stays unrecorded, doctor names the ambiguity', async () => withEnv(env, async () => {+ const { sourceId } = await managedSource({ 'Media/Shot.png': PNG, 'Media/SHOT.png': Buffer.concat([PNG, Buffer.from([0])]) }, ['Media/Shot.png']);+ await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE source_id=$1', [sourceId]);+ await engine.executeRaw('UPDATE files SET storage_path=lower(storage_path) WHERE source_id=$1', [sourceId]);+ const swept = await embedStaleImages(engine, { sourceId, dryRun: false });+ expect(swept).toMatchObject({ candidates: 1, rebuilt: 0, failures: 1 });+ expect(swept.failure_samples[0]).toContain('ambiguous');+ const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);+ expect(page.source_path).toBeNull();+ const check = (await buildChecks(engine, [])).find(c => c.name === 'image_assets')!;+ expect(check.status).toBe('warn');+ expect(check.message).toContain('ambiguous');+ expect(check.message).not.toContain('--skip-failed');+ }), 120_000);+});diff --git a/test/image-import-reserved-keys-6543.test.ts b/test/image-import-reserved-keys-6543.test.tsnew file mode 100644index 0000000000..fba5c8ecd8--- /dev/null+++ b/test/image-import-reserved-keys-6543.test.ts@@ -0,0 +1,76 @@+/**+ * #6543 D2: the image importer stops writing the parser-reserved `type`/`title` keys into an image page's stored+ * frontmatter (both live on the page columns already), so `stale_frontmatter_keys` converges on a multimodal brain.+ * The doctor message names the release that made the keys inert (v0.60.177.0) and, with several sources affected,+ * fixes with the all-sources preview instead of the first source only.+ *+ * Regression that fails it: the importer writing `type`/`title` again (doctor warns on a freshly imported PNG), or the+ * fix naming only the first source.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { staleFrontmatterKeysCheck } from '../src/commands/doctor/checks/frontmatter-keys.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const dir = mkdtempSync(join(tmpdir(), 'gbrain-6543-d2-'));+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function source(): Promise<{ sourceId: string; root: string }> {+ const sourceId = `s${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(dir, sourceId); mkdirSync(join(root, 'Media'), { recursive: true });+ writeFileSync(join(root, 'Media', 'IMG_1453.PNG'), PNG);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [sourceId, root]);+ return { sourceId, root };+}++test('an imported image page stores no reserved frontmatter key and doctor stale_frontmatter_keys is ok', async () => {+ const { sourceId, root } = await source();+ const result = await importImageFile(engine, join(root, 'Media', 'IMG_1453.PNG'), 'Media/IMG_1453.PNG', { sourceId, noEmbed: true });+ expect(result.status).toBe('imported');+ const [page] = await engine.executeRaw<{ type: string; title: string; frontmatter: Record<string, unknown> }>(+ 'SELECT type, title, frontmatter FROM pages WHERE source_id=$1', [sourceId]);+ expect(page.type).toBe('image');+ expect(page.title).toBe('IMG_1453.PNG');+ expect(page.frontmatter).not.toHaveProperty('type');+ expect(page.frontmatter).not.toHaveProperty('title');+ expect(page.frontmatter).toMatchObject({ mime_type: 'image/png' });+ const check = await staleFrontmatterKeysCheck(engine, [sourceId]);+ expect(check.status).toBe('ok');+});++test('with several sources affected the doctor fix previews every source and the message names v0.60.177.0', async () => {+ const ids: string[] = [];+ for (let i = 0; i < 2; i++) {+ const { sourceId } = await source();+ ids.push(sourceId);+ await engine.putPage('notes/legacy', { type: 'note', title: 'Legacy', compiled_truth: 'Body.', frontmatter: { title: 'Legacy' } }, { sourceId });+ await engine.executeRaw("UPDATE pages SET frontmatter = frontmatter || '{\"type\":\"note\"}'::jsonb WHERE source_id=$1", [sourceId]);+ }+ const check = await staleFrontmatterKeysCheck(engine, ids);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('v0.60.177.0');+ expect(check.message).not.toContain('v0.60.176.0');+ for (const id of ids) expect(check.message).toContain(`${id}: 1`);+ expect(check.fix?.argv).toEqual(['gbrain', 'repair', 'frontmatter-keys']);+});diff --git a/test/persistence-consumer-request-log-6543.test.ts b/test/persistence-consumer-request-log-6543.test.tsnew file mode 100644index 0000000000..c5889fd326--- /dev/null+++ b/test/persistence-consumer-request-log-6543.test.ts@@ -0,0 +1,84 @@+/**+ * #6543 F1: the consumer's `[persistence] phase=` line names the request it is about. Two requests failing+ * the same phase in the same tick each get their own line carrying request_id, principal, slug and+ * elapsed_ms; a repeat of the same request's failure inside the throttle window stays one line.+ *+ * Regression that fails it: a throttle keyed only on phase and code (the second request's line is+ * dropped), or a line without the request identity.+ */+import { afterAll, afterEach, beforeAll, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { admission, fixtures, initializeFixtures, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-request-log-'));+const config: HarnessConfig = {+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),+ seed: 6543, schedules: 0, operations: 0,+ sourceIds: ['request-log-a', 'request-log-b'], principalIds: [randomUUID()],+};+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };+let engine: PGLiteEngine;+const stderr: string[] = [];+let spy: ReturnType<typeof spyOn> | undefined;++beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+}), 120_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++afterEach(() => { spy?.mockRestore(); spy = undefined; stderr.length = 0; });++test('two requests failing the same phase in one tick each log a line naming the request', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const first = await admitWrite(engine, admission(config, sources[0], 'request-log/first', 'first body'));+ const second = await admitWrite(engine, admission(config, sources[1], 'request-log/second', 'second body'));+ spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { stderr.push(String(chunk)); return true; }) as typeof process.stderr.write);+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => {+ throw Object.assign(new Error('synthetic preparer failure'), { code: 'storage_error' });+ }, { hostId: config.hostId, pollMs: 20 });+ try {+ consumer.start();+ await waitFor(async () => (await getWriteRequestById(engine, first.id))?.state === 'failed'+ && (await getWriteRequestById(engine, second.id))?.state === 'failed', { timeoutMs: 5_000 });+ } finally { await consumer.stop(); }+ const lines = stderr.filter(entry => entry.startsWith('[persistence] phase=preparation'));+ for (const row of [first, second]) {+ const line = lines.find(entry => entry.includes(`request_id=${row.request_id}`));+ expect(line).toBeDefined();+ expect(line).toContain(`slug=${row.slug}`);+ expect(line).toContain(`source=${row.source_id}`);+ expect(line).toContain('operation=put_page');+ expect(line).toContain('principal=local_cli');+ expect(line).toMatch(/elapsed_ms=\d+/);+ }+ expect(lines.length).toBe(2);+}), 15_000);++test('the same request failing the same phase again inside the window stays one line', async () => {+ spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { stderr.push(String(chunk)); return true; }) as typeof process.stderr.write);+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { throw new Error('unused'); }, { hostId: randomUUID() });+ const row = { id: randomUUID(), request_id: randomUUID(), principal_kind: 'local_cli', operation: 'put_page', source_id: 's', slug: 'a/b', created_at: new Date() };+ const log = (consumer as unknown as { log(phase: string, code: string, detail?: string, timing?: string, row?: unknown): void }).log.bind(consumer);+ log('publication', 'storage_error', 'boom', '', row);+ log('publication', 'storage_error', 'boom', '', row);+ log('publication', 'storage_error', 'boom', '', { ...row, id: randomUUID(), request_id: randomUUID() });+ expect(stderr.filter(entry => entry.includes(`request_id=${row.request_id}`)).length).toBe(1);+ expect(stderr.length).toBe(2);+ await consumer.stop();+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 62207336c5..1906a6b34a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -113,6 +113,7 @@ test/physical-root-birth-tolerance-6501.test.tstest/purge-fact.test.tstest/purge-global-marker.test.tstest/remediation-manual-only.test.ts+test/repair-apply-pending-6543.test.tstest/repair-embedding-effects.test.tstest/repair-failed-writes-conflict-6429.test.tstest/repair-failed-writes-drift-w411.test.ts@@ -129,6 +130,7 @@ test/source-retire-missing-checkout.test.tstest/source-row-diagnostics.test.tstest/stats-health-source-scope.test.tstest/sync-drain-claims.test.ts+test/sync-drain-head-blocked-6543.test.tstest/sync-drain-inpass-stall.test.tstest/sync-drain-write-capacity.test.tstest/sync-frontmatter-recovery.test.tsdiff --git a/test/repair-apply-pending-6543.test.ts b/test/repair-apply-pending-6543.test.tsnew file mode 100644index 0000000000..35d877d3d1--- /dev/null+++ b/test/repair-apply-pending-6543.test.ts@@ -0,0 +1,211 @@+/**+ * #6543 (D1): `gbrain repair <kind> --apply` stopped at the first accepted-but-pending write, so an approved set of N+ * slow items needed up to N+1 reruns. Now a pending item is kept (its receipt, the cursor before it) and the run goes on:+ * later items are admitted without a publication wait, at most a window of receipts stays unresolved, and they settle+ * against one shared wait budget. Every early stop settles first; a crash leaves the cursor before the first unresolved+ * receipt, so the same command resumes. A run with no live consumer still stops at the first pending write and names it.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { resolveRepairScope, runRepair, type RepairHandler, type RepairItem } from '../src/core/repair/core.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { repairRunner, repairSpec } from '../src/core/repair/registry.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { getCliOptions, setCliOptions } from '../src/core/cli-options.ts';++const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-repair-pending-'));+const quiet = { info() {}, warn() {}, error() {} };++beforeAll(async () => {+ if (testBackends().includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }+ await closePostgres?.();+ rmSync(dataDir, { recursive: true, force: true });+});++const ctxFor = (engine: BrainEngine, sourceId: string, writeWaitMs?: number) => ({ engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: quiet, ...(writeWaitMs === undefined ? {} : { writeWaitMs }) }) as never;+const page = (body: string) => `---\ntype: note\ntitle: Example\n---\n${body}\n`;++async function brain(run: (engine: BrainEngine, source: string) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(dataDir, 'case-'));+ const source = `repair-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%'");+ await engine.executeRaw('UPDATE sources SET archived=true WHERE archived IS NOT TRUE');+ const root = join(dir, source); mkdirSync(root);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await run(engine, source);+ });+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }+ }+}++async function pagesWithHistory(engine: BrainEngine, sourceId: string, slugs: string[]) {+ for (const slug of slugs) await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content: page(`Body of ${slug}.`), request_id: randomUUID() } });+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy','History of '||slug,'' FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])`,+ [sourceId, slugs]), TEST_WRITE_ATTRIBUTION));+}+const marked = async (engine: BrainEngine, sourceId: string) => (await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id=$1 AND timeline LIKE '%gbrain:materialized%' ORDER BY slug`, [sourceId])).map(r => r.slug);+/** Slows the first `first` publications by `slowMs` and every later one by `restMs`. */+function slowPublications(slowMs: number, opts: { first?: number; restMs?: number } = {}) {+ let seen = 0;+ installFaultHook(async point => {+ if (point !== 'consumer:prepared') return;+ const ms = seen++ < (opts.first ?? Infinity) ? slowMs : opts.restMs ?? 0;+ if (ms) await new Promise(resolve => setTimeout(resolve, ms));+ });+}+async function withWriteWait<T>(writeWaitMs: number, run: () => Promise<T>): Promise<T> {+ const previous = getCliOptions();+ setCliOptions({ ...previous, writeWaitMs });+ try { return await run(); } finally { setCliOptions(previous); }+}+async function eventually(read: () => Promise<unknown>, expected: unknown, ms = 15_000) {+ const until = Date.now() + ms;+ let last: unknown;+ while (Date.now() < until) { last = await read(); if (JSON.stringify(last) === JSON.stringify(expected)) return; await new Promise(r => setTimeout(r, 100)); }+ expect(last).toEqual(expected);+}++describe('#6543 D1: repair apply continues past accepted-but-pending writes', () => {+ test('under --wait 0 one run admits all three slow items, which publish without a rerun (master: one item per run)', async () => {+ await brain(async (engine, source) => {+ await pagesWithHistory(engine, source, ['notes/a', 'notes/b', 'notes/c']);+ const scope = await resolveRepairScope(engine);+ slowPublications(1_000);+ const first = await withWriteWait(0, async () => (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope));+ expect(first).toMatchObject({ applied: 0, complete: false, stopped: { reason: 'write_pending' } });+ expect(first.pending?.map(p => p.item)).toEqual([`${source}:notes/a`, `${source}:notes/b`, `${source}:notes/c`]);+ expect(first.stopped!.message).toContain('3 repairs were accepted and are still pending publication');+ await eventually(() => marked(engine, source), ['notes/a', 'notes/b', 'notes/c']);+ const again = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope);+ expect(again).toMatchObject({ complete: true });+ expect(again.stopped).toBeUndefined();+ });+ }, 120_000);++ test('a first publication slower than the write wait no longer stops the run: the rest settle in one shared wait and one run completes', async () => {+ await brain(async (engine, source) => {+ await pagesWithHistory(engine, source, ['notes/a', 'notes/b', 'notes/c']);+ const scope = await resolveRepairScope(engine);+ slowPublications(2_500, { first: 1, restMs: 200 });+ const result = await withWriteWait(2_000, async () => (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope));+ expect(result.stopped).toBeUndefined();+ expect(result).toMatchObject({ applied: 3, complete: true });+ expect(await marked(engine, source)).toEqual(['notes/a', 'notes/b', 'notes/c']);+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair'")).toEqual([]);+ });+ }, 120_000);++ test('more than 100 slow repairs finish in one run under the shipped outstanding limits, and a lowered cap only narrows the window', async () => {+ await brain(async (engine, source) => {+ const slugs = Array.from({ length: 105 }, (_, i) => `notes/p${String(i).padStart(3, '0')}`);+ await pagesWithHistory(engine, source, slugs);+ const scope = await resolveRepairScope(engine);+ slowPublications(2_500, { first: 1, restMs: 5 });+ const result = await withWriteWait(2_000, async () => (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope));+ expect(result.stopped).toBeUndefined();+ expect(result).toMatchObject({ applied: 105, complete: true, failed: [] });+ expect((await marked(engine, source)).length).toBe(105);+ });+ await brain(async (engine, source) => {+ const slugs = Array.from({ length: 20 }, (_, i) => `notes/q${String(i).padStart(2, '0')}`);+ await pagesWithHistory(engine, source, slugs);+ await engine.setConfig('persistence.limits.principal_outstanding', '8');+ const scope = await resolveRepairScope(engine);+ slowPublications(2_500, { first: 1, restMs: 20 });+ const result = await withWriteWait(2_000, async () => (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope));+ expect(result.stopped).toBeUndefined();+ expect(result).toMatchObject({ applied: 20, complete: true });+ });+ }, 240_000);++ test('a run that dies after admitting pending items leaves the cursor before the first of them, and the same command resumes', async () => {+ await brain(async (engine, source) => {+ await pagesWithHistory(engine, source, ['notes/a', 'notes/b', 'notes/c']);+ const scope = await resolveRepairScope(engine);+ const spec = repairSpec('timeline');+ let calls = 0;+ const dying = { ...spec.handler, apply: async (...args: Parameters<typeof spec.handler.apply>) => {+ if (++calls === 3) throw new Error('process died');+ return spec.handler.apply(...args);+ } };+ slowPublications(1_000);+ await expect(runRepair(ctxFor(engine, source, 0), dying, scope, { apply: true, spec, embed: false })).rejects.toThrow('process died');+ const [row] = await engine.executeRaw<{ completed_keys: Array<{ cursor: unknown; run_id: string }> }>("SELECT completed_keys FROM op_checkpoints WHERE op='repair'");+ expect(row!.completed_keys[0]).toMatchObject({ cursor: null });+ installFaultHook(undefined);+ const resumed = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope);+ expect(resumed).toMatchObject({ complete: true, resumed_from: null });+ expect(await marked(engine, source)).toEqual(['notes/a', 'notes/b', 'notes/c']);+ });+ }, 120_000);++ test('with no live consumer the run still stops at the first pending write and names the owner', async () => {+ await brain(async (engine, source) => {+ await pagesWithHistory(engine, source, ['notes/a', 'notes/b', 'notes/c']);+ const scope = await resolveRepairScope(engine);+ const spec = repairSpec('timeline');+ slowPublications(1_000);+ const result = await runRepair(ctxFor(engine, source, 0), spec.handler, scope, { apply: true, spec, embed: false,+ publicationOwner: async () => ({ alive: false, owner: 'the serve process (pid 4242), which reports restart_required' }) });+ expect(result).toMatchObject({ applied: 0, complete: false, stopped: { reason: 'write_pending', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'], actor: 'host_admin' } } });+ expect(result.stopped!.message).toContain('nothing here publishes it (the serve process (pid 4242), which reports restart_required)');+ expect(result.pending).toEqual([{ item: `${source}:notes/a`, request_id: expect.any(String) }]);+ });+ }, 120_000);+ test('a preview-bound apply runs its last item (which retires the approved set) only after every earlier receipt is accounted for', async () => {+ await brain(async (engine, source) => {+ const scope = await resolveRepairScope(engine);+ const spec = repairSpec('failed-writes');+ const attempts: number[] = [];+ let pendingIds = true;+ const item = (id: number): RepairItem => ({ cursor: { phase: 0, id }, source_id: source, slug: `notes/s${id}`, chars: 1, action: 'replay' });+ const handler: RepairHandler = { kind: 'failed-writes', embeds: false,+ async plan(_engine, _scope, after) { return { items: [0, 1, 2].map(item).filter(i => !after || i.cursor.id > after.id), residuals: {}, preview_hash: 'h' }; },+ async apply(_ctx, it) {+ attempts.push(it.cursor.id);+ if (pendingIds && it.cursor.id < 2) {+ const error = new OperationError('write_pending', 'The write is accepted and is still pending.', 'wait');+ error.writeRequest = { request_id: randomUUID(), state: 'queued', retry_after_ms: 250 };+ throw error;+ }+ return { applied: true, outcome: 'replayed' };+ } };+ const alive = async () => ({ alive: true, owner: 'this process' });+ const stopped = await runRepair(ctxFor(engine, source, 0), handler, scope, { apply: true, spec, explicit: true, expect: 'h', publicationOwner: alive });+ expect(attempts).toEqual([0, 1]);+ expect(stopped).toMatchObject({ applied: 0, complete: false, stopped: { reason: 'write_pending' } });+ expect(stopped.pending?.map(p => p.item)).toEqual([`${source}:notes/s0`, `${source}:notes/s1`]);+ pendingIds = false; attempts.length = 0;+ const resumed = await runRepair(ctxFor(engine, source, 0), handler, scope, { apply: true, spec, explicit: true, expect: 'h', publicationOwner: alive });+ expect(attempts).toEqual([0, 1, 2]);+ expect(resumed).toMatchObject({ applied: 3, complete: true, resumed_from: null });+ });+ }, 60_000);+});diff --git a/test/serve-behavior-notice-6543.test.ts b/test/serve-behavior-notice-6543.test.tsnew file mode 100644index 0000000000..11d9a71322--- /dev/null+++ b/test/serve-behavior-notice-6543.test.ts@@ -0,0 +1,70 @@+/**+ * #6543 C2: serve writes the pending behavior-change disclosure to its own log once per process and not again on a+ * restart of the same release, without consuming the CLI's or the MCP channels' delivery and without recording the+ * brain's baseline. `runServe` calls it at startup.+ *+ * Regression that fails it: serve never logging the rows, logging them on every start, or claiming the CLI/stdio+ * marker (the next CLI command would then miss its notice).+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __resetBehaviorNoticeForTests, BEHAVIOR_NOTICE_CODE, takeLocalBehaviorNotice } from '../src/core/behavior-change-notice.ts';+import { __resetServeBehaviorNoticeForTests, logServeBehaviorNotice } from '../src/core/serve-behavior-notice.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // A brain that existed well before this release: the rows since its (derived) baseline are pending.+ await engine.executeRaw("UPDATE sources SET created_at = now() - interval '30 days'");+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-serve-notice-'));+ __resetServeBehaviorNoticeForTests();+ __resetBehaviorNoticeForTests();+});++const cfg = { engine: 'pglite' as const, database_path: '/tmp/serve-notice-test-brain' };++test('serve logs pending behavior changes once per process and not on the next start of the same release', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ try {+ const lines: string[] = [];+ expect(await logServeBehaviorNotice(engine, cfg, { write: line => lines.push(line) })).toBe(true);+ expect(await logServeBehaviorNotice(engine, cfg, { write: line => lines.push(line) })).toBe(false);+ expect(lines.length).toBe(1);+ expect(lines[0]).toStartWith(`[gbrain serve] notice=${BEHAVIOR_NOTICE_CODE}: `);+ expect(lines[0]).toContain('gbrain doctor --only behavior_changes');+ __resetServeBehaviorNoticeForTests();+ expect(await logServeBehaviorNotice(engine, cfg, { write: line => lines.push(line) })).toBe(false);+ expect(lines.length).toBe(1);+ } finally { rmSync(home, { recursive: true, force: true }); }+}), 30_000);++test('serve logging leaves the CLI notice, the stdio marker and the baseline untouched', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ try {+ await logServeBehaviorNotice(engine, cfg, { write: () => undefined });+ const dir = join(home, '.gbrain', 'notices', 'behavior-changes');+ const names = existsSync(dir) ? readdirSync(dir) : [];+ expect(names.filter(name => name.endsWith('.cli.shown') || name.endsWith('.stdio.shown') || name.endsWith('.baseline'))).toEqual([]);+ expect(names.filter(name => name.endsWith('.serve_log.shown')).length).toBe(1);+ const cliNotice = await takeLocalBehaviorNotice(engine, 'cli', { cfg });+ expect(cliNotice?.code).toBe(BEHAVIOR_NOTICE_CODE);+ } finally { rmSync(home, { recursive: true, force: true }); }+}), 30_000);++test('runServe logs the notice at startup', () => {+ const source = readFileSync(join(import.meta.dir, '../src/commands/serve.ts'), 'utf8');+ expect(source).toMatch(/logServeBehaviorNotice\(engine, /);+});diff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.tsindex bf08758701..20bc89251a 100644--- a/test/serve-sync-handoff.serial.test.ts+++ b/test/serve-sync-handoff.serial.test.ts@@ -46,6 +46,7 @@ import {startDelegatedSync,} from '../src/core/serve-sync-runner.ts';import { maybeDelegateManagedSyncToServe, type ManagedDelegationDeps } from '../src/commands/sync-delegate.ts';+import { implyManagedNoPull } from '../src/commands/sync/managed-no-pull.ts';import type { ConsumerRow } from '../src/core/persistence/consumer-heartbeat.ts';import type { SyncOpts } from '../src/commands/sync.ts';import { withEnv } from './helpers/with-env.ts';@@ -346,4 +347,18 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (const rows = await engine.executeRaw<{ principal_id: string }>('SELECT DISTINCT principal_id FROM persistence_requests WHERE source_id=$1', [f.id]);expect(rows.map(r => r.principal_id)).toEqual([local.id]);}), 180_000);++ test('#6543 C1: `gbrain sync --source <id>` without --no-pull on a managed brain delegates with --no-pull implied and the serve drains it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const f = await fixture(2);+ const sock = await serveSocket();+ const flags = { noPull: false, dryRun: false };+ captureStderr();+ await implyManagedNoPull(engine, flags, f.id);+ const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--json'], { ...baseOpts(f.id), noPull: flags.noPull, noEmbed: undefined, explicitProcessing: [] }, deps({ sock }));+ releaseStderr();+ expect(captured.some(l => l.includes('--no-pull is implied') && l.includes(`gbrain sources refresh ${f.id}`))).toBe(true);+ expect(outcome.kind).toBe('delegated');+ if (outcome.kind !== 'delegated') throw new Error('unreachable');+ expect(outcome.result).toMatchObject({ status: 'first_sync', added: 2 });+ }), 180_000);});diff --git a/test/sync-drain-head-blocked-6543.test.ts b/test/sync-drain-head-blocked-6543.test.tsnew file mode 100644index 0000000000..b7e227580e--- /dev/null+++ b/test/sync-drain-head-blocked-6543.test.ts@@ -0,0 +1,171 @@+/**+ * #6543 (B2): the drain used to print a constant "claimable here: no" and wait the whole no-progress window (600 s in the+ * report) for a queued head no consumer could claim. The head probe names the predicate blocking the head; an+ * intervention-required blocker (a refresh fence no refresh process holds, a zombie publication ahead) stops the drain+ * `drain_stalled` / `cause: head_blocked` after one governor tick, while a live blocker (a foreground publication) keeps the+ * progress-aware wait. A failed probe prints `unknown`. Writer status names the same blocker.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { drainNext, engineStallProbe, formatDrainSummary, runDrain, type StallProbe } from '../src/core/persistence/sync-drain.ts';+import { headClaimability, type HeadBlocker } from '../src/core/persistence/head-blocker.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { refreshLockPath } from '../src/core/persistence/worktree-refresh.ts';+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import type { SyncResult } from '../src/commands/sync.ts';++const RESUME = 'gbrain sync --source s';+const done: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };+const fence: HeadBlocker = { predicate: 'refresh_fence', ids: ['ref-1'], state: 'fenced', owner: { kind: 'refresh', pid: null, live: false, restart_required: false }, intervention: true };+const hold: HeadBlocker = { predicate: 'root_hold', ids: ['req-ahead'], state: 'running', owner: { kind: 'serve', pid: 77, live: true, restart_required: false }, intervention: false };+const probeWith = (head: StallProbe['head']): StallProbe => ({ blockedHead: async () => null, fingerprint: async () => null, head });++describe('in-pass governor: head blocker classification', () => {+ test('an intervention-required blocker on a queued head stops within one governor tick, naming the predicate and its recovery', async () => {+ const started = Date.now();+ const result = await runDrain({ governMs: 20, noProgressMs: 60_000, publicationCeilingMs: 60_000,+ probe: probeWith(async () => ({ head_state: 'queued', request_id: 'req-head', claim: null, claimable_here: false, blocked_by: fence, consumer: 'self(full)' })),+ pass: () => new Promise<SyncResult>(() => undefined) });+ expect(Date.now() - started).toBeLessThan(5_000);+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',+ stall: { cause: 'head_blocked', in_pass: true, head_request_id: 'req-head', claimable_here: false, consumer: 'self(full)', blocked_by: { predicate: 'refresh_fence', ids: ['ref-1'] } } });+ const next = drainNext(result, RESUME, 's')!;+ expect(next).toMatchObject({ code: 'drain_stalled', cause: 'head_blocked', safe_to_loop: false, command: 'gbrain sources refresh s --resume', docs: 'docs/guides/write-refusals.md#head-blocked' });+ expect(next.fix).toMatchObject({ argv: ['gbrain', 'sources', 'refresh', 's', '--resume'], next: 'run' });+ const summary = formatDrainSummary(result, RESUME, 's').join('\n');+ expect(summary).toContain('cause=head_blocked');+ expect(summary).toContain('blocked_by=refresh_fence(fenced ref-1 no live refresh)');+ expect(summary).toContain('consumer=self(full)');+ });++ test('a zombie publication ahead suggests restarting the named owner', async () => {+ const zombie: HeadBlocker = { predicate: 'zombie_publication', ids: ['req-z'], state: 'running', owner: { kind: 'serve', pid: 4242, live: true, restart_required: true }, intervention: true };+ const result = await runDrain({ governMs: 20, noProgressMs: 60_000, publicationCeilingMs: 60_000,+ probe: probeWith(async () => ({ head_state: 'queued', request_id: 'req-head', claim: null, claimable_here: false, blocked_by: zombie })),+ pass: () => new Promise<SyncResult>(() => undefined) });+ const next = drainNext(result, RESUME, 's')!;+ expect(next).toMatchObject({ cause: 'head_blocked', fix: { actor: 'host_admin', next: 'tell_user_to_run' } });+ expect(next.why).toContain('Restart the gbrain serve process (pid 4242)');+ });++ test('a live blocker (a foreground publication ahead) lasting several ticks never stops the drain; the pass completes', async () => {+ let reads = 0;+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 60_000,+ probe: probeWith(async () => { reads++; return { head_state: 'queued', request_id: 'req-head', claim: null, claimable_here: false, blocked_by: hold }; }),+ pass: () => new Promise<SyncResult>(resolve => setTimeout(() => resolve({ ...done, managedCursor: { index: 1, total: 1 } }), 150)) });+ expect(reads).toBeGreaterThanOrEqual(3);+ expect(result.drain).toMatchObject({ outcome: 'synced' });+ });++ test('a head whose claimability could not be read prints unknown, never no', async () => {+ const result = await runDrain({ governMs: 10, noProgressMs: 60, publicationCeilingMs: 60_000,+ probe: probeWith(async () => ({ head_state: 'queued', request_id: 'req-head', claim: null, claimable_here: null, blocked_by: null })),+ pass: () => new Promise<SyncResult>(() => undefined) });+ expect(result.drain).toMatchObject({ stop_reason: 'drain_stalled', stall: { cause: 'no_progress', claimable_here: null } });+ expect(formatDrainSummary(result, RESUME, 's').join('\n')).toContain('claimable here: unknown');+ }, 15_000);++ test('the stall line names the consumer and the blocker', async () => {+ const lines: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.join(' ')); });+ try {+ await runDrain({ announce: true, progressMs: 15, governMs: 10, noProgressMs: 200, publicationCeilingMs: 60_000,+ probe: probeWith(async () => ({ head_state: 'queued', request_id: 'req-head', claim: null, claimable_here: false, blocked_by: hold, consumer: 'serve pid=77 last_heartbeat_ago=3s' })),+ pass: () => new Promise<SyncResult>(() => undefined) });+ } finally { spy.mockRestore(); }+ expect(lines.some(line => line.includes('consumer=serve pid=77 last_heartbeat_ago=3s') && line.includes('blocked_by=root_hold(running req-ahead serve pid 77)'))).toBe(true);+ }, 15_000);+});++describe('head blocker probe over a real brain', () => {+ const engines: Array<[string, BrainEngine]> = [];+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(['pglite', lite]); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(['postgres', pg.engine]); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => { for (const [kind, engine] of engines) if (kind === 'pglite') await engine.disconnect(); await closePostgres?.(); });++ async function seed(engine: BrainEngine) {+ const id = `hb-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, `/tmp/${id}`]);+ const [wt] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees(owner_host_id) VALUES($1::uuid) RETURNING id::text AS id', [localHostId()]);+ const [src] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);+ await engine.executeRaw('INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id) VALUES($1,$2::uuid,$3::uuid)', [id, src!.incarnation, wt!.id]);+ const request = async (state: 'queued' | 'running', slug: string, kind: string, extra: { token?: string; stamp?: string } = {}) => {+ const [row] = await engine.executeRaw<{ id: string; request_id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,+ state,execution_token,claim_expires_at,claim_phase)+ VALUES('local_cli','cli:example',$1::uuid,'put_page',$2,$3::uuid,$4,$5::uuid,'d','{}'::jsonb,$6::text::jsonb,1,16384,$7,$8::uuid,+ CASE WHEN $7='running' THEN now()+interval '30 seconds' END,$9::text::jsonb)+ RETURNING id::text AS id, request_id::text AS request_id`,+ [randomUUID(), id, src!.incarnation, slug, wt!.id, JSON.stringify({ kind, path: `${slug}.md` }), state, extra.token ?? null, extra.stamp ?? null]);+ return row!;+ };+ return { id, worktree: wt!.id, request };+ }++ test('a durable refresh fence with no refresh process stops the drain within one tick and writer status names it', async () => {+ for (const [, engine] of engines) {+ const { id, worktree, request } = await seed(engine);+ const head = await request('queued', 'notes/a', 'managed_sync_import');+ const [refresh] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_worktree_refreshes(worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)+ VALUES($1::uuid,ARRAY[$2],gen_random_uuid(),1,1,'fenced',$3,$4,'origin/main') RETURNING id::text AS id`, [worktree, id, 'a'.repeat(40), 'b'.repeat(40)]);+ const probe = engineStallProbe(engine, id);+ const result = await runDrain({ governMs: 20, noProgressMs: 60_000, publicationCeilingMs: 60_000, probe, pass: () => new Promise<SyncResult>(() => undefined) });+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',+ stall: { cause: 'head_blocked', head_request_id: head.id, claimable_here: false, blocked_by: { predicate: 'refresh_fence', ids: [refresh!.id], state: 'fenced', intervention: true } } });+ const status = await readWriterDiagnostics(engine);+ const row = (status.blockers as Array<Record<string, unknown>>).find(b => b.request_id === head.request_id)!;+ expect(row).toMatchObject({ claimable_here: false, blocked_by: { predicate: 'refresh_fence', ids: [refresh!.id] } });+ expect(String(row.next_action)).toContain(`gbrain sources refresh ${id} --resume`);+ expect(row.cancel_command).toBeUndefined();++ // A refresh process holding the lock is live work: the drain keeps waiting.+ const lock = await tryAcquireNativeLock(refreshLockPath(worktree));+ try {+ const live = await headClaimability(engine, { id: head.id, state: 'queued' }, localHostId());+ expect(live).toMatchObject({ claimable_here: false, blocked_by: { predicate: 'refresh_fence', intervention: false, owner: { live: true } } });+ } finally { await lock?.release(); }+ await engine.executeRaw("UPDATE persistence_worktree_refreshes SET state='aborted' WHERE id=$1::uuid", [refresh!.id]);+ expect(await headClaimability(engine, { id: head.id, state: 'queued' }, localHostId())).toEqual({ claimable_here: true, blocked_by: null });+ }+ }, 60_000);++ test('a foreground publication ahead of a queued head lasting several ticks does not stop the drain, which completes', async () => {+ for (const [, engine] of engines) {+ const { id, request } = await seed(engine);+ const token = randomUUID(), at = new Date().toISOString();+ const stamp = JSON.stringify({ phase: 'publishing', claimed_at: at, since: at, token, step: null, step_since: at, waiting_on: 'publication', owner: { kind: 'serve', pid: 5151, version: 'test', nonce: 'n5' } });+ const ahead = await request('running', 'notes/fg', 'put_page', { token, stamp });+ const head = await request('queued', 'notes/b', 'managed_sync_import');+ const probe = engineStallProbe(engine, id);+ const read = await probe.head!();+ expect(read).toMatchObject({ head_state: 'running' });+ expect(await headClaimability(engine, { id: head.id, state: 'queued' }, localHostId()))+ .toMatchObject({ claimable_here: false, blocked_by: { predicate: 'root_hold', ids: [ahead.request_id], intervention: false } });+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 60_000, probe,+ pass: () => new Promise<SyncResult>(resolve => setTimeout(() => resolve({ ...done, managedCursor: { index: 1, total: 1 } }), 200)) });+ expect(result.drain).toMatchObject({ outcome: 'synced' });+ const status = await readWriterDiagnostics(engine);+ const row = (status.blockers as Array<Record<string, unknown>>).find(b => b.request_id === head.request_id)!;+ expect(row).toMatchObject({ claimable_here: false, blocked_by: { predicate: 'root_hold', ids: [ahead.request_id] } });+ expect(row.cancel_command).toBeUndefined();+ }+ }, 60_000);++ test('a failed probe reads unknown, not no', async () => {+ for (const [, engine] of engines) {+ const failing = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return async () => { throw new Error('probe read failed'); };+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ expect(await headClaimability(failing, { id: randomUUID(), state: 'queued' }, localHostId())).toEqual({ claimable_here: null, blocked_by: null });+ }+ });+});diff --git a/test/sync-legacy-ledger-6543.serial.test.ts b/test/sync-legacy-ledger-6543.serial.test.tsnew file mode 100644index 0000000000..66af6fef4c--- /dev/null+++ b/test/sync-legacy-ledger-6543.serial.test.ts@@ -0,0 +1,98 @@+/**+ * #6543 D5 (+ #6518): on a managed brain, rows the pre-managed sync left in the local ledger+ * (`sync-failures.jsonl`, often `auto_skipped`) were never retried or cleared by a managed sync, while doctor told the+ * operator to run `gbrain sync --no-pull --retry-failed`, which printed "No local ledger entries" and left them.+ *+ * Now a successful managed sync reconciles each legacy row of its source on its own against the imported commit, the+ * live page and any hold: a row whose file the commit holds with a live page (or whose file is gone with no page)+ * settles; rows for files the sync did not index, or recorded on a commit this checkout does not have (a replaced+ * source), stay. Mirror rows whose durable failure is gone are pruned only after the durable lookup succeeds.+ * `--retry-failed` names the legacy rows, and doctor names them as their own count.+ *+ * Regression that fails it: legacy rows surviving a successful sync, an unindexed file's row disappearing, the stale+ * mirror surviving, "No local ledger entries" printed while legacy rows exist, or doctor without the legacy note.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSyncInner } from '../src/commands/sync/run.ts';+import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { loadSyncFailures, syncFailuresPath } from '../src/core/sync-failure-ledger.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-legacy-ledger-'));+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, GBRAIN_SYNC_NO_DELEGATE: '1' };+let engine: PGLiteEngine;+const captured: string[] = [];+const orig = { out: process.stdout.write.bind(process.stdout), err: process.stderr.write.bind(process.stderr), log: console.log, error: console.error };+function capture(): void {+ captured.length = 0;+ process.stdout.write = ((chunk: string | Uint8Array) => { captured.push(String(chunk)); return true; }) as typeof process.stdout.write;+ process.stderr.write = ((chunk: string | Uint8Array) => { captured.push(String(chunk)); return true; }) as typeof process.stderr.write;+ console.log = (...a: unknown[]) => { captured.push(a.map(String).join(' ')); };+ console.error = (...a: unknown[]) => { captured.push(a.map(String).join(' ')); };+}+function release(): void { process.stdout.write = orig.out; process.stderr.write = orig.err; console.log = orig.log; console.error = orig.error; }++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterAll(async () => {+ release();+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});++function legacyRow(sourceId: string, path: string, commit: string, extra: Record<string, unknown> = {}): string {+ const at = '2026-09-01T00:00:00.000Z';+ return JSON.stringify({ source_id: sourceId, path, error: 'source_changed: file and database disagree', code: 'source_changed', commit,+ first_seen: at, ts: at, attempts: 3, state: 'auto_skipped', resolved_at: at, acknowledged: false, acknowledged_at: null, ...extra });+}++test('a successful managed sync settles legacy rows it imports, keeps unindexed and replaced-source rows, prunes a stale mirror; retry and doctor name them', async () => withEnv(env, async () => {+ const id = `legacy-${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); mkdirSync(join(root, 'assets'));+ execFileSync('git', ['-C', root, 'init', '-q']);+ writeFileSync(join(root, 'notes', 'a.md'), '---\ntitle: A\n---\nA durable observation.\n');+ writeFileSync(join(root, 'assets', 'data.bin'), Buffer.from([0, 1, 2, 3]));+ execFileSync('git', ['-C', root, 'add', '-A']);+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'initial']);+ const head = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');++ writeFileSync(syncFailuresPath(), [+ legacyRow(id, 'notes/a.md', head),+ legacyRow(id, 'notes/gone.md', head),+ legacyRow(id, 'assets/data.bin', head),+ legacyRow(id, 'notes/old.md', '0123456789abcdef0123456789abcdef01234567'),+ legacyRow(id, 'notes/mirror.md', head, { state: 'open', managed_cursor_key: 'stale-cursor-key', request_id: null, run_id: 'r', observation_id: 'o' }),+ ].join('\n') + '\n');++ const before = await checkSyncFailures(engine, { sourceIds: [id], remote: false });+ expect(before?.message).toContain('legacy ledger');+ expect(before?.message).toContain(`gbrain sync --source ${id}`);++ capture();+ try { await runSyncInner(engine, ['--source', id, '--no-pull', '--retry-failed', '--no-embed', '--no-extract']); } finally { release(); }+ const output = captured.join('\n');+ expect(output).not.toContain('No local ledger entries');+ expect(output).toContain('4 legacy ledger row(s)');++ const rows = loadSyncFailures().filter(row => row.source_id === id);+ expect(rows.map(row => row.path).sort()).toEqual(['assets/data.bin', 'notes/old.md']);+ expect(rows.every(row => !row.managed_cursor_key)).toBe(true);++ const after = await checkSyncFailures(engine, { sourceIds: [id], remote: false });+ expect(after?.message).toContain('2 of these are legacy ledger row(s)');+ expect(after?.message).not.toContain('notes/a.md');+ const noEngine = await checkSyncFailures(null, { sourceIds: [id], remote: false });+ expect(noEngine?.message).toContain('2 unresolved sync failure(s)');+}), 120_000);diff --git a/test/sync-managed-implied-no-pull-6543.serial.test.ts b/test/sync-managed-implied-no-pull-6543.serial.test.tsnew file mode 100644index 0000000000..19f505fa6e--- /dev/null+++ b/test/sync-managed-implied-no-pull-6543.serial.test.ts@@ -0,0 +1,97 @@+/**+ * #6543 C1: managed sync never pulls (the managed path read `noPull` only to refuse), so the CLI implies+ * `--no-pull` on a managed brain and prints one stderr line naming `gbrain sources refresh <id>`. Covers the+ * single-source and `--all` CLI paths here; the serve-delegated path is pinned in serve-sync-handoff.serial.test.ts.+ * The library refusal of an explicit pull (`performSync({ noPull: false })`) stays.+ *+ * Regression that fails it: the CLI refusing with writer_coordinator_required again, the notice landing on stdout+ * (it would corrupt `--json`), or the library refusal being dropped.+ */+import { afterAll, afterEach, beforeAll, expect, test, spyOn } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync } from '../src/commands/sync.ts';+import { runSyncInner } from '../src/commands/sync/run.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-implied-no-pull-'));+let engine: PGLiteEngine;+const sources: string[] = [];+const out: string[] = [], err: string[] = [];+const origOut = process.stdout.write.bind(process.stdout), origErr = process.stderr.write.bind(process.stderr);+const origLog = console.log, origError = console.error;+function capture(): void {+ out.length = 0; err.length = 0;+ process.stdout.write = ((chunk: string | Uint8Array) => { out.push(String(chunk)); return true; }) as typeof process.stdout.write;+ process.stderr.write = ((chunk: string | Uint8Array) => { err.push(String(chunk)); return true; }) as typeof process.stderr.write;+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ') + '\n'); };+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ') + '\n'); };+}+function release(): void { process.stdout.write = origOut; process.stderr.write = origErr; console.log = origLog; console.error = origError; }++function git(root: string, ...args: string[]): void {+ execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });+}++async function fixture(): Promise<{ id: string; root: string }> {+ const id = `nopull-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, 'notes', 'a.md'), '---\ntitle: Note A\n---\nA durable observation.\n');+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root };+}++const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, GBRAIN_SYNC_NO_DELEGATE: '1' };++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterEach(() => release());+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);+ await engine.disconnect();+ });+ rmSync(home, { recursive: true, force: true });+});++test('single-source `gbrain sync --source <id>` on a managed brain imports without --no-pull and names sources refresh on stderr', async () => withEnv(env, async () => {+ const f = await fixture();+ capture();+ try { await runSyncInner(engine, ['--source', f.id, '--no-embed', '--no-extract', '--json']); } finally { release(); }+ const notice = err.find(line => line.includes('--no-pull is implied'));+ expect(notice).toBeDefined();+ expect(notice).toContain(`gbrain sources refresh ${f.id}`);+ expect(out.join('')).not.toContain('--no-pull is implied');+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1', [f.id]))[0].n).toBe(1);+}), 120_000);++test('`gbrain sync --all` on a managed brain implies --no-pull once for every source', async () => withEnv(env, async () => {+ const f = await fixture();+ capture();+ // The --all path ends a failed run with process.exit(1); trap it so a regression fails this test instead of the runner.+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`process.exit(${code})`); }) as never);+ try { await runSyncInner(engine, ['--all', '--no-embed', '--no-extract', '--json', '--yes']); } finally { exit.mockRestore(); release(); }+ expect(err.filter(line => line.includes('--no-pull is implied')).length).toBe(1);+ expect(err.join('')).not.toContain('writer_coordinator_required');+ expect(out.join('')).not.toContain('--no-pull is implied');+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1', [f.id]))[0].n).toBe(1);+}), 120_000);++test('the library refusal of an explicit pull stays', async () => withEnv(env, async () => {+ const f = await fixture();+ const thrown = await performSync(engine, { sourceId: f.id, repoPath: f.root, noPull: false, noEmbed: true, noExtract: true }).catch(e => e);+ expect((thrown as { code?: string }).code).toBe('writer_coordinator_required');+}), 120_000);