Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane A): pass stops drain to their §9 outcomes (probe 52), not_converged streak, source_changed is the level moving
garrytan23ddf6d1752b
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 837ce26a83..b795b6ce22 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1684,6 +1684,16 @@ Reasons: `count`, `digest`, `sequence`, `fk`, `trigger`, `relation_set`, `replayMore: [docs/guides/move-to-postgres.md#verify](../../docs/guides/move-to-postgres.md#verify)+### grant_scope++<a id="grant_scope"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed sync pass ran under a grant that covers only part of the source, so it admitted what the grant can see and cannot finish (stamp) the source. | A slug-fenced grant never stamps a pass (design v3.2 §5): converging the whole source needs a writer that can see every page, which is the owner host's own sync. | On the host that owns the source, run gbrain sync --source <id> --no-pull; check the result with gbrain sync status --source <id> --json. | user | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#drain-grant-scope](../../docs/guides/write-refusals.md#drain-grant-scope)+### graph_incomplete<a id="graph_incomplete"></a>@@ -2354,6 +2364,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### not_converged++<a id="not_converged"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed sync pass used its rounds without the level settling (another writer kept changing it), so it ended resumable; everything it admitted stands. | A pass re-reads the level each round and stamps only when nothing is left to admit. Concurrent writes can keep producing new work; the next pass starts from what this one settled. Three in a row (the pass row's not_converged_streak) mean rerunning is not converging. | Rerun the same gbrain sync; after three consecutive not_converged passes, stop and report it with gbrain sync status --source <id> --json and gbrain doctor --json. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/write-refusals.md#drain-not-converged](../../docs/guides/write-refusals.md#drain-not-converged)+### not_found<a id="not_found"></a>@@ -2850,6 +2870,16 @@ More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guidMore: [docs/guides/company-brain-ingestion.md#agent-and-ci-use](../../docs/guides/company-brain-ingestion.md#agent-and-ci-use)+### reconcile_host_required++<a id="reconcile_host_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A remote caller's managed sync admitted what it could, and the rest of the source needs the owner host (holds, markers, keep_db writes or the stamp). | Remote callers admit only one-sided work and never write holds, markers, keep_db writes or stamps (design v3.2 §5), so only the owner host's sync converges the source. | On the host that owns the source, run gbrain sync --source <id> --no-pull; verify with gbrain sync status --source <id> --json. | user | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#drain-reconcile-host-required](../../docs/guides/write-refusals.md#drain-reconcile-host-required)+### reconcile_read_incomplete<a id="reconcile_read_incomplete"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 78f5950931..a982ad63f8 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -520,6 +520,11 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| <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), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. 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`, an `effect_recovery` or `request_recovery` that can still finish, `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; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. 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>`. || <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. || <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |+| <a id="drain-not-converged"></a>`not_converged` | `not_converged` | `resumable` | The live pass (#6712 PR 4b) used its rounds without the level settling: another writer kept changing the checkout or the database while it ran. Everything it admitted stands and nothing is held for it; the pass row counts consecutive such passes (`not_converged_streak`). | Rerun the same `gbrain sync` (`next.safe_to_loop` is true). After three consecutive `not_converged` passes `next` turns to `report` (`safe_to_loop` false): run `gbrain sync status --source <id> --json` and `gbrain doctor --json` and report what keeps changing. Exit 0. |+| <a id="drain-admission-paused"></a>`admission_paused` | `admission_paused` | `resumable` | `sync.admission` is `imports_only` or `classify_only`, so the pass admitted only what it allows (or nothing) and stopped; a destructive write paused at publication is completed `cancelled` with `admission_paused`. Nothing failed. | Restoring admission is the owner's decision: `gbrain config set sync.admission normal` (`next.fix` is `tell_user_to_run`; never run automatically). The next sync continues. Exit 0. |+| <a id="drain-grant-scope"></a>`grant_scope` | `grant_scope` | `blocked` | The pass ran under a grant that covers only part of the source, so it admitted what the grant can see and cannot stamp the source. | On the owner host run `gbrain sync --source <id> --no-pull` (`next.fix` is `tell_user_to_run`), then verify with `gbrain sync status --source <id> --json`. Exit 1. |+| <a id="drain-reconcile-host-required"></a>`reconcile_host_required` | `reconcile_host_required` | `blocked` | A remote caller's pass admitted what it could; the rest needs the owner host, because remote callers never write holds, markers, keep_db writes or the stamp. | On the owner host run `gbrain sync --source <id> --no-pull` (`tell_user_to_run`), then verify with `gbrain sync status --source <id> --json`. Exit 1. |+| <a id="drain-reconcile-read-incomplete"></a>`reconcile_read_incomplete` | `reconcile_read_incomplete` | `blocked` | A Git listing the pass reads (`ls-tree`, `ls-files`, `diff-tree`) did not finish cleanly, so the pass classified and wrote nothing. | Check the checkout with `git -C <dir> status`; report it with `gbrain doctor --json` if it repeats (`next.fix` is `report`). Exit 1. |## Unbound sources on Postgresdiff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 0d8166cdd3..39c6881acb 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -100,6 +100,12 @@ export const ERROR_CATALOGUE = {sync_drain_capacity_paused: { code: 'capacity_paused', docs: 'docs/guides/write-refusals.md#drain-capacity-paused' },sync_drain_head_blocked: { code: 'drain_stalled', docs: 'docs/guides/write-refusals.md#head-blocked' },sync_drain_lease_held: { code: 'sync_drain_lease_held', docs: 'docs/guides/write-refusals.md#sync_drain_lease_held' },+ // #6712 PR 4b: the live pass's stops (design v3.2 §9).+ sync_drain_not_converged: { code: 'not_converged', docs: 'docs/guides/write-refusals.md#drain-not-converged' },+ sync_drain_admission_paused: { code: 'admission_paused', docs: 'docs/guides/write-refusals.md#drain-admission-paused' },+ sync_drain_grant_scope: { code: 'grant_scope', docs: 'docs/guides/write-refusals.md#drain-grant-scope' },+ sync_drain_reconcile_host_required: { code: 'reconcile_host_required', docs: 'docs/guides/write-refusals.md#drain-reconcile-host-required' },+ sync_drain_reconcile_read_incomplete: { code: 'reconcile_read_incomplete', docs: 'docs/guides/write-refusals.md#drain-reconcile-read-incomplete' },// 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 906e3b2778..b4c1a03f08 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -302,6 +302,10 @@ export const CODES = {graduation_unclassified_table: { class: 'server', summary: "A database has a relation the graduation inventory does not classify, so moving it could lose data.", docs: 'docs/guides/move-to-postgres.md#inventory', reasons: ['newer_schema', 'missing_inventory_row'] },graduation_unsupported_platform: { class: 'host_only', summary: "Moving a brain with write history to Postgres is not available on this platform yet.", docs: 'docs/guides/move-to-postgres.md#platforms' },graduation_verify_failed: { class: 'server', summary: "The moved copy did not verify against the source; the target stays fenced and the source stays authoritative.", docs: 'docs/guides/move-to-postgres.md#verify', reasons: ['count', 'digest', 'sequence', 'fk', 'trigger', 'relation_set', 'replay', 'doctor'] },+ grant_scope: { class: 'host_only', actor: 'user', summary: "A managed sync pass ran under a grant that covers only part of the source, so it admitted what the grant can see and cannot finish (stamp) the source.",+ why: "A slug-fenced grant never stamps a pass (design v3.2 §5): converging the whole source needs a writer that can see every page, which is the owner host's own sync.",+ docs: 'docs/guides/write-refusals.md#drain-grant-scope',+ suggestion: 'On the host that owns the source, run gbrain sync --source <id> --no-pull; check the result with gbrain sync status --source <id> --json.' },graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },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 } },@@ -400,6 +404,10 @@ export const CODES = {no_worker: { class: 'caller', summary: "No worker is running for this queue, so a queued job would wait until something runs it.", why: "PGLite brains have no background worker (the database is single-writer), and a Postgres queue needs a running `gbrain jobs work` or supervisor. Queuing without one leaves the job waiting with no error." },no_worker_surface: { class: 'caller', summary: "No worker surface." },not_a_git_repo: { class: 'caller', summary: "The source path must contain committed Git content." },+ not_converged: { class: 'retryable', retryable: true, actor: 'agent', summary: "A managed sync pass used its rounds without the level settling (another writer kept changing it), so it ended resumable; everything it admitted stands.",+ why: "A pass re-reads the level each round and stamps only when nothing is left to admit. Concurrent writes can keep producing new work; the next pass starts from what this one settled. Three in a row (the pass row's not_converged_streak) mean rerunning is not converging.",+ docs: 'docs/guides/write-refusals.md#drain-not-converged',+ suggestion: 'Rerun the same gbrain sync; after three consecutive not_converged passes, stop and report it with gbrain sync status --source <id> --json and gbrain doctor --json.' },not_owner_host: { class: 'host_only', summary: "This host does not own the source's active canonical worktree, so ghost pages (live pages whose canonical file is missing) cannot be checked or removed here; nothing was changed.", why: "Whether a page's canonical file is missing is only known on the host that holds the source's checkout; another host would read its own disk.", reasons: ['not_owner_host', 'not_applicable'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Run gbrain repair ghost-pages --source <id> in a terminal on the source\'s canonical owner host (writer status names it).', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: names the canonical owner host of the source.', requires_exclusive: false } },not_connected: { class: 'caller', summary: "Google connect credential error: not connected.", docs: 'docs/guides/google-connect.md#troubleshooting' },no_brain: { class: 'caller', summary: "No brain is configured on this machine.", suggestion: 'Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options).' },@@ -487,6 +495,10 @@ export const CODES = {receipt_identity_mismatch: { class: 'caller', summary: "The receipt ID is already bound to different approved ingestion metadata.", docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' },pat_file_unreadable: { class: 'caller', summary: "The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read.", why: "The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written.", suggestion: 'Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file.' },// #6712 PR 4a: a Git listing the reconcile reads did not finish cleanly (sync-git-stream.ts).+ reconcile_host_required: { class: 'host_only', actor: 'user', summary: "A remote caller's managed sync admitted what it could, and the rest of the source needs the owner host (holds, markers, keep_db writes or the stamp).",+ why: "Remote callers admit only one-sided work and never write holds, markers, keep_db writes or stamps (design v3.2 §5), so only the owner host's sync converges the source.",+ docs: 'docs/guides/write-refusals.md#drain-reconcile-host-required',+ suggestion: 'On the host that owns the source, run gbrain sync --source <id> --no-pull; verify with gbrain sync status --source <id> --json.' },reconcile_read_incomplete: { class: 'server', actor: 'agent', summary: "A Git listing the managed-sync reconcile reads (`ls-tree`, `ls-files`, `diff-tree`) did not finish cleanly: Git exited non-zero, was killed by a signal or its time or size cap, or its output did not end at a record boundary.",why: 'A partial listing would make files look deleted or new, so the level is refused rather than classified. In PR 4a only the read-only convergence shadow reads it, and it reports `status: unavailable` with this code.',docs: 'docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes',diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex e1b3dc895a..161d96f97f 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -43,7 +43,17 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio/** #6696 (A7): a cumulative write cap (or the background pause line) refused the next admission after the preflight passed; resumable once capacity returns. */| 'capacity_paused'/** #6712 PR 1: another drainer holds the source's drain lease (or took it from this run); resumable, the next run follows it. */- | 'drain_lease_held';+ | 'drain_lease_held'+ /** #6712 PR 4b (design v3.2 §9): the live pass's stops. `not_converged` and `admission_paused` are resumable; the rest need the host or a report. */+ | 'not_converged' | 'admission_paused' | 'grant_scope' | 'reconcile_host_required' | 'reconcile_read_incomplete';+/** The pass's status reasons that end a drain, with their outcome (design v3.2 §9). */+const PASS_STOPS: Partial<Record<string, { outcome: DrainOutcome; reason: DrainStopReason }>> = {+ not_converged: { outcome: 'resumable', reason: 'not_converged' }, admission_paused: { outcome: 'resumable', reason: 'admission_paused' },+ grant_scope: { outcome: 'blocked', reason: 'grant_scope' }, reconcile_host_required: { outcome: 'blocked', reason: 'reconcile_host_required' },+ reconcile_read_incomplete: { outcome: 'blocked', reason: 'reconcile_read_incomplete' },+};+/** Consecutive `not_converged` passes after which the agent reports instead of rerunning (design v3.2 §9). */+export const NOT_CONVERGED_REPORT_STREAK = 3;/** #6696 (A7): the refusal that paused the drain (`capacity_paused`); `fix` is the host's config raise. */export interface DrainCapacityPause { code: string; reason: string | null; detail: string | null; message: string; fix?: Action }/** A capacity refusal raised by an admission after the run's preflight (the preflight's own refusal stops the command up front). */@@ -581,6 +591,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {: finish(result, 'resumable', 'drain_lease_held', { retry_after_ms: result.leaseHeld.retry_after_ms });// #6278: the breaker's systemic stop is one diagnostic, not a failed page.if (result.breaker) return finish(result, 'blocked', 'preparation_systemic');+ const passStop = result.pass ? PASS_STOPS[result.reason ?? ''] : undefined;+ if (passStop) return finish(result, passStop.outcome, passStop.reason);if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');if (result.managedWrite && result.managedWrite.write_error !== 'write_pending') return finish(result, 'blocked', 'blocked_by_failures');if (result.status === 'partial' && (result.reason === 'timeout' || signal?.aborted)) return finish(result, 'resumable', 'deadline');@@ -897,8 +909,47 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic', write_capacity: 'sync_drain_write_capacity',connection_lost: 'sync_drain_connection_lost', capacity_paused: 'sync_drain_capacity_paused', drain_lease_held: 'sync_drain_lease_held',+ not_converged: 'sync_drain_not_converged', admission_paused: 'sync_drain_admission_paused', grant_scope: 'sync_drain_grant_scope',+ reconcile_host_required: 'sync_drain_reconcile_host_required', reconcile_read_incomplete: 'sync_drain_reconcile_read_incomplete',};+/**+ * #6712 PR 4b (design v3.2 §9): `next` for the live pass's stops. `not_converged` reruns the same sync until the server-side+ * streak reaches NOT_CONVERGED_REPORT_STREAK, then reports; the others never loop: the host runs the sync, the owner restores+ * `sync.admission` (never run automatically), or the agent reports.+ */+function passNext(stop: DrainStopReason | undefined, result: SyncResult, resumeCommand: string, sourceId: string):+ Omit<DrainNext, 'eta_seconds' | 'rate_pages_per_min' | 'docs'> | null {+ const status = ['gbrain', 'sync', 'status', '--source', sourceId, '--json'];+ const verify = { argv: status };+ const render = (action: Omit<Action, 'requires_exclusive' | 'consent'>) => renderAction({ consent: [], requires_exclusive: false, verify, ...action }, cliRenderContext());+ const hostSync = `gbrain sync --source ${sourceId} --no-pull`;+ switch (stop) {+ case 'not_converged': {+ const streak = result.pass?.not_converged_streak ?? 0;+ if (streak < NOT_CONVERGED_REPORT_STREAK) return { command: resumeCommand, safe_to_loop: true, retry_after_ms: 0, code: 'not_converged',+ why: `The pass ran ${result.pass?.round ?? 'its'} rounds without the level settling (another writer kept changing it); everything it admitted stands. The next sync reads the level again: rerun ${resumeCommand}.`,+ fix: render({ argv: resumeCommand.split(' '), actor: 'agent', why: 'Reruns the pass; it starts from what the last one settled.' }) };+ return { command: status.join(' '), safe_to_loop: false, retry_after_ms: 0, code: 'not_converged',+ why: `${streak} passes in a row ended without the level settling, so rerunning is not converging. Report it with the status (read-only) and gbrain doctor --json; the writer changing the checkout is named there.`,+ fix: render({ actor: 'agent', why: `${streak} consecutive passes did not converge; report it instead of rerunning.` }) };+ }+ case 'admission_paused': return { command: status.join(' '), safe_to_loop: false, retry_after_ms: 0, code: 'admission_paused',+ why: 'sync.admission is not normal, so the pass admitted only what it allows and stopped; nothing failed. Restoring it is the owner\'s decision: gbrain config set sync.admission normal, then the next sync continues.',+ fix: render({ argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], actor: 'user', why: 'Restores what managed sync may write; never run automatically.',+ user_message: `Managed sync of ${sourceId} is paused by sync.admission. To resume it, run: gbrain config set sync.admission normal` }) };+ case 'grant_scope': case 'reconcile_host_required': return { command: status.join(' '), safe_to_loop: false, retry_after_ms: 0, code: stop,+ why: stop === 'grant_scope'+ ? `This writer's grant covers only part of source ${sourceId}, so the pass admitted what it could see and cannot finish the source; the owner host's sync finishes it: ${hostSync}.`+ : `What is left in source ${sourceId} needs the owner host (holds, markers or decisions a remote caller never writes); everything this run admitted stands. On the owner host run: ${hostSync}.`,+ fix: render({ argv: hostSync.split(' '), actor: 'user', why: 'Only the source\'s owner host finishes the pass.', user_message: `On the host that owns source ${sourceId}, run: ${hostSync}` }) };+ case 'reconcile_read_incomplete': return { command: status.join(' '), safe_to_loop: false, retry_after_ms: 0, code: 'reconcile_read_incomplete',+ why: `A Git listing of source ${sourceId}'s checkout did not finish cleanly, so the pass classified nothing and wrote nothing. Check the checkout (git status), then report it with gbrain doctor --json if it repeats.`,+ fix: render({ actor: 'agent', why: 'The checkout could not be listed; report it with gbrain doctor --json.' }) };+ default: return null;+ }+}+/** What the agent runs next, or null when the sync is done (DX-A2). */export function drainNext(result: SyncResult, resumeCommand: string, sourceId: string): DrainNext | null {const outcome = syncOutcome(result);@@ -920,6 +971,8 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: swhy: held?.fix.why ?? 'Another drainer holds this source\'s drain lease and resumes the same cursor; rerun after retry_after_ms.',...(held ? { fix: renderAction({ ...held.fix, argv: resumeCommand.split(' ') }, cliRenderContext()) } : {}), docs: ERROR_CATALOGUE.sync_drain_lease_held.docs };}+ const pass = passNext(d?.stop_reason, result, resumeCommand, sourceId);+ if (pass) return { ...pass, ...estimate, docs: ERROR_CATALOGUE[STOP_DOCS[d!.stop_reason!]].docs };// #6712 PR 1: the drain-lease holder this run followed heartbeats but has committed nothing (and saved no cursor) for the// stall window. Waiting again would read as a clean exit on every tick, so this stops blocked with the holder named.if (d?.stop_reason === 'drain_stalled' && d.stall?.lease_holder) {diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 3bd4fec5ff..0a7133b613 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -24,7 +24,7 @@ import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OPtype PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';import { passIdleProbe, readShadowLevel, workingIdleChange, type ShadowLevel, type ShadowPath } from './sync-pass.ts';-import { recallWorkingStatCache, rememberWorkingStatCache } from './sync-git-stream.ts';+import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';import { syncPassKind } from './sync-classify.ts';import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';import { assertDrainLease, currentDrainLease } from './sync-lease.ts';@@ -430,6 +430,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr} catch (error) {if (error instanceof SyncAdmissionPaused) { await save('resumable', 'admission_paused').catch(() => undefined); return result('partial', 'admission_paused'); }if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') { await save('resumable', 'timeout').catch(() => undefined); return result('partial', 'timeout'); }+ // A Git listing that did not finish cleanly classifies nothing (design v3.2 §9): the pass stops blocked, having written nothing for that round.+ if (error instanceof SyncTreeReadIncomplete) { await save('blocked', 'reconcile_read_incomplete').catch(() => undefined); return result('blocked_by_failures', 'reconcile_read_incomplete'); }throw error;}}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex fc7fa407a0..a282688caf 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1658,6 +1658,14 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPreturn { ...result(cursor, done.error_code === 'admission_paused' ? 'partial' : 'blocked_by_failures', done.error_code === 'admission_paused' ? 'admission_paused' : undefined),...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };}+ // #6712 PR 4b (design v3.2 §2): a pass's write refused because its file changed after admission is the level moving, not a+ // page failure: the entry is passed over and the next round classifies the new level (a level that never settles ends the+ // pass not_converged).+ if (done.state !== 'committed' && cursor.passId && done.error_code === 'source_changed') {+ cursor = await saveCursor(engine, key, cursor, committedPast({ ...cursor, counts: { ...cursor.counts } }, pending));+ assertActive();+ continue;+ }if (done.state !== 'committed') {const settled = await settleFailedRequest(engine, { cursor, key, pending, done, assertActive, run: frozenRun, syncOptions, processingOptions,remote: authority.writer.remote, waitMs: opts.drainStartedAt ? 30_000 : 5000, signal });diff --git a/test/fixtures/goldens/sync/pass-outcomes.json b/test/fixtures/goldens/sync/pass-outcomes.jsonnew file mode 100644index 0000000000..4581686ef5--- /dev/null+++ b/test/fixtures/goldens/sync/pass-outcomes.json@@ -0,0 +1,641 @@+{+ "golden": {+ "admission_paused (stop)": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "admission_paused",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "admission_paused",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-admission-paused",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "config",+ "set",+ "sync.admission",+ "normal"+ ],+ "command": "gbrain config set sync.admission normal",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "Managed sync of default is paused by sync.admission. To resume it, run: gbrain config set sync.admission normal",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Restores what managed sync may write; never run automatically."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "sync.admission is not normal, so the pass admitted only what it allows and stopped; nothing failed. Restoring it is the owner's decision: gbrain config set sync.admission normal, then the next sync continues."+ },+ "outcome": "resumable",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "admission_paused",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "admission_paused",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-admission-paused",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "config",+ "set",+ "sync.admission",+ "normal"+ ],+ "command": "gbrain config set sync.admission normal",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "Managed sync of default is paused by sync.admission. To resume it, run: gbrain config set sync.admission normal",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Restores what managed sync may write; never run automatically."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "sync.admission is not normal, so the pass admitted only what it allows and stopped; nothing failed. Restoring it is the owner's decision: gbrain config set sync.admission normal, then the next sync continues."+ },+ "outcome": "resumable"+ },+ "exit": 0,+ "job": "needs_operator"+ },+ "grant_scope (stop)": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "grant_scope",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "grant_scope",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-grant-scope",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "On the host that owns source default, run: gbrain sync --source default --no-pull",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Only the source's owner host finishes the pass."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "This writer's grant covers only part of source default, so the pass admitted what it could see and cannot finish the source; the owner host's sync finishes it: gbrain sync --source default --no-pull."+ },+ "outcome": "blocked",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "grant_scope",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "grant_scope",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-grant-scope",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "On the host that owns source default, run: gbrain sync --source default --no-pull",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Only the source's owner host finishes the pass."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "This writer's grant covers only part of source default, so the pass admitted what it could see and cannot finish the source; the owner host's sync finishes it: gbrain sync --source default --no-pull."+ },+ "outcome": "blocked"+ },+ "exit": 1,+ "job": "needs_operator"+ },+ "not_converged (stop)": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "not_converged",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "not_converged",+ "command": "gbrain sync --source default --no-pull",+ "docs": "docs/guides/write-refusals.md#drain-not-converged",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Reruns the pass; it starts from what the last one settled."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": true,+ "why": "The pass ran 4 rounds without the level settling (another writer kept changing it); everything it admitted stands. The next sync reads the level again: rerun gbrain sync --source default --no-pull."+ },+ "outcome": "resumable",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "not_converged",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "not_converged",+ "command": "gbrain sync --source default --no-pull",+ "docs": "docs/guides/write-refusals.md#drain-not-converged",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Reruns the pass; it starts from what the last one settled."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": true,+ "why": "The pass ran 4 rounds without the level settling (another writer kept changing it); everything it admitted stands. The next sync reads the level again: rerun gbrain sync --source default --no-pull."+ },+ "outcome": "resumable"+ },+ "exit": 0,+ "job": "continue"+ },+ "not_converged after a 3-pass streak": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "not_converged",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "not_converged",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-not-converged",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "consent": [],+ "next": "report",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "3 consecutive passes did not converge; report it instead of rerunning."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "3 passes in a row ended without the level settling, so rerunning is not converging. Report it with the status (read-only) and gbrain doctor --json; the writer changing the checkout is named there."+ },+ "outcome": "resumable",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "resumable",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "not_converged",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "not_converged",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-not-converged",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "consent": [],+ "next": "report",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "3 consecutive passes did not converge; report it instead of rerunning."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "3 passes in a row ended without the level settling, so rerunning is not converging. Report it with the status (read-only) and gbrain doctor --json; the writer changing the checkout is named there."+ },+ "outcome": "resumable"+ },+ "exit": 0,+ "job": "needs_operator"+ },+ "reconcile_host_required (stop)": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "reconcile_host_required",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "reconcile_host_required",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-reconcile-host-required",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "On the host that owns source default, run: gbrain sync --source default --no-pull",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Only the source's owner host finishes the pass."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "What is left in source default needs the owner host (holds, markers or decisions a remote caller never writes); everything this run admitted stands. On the owner host run: gbrain sync --source default --no-pull."+ },+ "outcome": "blocked",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "reconcile_host_required",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "reconcile_host_required",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-reconcile-host-required",+ "eta_seconds": null,+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull"+ ],+ "command": "gbrain sync --source default --no-pull",+ "consent": [],+ "next": "tell_user_to_run",+ "requires_exclusive": false,+ "user_message": "On the host that owns source default, run: gbrain sync --source default --no-pull",+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "Only the source's owner host finishes the pass."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "What is left in source default needs the owner host (holds, markers or decisions a remote caller never writes); everything this run admitted stands. On the owner host run: gbrain sync --source default --no-pull."+ },+ "outcome": "blocked"+ },+ "exit": 1,+ "job": "needs_operator"+ },+ "reconcile_read_incomplete (stop)": {+ "delegated": {+ "continuation_job_id": null,+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "reconcile_read_incomplete",+ "waived": 0,+ "written": 0+ },+ "incomplete": true,+ "next": {+ "code": "reconcile_read_incomplete",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-reconcile-read-incomplete",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "consent": [],+ "next": "report",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "The checkout could not be listed; report it with gbrain doctor --json."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "A Git listing of source default's checkout did not finish cleanly, so the pass classified nothing and wrote nothing. Check the checkout (git status), then report it with gbrain doctor --json if it repeats."+ },+ "outcome": "blocked",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "blocked",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": null,+ "stop_reason": "reconcile_read_incomplete",+ "waived": 0,+ "written": 0+ },+ "next": {+ "code": "reconcile_read_incomplete",+ "command": "gbrain sync status --source default --json",+ "docs": "docs/guides/write-refusals.md#drain-reconcile-read-incomplete",+ "eta_seconds": null,+ "fix": {+ "actor": "agent",+ "consent": [],+ "next": "report",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "sync",+ "status",+ "--source",+ "default",+ "--json"+ ]+ },+ "why": "The checkout could not be listed; report it with gbrain doctor --json."+ },+ "rate_pages_per_min": null,+ "retry_after_ms": 0,+ "safe_to_loop": false,+ "why": "A Git listing of source default's checkout did not finish cleanly, so the pass classified nothing and wrote nothing. Check the checkout (git status), then report it with gbrain doctor --json if it repeats."+ },+ "outcome": "blocked"+ },+ "exit": 1,+ "job": "needs_operator"+ },+ "scoped pass converged (selection_scoped)": {+ "delegated": {+ "drain": {+ "eta_seconds": null,+ "outcome": "synced",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": 0,+ "waived": 0,+ "written": 0+ },+ "incomplete": false,+ "outcome": "synced",+ "pagesAffected": []+ },+ "direct": {+ "drain": {+ "eta_seconds": null,+ "outcome": "synced",+ "passes": 1,+ "processed": 0,+ "rate_pages_per_min": null,+ "remaining": 0,+ "waived": 0,+ "written": 0+ },+ "outcome": "synced"+ },+ "exit": 0,+ "job": "synced"+ }+ },+ "normalizer": "sync-pass-outcomes-v1"+}diff --git a/test/sync-pass-live-6712.test.ts b/test/sync-pass-live-6712.test.tsindex a4dff20aab..394fd18b44 100644--- a/test/sync-pass-live-6712.test.ts+++ b/test/sync-pass-live-6712.test.ts@@ -7,6 +7,9 @@* `managed_sync_delete` re-reads it at publication (completed `cancelled` / `admission_paused`, nothing written);* once it is `normal` again the next pass deletes the page.*+ * - not_converged (design v3.2 §9): a working copy that changes under every round ends the pass `partial` / `not_converged`;+ * the pass row counts the streak server-side, and from the third consecutive pass the drain's `next` is `report`.+ ** Each test fails on capy/6712-pr4b (8cda2764b), where a non-company source still runs the cursor engine, whose intents* the fences do not cover, so both deletes publish.*/@@ -18,6 +21,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { SYNC_ADMISSION_KEY } from '../src/core/persistence/sync-admission.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { drainNext, runDrain } from '../src/core/persistence/sync-drain.ts';import { managedBrain } from './helpers/managed-brain.ts';const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();@@ -70,4 +74,23 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {expect((await performManagedSync(engine, OPTS)).status).toBe('synced');expect(await liveSlugs(engine)).toEqual(['notes/b', 'notes/c']);}, { setup }), 180_000);++ test('not_converged: a working copy that changes under every round ends the pass not_converged; the third in a row reports', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ let edits = 0;+ installFaultHook(async point => { if (point === 'sync:mid_checkpoint') writeFileSync(join(root, 'notes/a.md'), note('notes/a', `An uncommitted edit ${++edits}.`)); });+ const streaks: number[] = [], loops: boolean[] = [];+ for (let i = 0; i < 3; i++) {+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'An uncommitted edit before the pass.'));+ const drained = await runDrain({ pass: () => performManagedSync(engine, { ...OPTS, workingTree: true }) });+ expect({ status: drained.status, reason: drained.reason, stop: drained.drain?.stop_reason }).toEqual({ status: 'partial', reason: 'not_converged', stop: 'not_converged' });+ streaks.push(drained.pass!.not_converged_streak);+ loops.push(drainNext(drained, 'gbrain sync --source default --no-pull', 'default')!.safe_to_loop);+ }+ installFaultHook(undefined);+ expect({ streaks, loops }).toEqual({ streaks: [1, 2, 3], loops: [true, true, false] });+ expect((await performManagedSync(engine, { ...OPTS, workingTree: true })).status).toBe('synced');+ const [row] = await engine.executeRaw<{ streak: number }>("SELECT (completed_keys->0->'obligations'->>'not_converged_streak')::int AS streak FROM op_checkpoints WHERE op='managed-sync-pass'");+ expect(row?.streak).toBe(0);+ }, { setup }), 240_000);});diff --git a/test/sync-pass-outcomes-6712.test.ts b/test/sync-pass-outcomes-6712.test.tsnew file mode 100644index 0000000000..6bde8adb8e--- /dev/null+++ b/test/sync-pass-outcomes-6712.test.ts@@ -0,0 +1,59 @@+/**+ * #6712 PR 4b lane A, probe 52: the outcome golden for each row of design v3.2 §9, direct and delegated through a job.+ *+ * Protects: each live-pass stop (not_converged below and at the 3-pass streak, the selection-scoped synced pass, grant_scope,+ * reconcile_host_required, reconcile_read_incomplete, admission_paused) drains to its §9 outcome, exit (1 only when+ * blocked), job disposition and follow-up, and its exact JSON (outcome, drain, next with its rendered fix) on the CLI and in+ * a durable sync job's result. A change to any row's wire shape fails the golden+ * (test/fixtures/goldens/sync/pass-outcomes.json, GBRAIN_TEST_UPDATE_GOLDENS=1 regenerates it deliberately).+ *+ * Fails on capy/6712-pr4b (8cda2764b): there every one of these stops drains as resumable / deadline (or blocked /+ * blocked_by_failures) with the deadline's or the failed page's next step.+ */+import { describe, expect, test } from 'bun:test';+import type { SyncResult } from '../src/commands/sync.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { drainJsonFields, jobDisposition, runDrain, syncOutcome, type JobDisposition } from '../src/core/persistence/sync-drain.ts';+import { settleJobDrain } from '../src/core/minions/handlers/sync-job-drain.ts';+import { defineNormalizer, expectGolden } from './helpers/golden.ts';++const RESUME = 'gbrain sync --source default --no-pull';+const passResult = (status: SyncResult['status'], reason: SyncResult['reason'] | undefined, streak = 0): SyncResult => ({ status, fromCommit: 'a', toCommit: 'b',+ added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0, ...(reason ? { reason } : {}),+ pass: { pass_id: '00000000-0000-4000-8000-000000006712', kind: 'full', round: 4, outcome: status === 'synced' ? 'synced' : 'resumable', stop_reason: reason ?? null,+ candidates: 2, settled: 1, remaining: 1, not_converged_streak: streak } });++/** The §9 table: result, then the outcome, exit, next.fix.next, safe_to_loop, job disposition and follow-up it must drain to. */+const ROWS: Array<{ row: string; result: SyncResult; outcome: string; exit: 0 | 1; next: string | null; loop: boolean | null; job: JobDisposition; followUp: string }> = [+ { row: 'not_converged (stop)', result: passResult('partial', 'not_converged', 1), outcome: 'resumable', exit: 0, next: 'run', loop: true, job: 'continue', followUp: 'the next tick' },+ { row: 'not_converged after a 3-pass streak', result: passResult('partial', 'not_converged', 3), outcome: 'resumable', exit: 0, next: 'report', loop: false, job: 'needs_operator', followUp: 'none' },+ { row: 'scoped pass converged (selection_scoped)', result: passResult('synced', 'selection_scoped'), outcome: 'synced', exit: 0, next: null, loop: null, job: 'synced', followUp: 'none' },+ { row: 'grant_scope (stop)', result: passResult('blocked_by_failures', 'grant_scope'), outcome: 'blocked', exit: 1, next: 'tell_user_to_run', loop: false, job: 'needs_operator', followUp: 'none' },+ { row: 'reconcile_host_required (stop)', result: passResult('blocked_by_failures', 'reconcile_host_required'), outcome: 'blocked', exit: 1, next: 'tell_user_to_run', loop: false, job: 'needs_operator', followUp: 'none' },+ { row: 'reconcile_read_incomplete (stop)', result: passResult('blocked_by_failures', 'reconcile_read_incomplete'), outcome: 'blocked', exit: 1, next: 'report', loop: false, job: 'needs_operator', followUp: 'none' },+ { row: 'admission_paused (stop)', result: passResult('partial', 'admission_paused'), outcome: 'resumable', exit: 0, next: 'tell_user_to_run', loop: false, job: 'needs_operator', followUp: 'none' },+];++const job = { id: 6712, data: { sourceId: 'default' }, signal: new AbortController().signal, updateProgress: async () => undefined } as unknown as MinionJobContext;+const plan = { opts: { drain: true }, row: null, trusted: true } as never;+const normalizer = defineNormalizer<unknown>('sync-pass-outcomes-v1', value => value);++describe('#6712 PR 4b probe 52: the §9 outcome golden', () => {+ test('each row drains to its outcome, exit, next, loop, job disposition and follow-up, direct and delegated', async () => {+ const golden: Record<string, unknown> = {};+ for (const spec of ROWS) {+ const drained = await runDrain({ pass: async () => spec.result });+ const direct = drainJsonFields(drained, RESUME, 'default') as { outcome: string; next?: { safe_to_loop: boolean; fix?: { next: string } } };+ const delegated = await settleJobDrain({} as BrainEngine, job, drained, 'default', plan) as { outcome?: string; incomplete?: boolean; continuation_job_id?: number | null; next?: unknown };+ const exit = syncOutcome(drained) === 'blocked' ? 1 : 0;+ expect({ row: spec.row, outcome: direct.outcome, exit, next: direct.next ? direct.next.fix?.next ?? null : null, loop: direct.next ? direct.next.safe_to_loop : null,+ job: jobDisposition(drained, 'default'), followUp: delegated.continuation_job_id ? 'continuation job' : spec.job === 'continue' ? 'the next tick' : 'none' })+ .toEqual({ row: spec.row, outcome: spec.outcome, exit: spec.exit, next: spec.next, loop: spec.loop, job: spec.job, followUp: spec.followUp });+ expect(delegated.outcome).toBe(spec.outcome);+ expect(delegated.incomplete).toBe(spec.job !== 'synced');+ golden[spec.row] = { direct, delegated, exit, job: jobDisposition(drained, 'default') };+ }+ expectGolden('sync/pass-outcomes', golden, normalizer);+ });+});