Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 2 L4: per-hold-code action-chain test, tests, docs and changelog
garrytan75ac62d8870a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4799d01e77..cab60e8cc7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,35 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Every held file has a working exit, and a hold asks a person only when its safe action really failed (#6712 PR 2, lane L4).** Each of the 14 hold codes now leads an agent to a cleared hold or to one decision sentence for the user; a test drives every code's printed chain under the agent operator protocol.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| a managed-sync file `write_gate.external_mode=reject` refuses | its receipt failed at preparation and the whole source stopped `blocked_by_failures` | the file is held `write_gate_rejected` (needs a person) and the rest syncs |+| `sync status` shows a `purged_content` or `write_gate_rejected` hold | `Unknown code` (systemic, needs a person) | a page hold with its own sentence (unpurge or edit; switch the gate or edit) |+| you exclude a held file with `sync.exclude` (its printed fix), or multimodal is off for a held image | the hold stayed until some unrelated commit | the next `gbrain sync` releases it, even with nothing new committed |+| a hold is re-held three times within an hour | `needs_human` | still the agent's: `needs_human` needs 3 failed attempts and 24 h since it was first held; a file still being edited (`worktree_dirty`) and an image never escalate |+| `unblock --apply` finds a dirty file still uncommitted, or a repair holds the file again | not counted | counts as a failed attempt toward that rule |+| a `source_changed` receipt (`sources writer failures`, `write-request`) | `sources reconcile … --preview` for every reason | by recorded reason: two-sided drift → `repair file-drift --slug … --prefer database`; missing file → `repair ghost-pages`; admission race → retry; binding or unsafe target → writer status |+| many drift receipts | one command per page | `repair file-drift --all-drifted --since <oldest receipt instant>` |+| `gbrain repair file-drift --since 7d` | unknown flag | narrows `--all-drifted` to recent drift; the preview and apply carry one concrete instant |+| a managed sync with live pages whose files are gone | silent | `[sync] N live page(s) … have no canonical file`, with the `repair ghost-pages` preview; sync never deletes them |+| a parked cursor with a non-empty queue and no consumer (#6552) | doctor listed it as parked (info) | doctor `managed_sync_not_moving` fails with the resume sync as its fix |+| `gbrain doctor --json` | no intervention counts | `sync_soak_counters`: interventions and content decisions per day for 7 days |++### Itemized changes++- Fault table: `purged_content` and `write_gate_rejected` rows; `source_changed` reasons (`file_database_drift`, `canonical_file_missing`, `pending_import`, `raw_file_changed`, `source_binding_changed`, `unsafe_file_target`) each get their own row. The runbook table is regenerated.+- Hold escalation: `HOLD_ESCALATE_MS` (24 h) beside `HOLD_ATTEMPTS_NEEDS_HUMAN`; holds record `first_held_at`, `edited_at` and `needs_human_at`.+- `src/core/since.ts`: one `--since` parser for `agent logs` and `repair file-drift`.+- `src/core/persistence/sync-ghosts.ts`: the bounded post-sync ghost count (`SyncResult.ghostPages`).+- `src/core/persistence/soak-counters.ts`: the counters and doctor's `sync_soak_counters`.+- Managed sync's freeze screen applies the write gate (`SyncImportScreenInput.sourceConfig`); a discovery with nothing to write releases holds that left the source (`releaseDiscoveredHolds`).+## [0.60.255.0] - 2026-10-16**One drainer per managed source, one cursor per source, and a resume never refuses over processing flags (#6712 PR 1).** Two processes could drain one source at once (a cron `gbrain sync` beside a serve, a `--no-delegate` run beside a job), racing each other's checkpoints, and every writer, authority and option set got its own cursor, so a resume by a different process started over or refused with `cursor_processing_options_conflict`. Now every managed pass runs under the source's drain lease, a second run follows the holder instead of competing, the cursor key is the source itself, and the cursor's opt-outs are inherited.diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex f2e6060e4a..7f0d6c4299 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -33,3 +33,6 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.+- `src/core/since.ts` — #6712 PR 2: `parseSince(input, flag, now)`, the one `--since` parser (`gbrain agent logs --since`, `gbrain repair file-drift --since`). An age (`90s`, `30m`, `12h`, `7d`) becomes one concrete UTC instant at parse time; an ISO-8601 date or timestamp is normalized; anything else throws `invalid_params` naming the flag. Callers print and hash the instant, never the age. Tests: `test/sync-exits-l4-6712.test.ts`, `test/agent-cli.test.ts`.+- `src/core/persistence/sync-ghosts.ts` — #6712 PR 2: `countSyncGhosts(engine, sourceId)`, the post-sync ghost count. It reuses `scanGhostSource` from `repair/ghost-pages.ts` (no second classifier) with a candidate bound of `SYNC_GHOST_CHECK_LIMIT` (50) stats, leaves out paths sync holds (a held file is the hold's to explain), and returns the count, samples and the `gbrain repair ghost-pages --source <id>` preview as its fix. Sync never deletes or tombstones a ghost; `commands/sync/perform.ts` prints one line and sets `SyncResult.ghostPages`. Test: `test/sync-exits-l4-6712.test.ts`.+- `src/core/persistence/soak-counters.ts` — #6712 PR 2: the soak counters doctor `sync_soak_counters` reports (one `op_checkpoints` row per UTC day under op `sync-soak-counters`). Interventions: `sync_non_plain` (`nonPlainSyncFlags`, from `sync/run.ts`), `repair_apply` (`repair.ts`), `unblock_apply` (`sync/operator.ts`), `retry_held` (`sources-retry-held.ts`) and `needs_human` (`sweepNeedsHumanHolds`, run after each managed sync: stamps `needs_human_at` on a hold the fault table now calls `needs_human` and counts it once; the stamp survives same-code re-holds). Content decisions: `file_drift_apply` and `file_drift_hold`. `readSoakCounters` sums the last seven days. Counting never fails the command that counts. Test: `test/sync-exits-l4-6712.test.ts`.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex d5ff8eab5f..5ff1f1e3c0 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -29,7 +29,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.-- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark, one probe of the partial index `persistence_requests_sync_watermark`, v223, whose predicate repeats the read's kind test; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the exact `gbrain sources writer status --source <id> --json` beside `data_moving: false`; doctor `managed_sync_not_moving` (warn; counts against the score for `not_moving`, never for `parked`) uses the same rule with that command as its structured fix; `serve` prints one `[gbrain notice]` when a source flips. `/health` stays liveness-only.+- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. `/health` stays liveness-only.- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` carries the read failure's own code with `fix.next: report`. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 30a5e9f887..d43322f278 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1177,6 +1177,7 @@ gbrain repair file-drift --source <id> --slug notes/a --prefer file # pregbrain repair file-drift --source <id> --all-drifted --class structurally_additive --prefer filegbrain repair file-drift --source <id> --all-drifted --class structurally_additive --prefer file --apply --expect <hash>gbrain repair file-drift --source <id> --all-drifted --only 'concepts/**' --prefer database # preview every drifted page filed under concepts/+gbrain repair file-drift --source <id> --all-drifted --since 7d --prefer database # only pages that drifted in the last 7 days```Select pages with `--slug` (repeatable), `--request <id>` (a conflict receipt,@@ -1207,6 +1208,17 @@ and printed in the apply command, so running that exact command appliesexactly the previewed pages (an apply under other globs refuses`preview_changed`). Quote a glob so the shell does not expand it.+<a id="file-drift-since"></a>`--since <ISO-8601 | age>` narrows `--all-drifted` to the pages whose newest+drift receipt was recorded at or after that instant (#6712 PR 2). An age+(`90s`, `30m`, `12h`, `7d`) is converted to one concrete UTC instant when the+command runs, and the preview hash and the printed apply command carry that+instant, not the age, so the apply selects the same pages the preview did.+Any other value refuses before anything is read. `--since` with `--slug` or+`--request` refuses: it only narrows `--all-drifted`. The fix that+`gbrain sources writer failures` prints for a group of drift receipts already+carries `--since` with the oldest receipt's time. One parser serves this flag+and `gbrain agent logs --since`.+`--keep` belongs to `stuck-recovery`; file-drift refuses it and names theequivalent: `--prefer database` keeps the database copy, `--prefer file`keeps the file.diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 129f4b6ce6..54df33c3dc 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -73,9 +73,14 @@ Every hold and error has three fields, from one table`reconcile` previews two diverged versions; `upgrade` installs a newer gbrain;`none` waits for a person.- `needs_human`: a person has to choose or act before it clears;- `human_reason` says what. A page held three times with the same code- (`attempts`) is `needs_human` whatever its code says: it keeps moving under- the sync. A repair-class hold is `needs_human` when its stored repair state+ `human_reason` says what. A page whose safe action failed three times with+ the same code (`attempts`: a re-hold, or a failed `unblock --apply` or+ repair) over at least 24 hours since it was first held is `needs_human`+ whatever its code says, and `human_reason` ends with both numbers. Two holds+ never escalate this way: a `worktree_dirty` file whose uncommitted bytes+ changed in the last 24 hours (someone is still editing it) and a+ `managed_image_sync_unsupported` image (held by design until multimodal+ embedding is on or the image is excluded). A repair-class hold is `needs_human` when its stored repair statesays so: a fence hold the lane marked `manual` (a manual-only reason, a gaterejection, a model answer the run does not retry) or `paid` (spend only theuser raises), and a slug-conflict hold the lane decided a person must settle@@ -87,10 +92,10 @@ Every hold and error has three fields, from one table<!-- sync-fault-table:begin (pinned by test/sync-runbook-table.test.ts) -->| Code | Class | Safe actions | Needs human | Escalate when ||---|---|---|---|---|-| `worktree_dirty` | page | retry_when_clean | no | held 3 times: the file keeps changing without being committed |+| `worktree_dirty` | page | retry_when_clean | no | 3 failed attempts over 24 h with no edit in the last 24 h: the uncommitted edit is abandoned || `concurrent_write` | page | reconcile | yes | always: the file and the database page diverge || `file_drift` | page | reconcile | yes | always: the page changed in the database since its file was last imported |-| `preparation_stalled` | page | retry, upgrade | no | held 3 times, or writer status names a step that never finishes |+| `preparation_stalled` | page | retry, upgrade | no | 3 failed attempts over 24 h, or writer status names a step that never finishes || `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) || `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) || `frontmatter_slug_conflict` | page | repair | no | the repair preview needs an interpretation |@@ -99,10 +104,18 @@ Every hold and error has three fields, from one table| `content_rejected` | page | none | yes | always || `parser_regression` | page | upgrade | yes | always: a gbrain bug || `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off |+| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |+| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting || `revision_conflict` | page | retry | no | the same path fails again after a rerun || `page_identity_changed` | page | retry | no | the same path fails again after a rerun || `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun || `source_changed` | page | retry | no | the same path fails again after a rerun |+| `pending_import` | page | retry | no | the same path refuses again after a sync imported its file |+| `raw_file_changed` | page | retry | no | the same path fails again after a rerun re-freezes it |+| `file_database_drift` | page | reconcile | yes | always: the file and the database page diverge |+| `canonical_file_missing` | page | repair | yes | always: no sync can import a file that is not there |+| `source_binding_changed` | systemic | none | yes | always: the source or its checkout binding moved |+| `unsafe_file_target` | systemic | none | yes | always: the file target resolves outside its source || `cancelled` | page | retry | no | the same group is cancelled again after a rerun || `knock_on` | page | retry | no | never: superseded; an older gbrain cancelled this page for another page's failure and a plain sync re-freezes it || `run_replaced` | page | retry | no | never: another run of the source superseded this one and covers its pages |@@ -258,6 +271,28 @@ apply with the printed `--apply --expect <hash>` once the user agrees. A cursorwith a live pending request is kept; the loop above owns it([repair guide](repair.md#managed-sync-orphans)).+## Soak counters++`gbrain doctor --json` reports `sync_soak_counters` (info, never a warning):+how often a person or an agent had to step in, per UTC day for the last seven+days, so a soak can show that sync keeps moving on its own.++- `interventions`: `sync_non_plain` (a `gbrain sync` with a recovery flag such+ as `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain+ scheduler flags `--all`, `--no-pull`, `--hard-deadline`, `--no-embed`,+ `--no-lanes`, `--no-bulk` and `--json` do not count), `repair_apply` (a+ `gbrain repair … --apply` of any kind but file-drift), `unblock_apply`,+ `retry_held` (a `gbrain sources retry-held` without `--dry-run`) and+ `needs_human` (a hold that turned `needs_human`, counted once, by the first+ sync that sees it).+- `content_decisions`: `file_drift_apply` (a `gbrain repair file-drift+ --apply`) and `file_drift_hold` (a `file_drift` hold a sync found). These+ are choices about which version of a page wins, not interventions; a+ `keep_db` prefix reconciles with no decision and counts in neither line.++Each line has one count per kind and a `total`; `by_day` lists both line+totals for each day that recorded anything. Fields are only ever added.+## See also- [`write-refusals.md`](write-refusals.md#held-files-and-content-refusals): every hold code with its recovery.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 4252bc1e87..f949a2ed1e 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -133,7 +133,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.-<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:+<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:1. `gbrain sources status <id> --json`: `data_moving`, `not_moving_since`, `movement_state` and, beside `data_moving: false`, the exact `gbrain sources writer status --source <id> --json` to run next. Doctor's `managed_sync_not_moving` fix is that same command.2. `gbrain sources writer status --source <id> --json`: every running claim ends in one `claim.next` envelope (`code` `claim_running`, `claim_overdue` or `claim_lapsed`). `claim_running` carries `retry_after_ms` and a `run` of the same status command while the owner is inside its allowance (the owner's own budget will cut the write; nothing to do but rerun after the delay), `tell_user_to_run` naming the owner `kind` and pid past the ceiling or when the owner reads `restart_required` (restart that process), `run` the printed resume command for a lapsed claim. `host.consumers` lists the processes on this host holding a consumer (pid, kind, mode `full|waiter_only`, started_at, the pool gauge), so a second consumer is visible in the same call.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 34924c5f34..cd440d158f 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -51,7 +51,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- |-| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |+| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | The receipt's fix (`gbrain sources writer failures <source>`, `gbrain write-request <request_id> --json`) previews keeping the database copy for that one page with `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (`--prefer file` previews importing the file instead); a person picks the side, then the agent runs the apply command the preview prints. A group of such receipts gets `--all-drifted --since <instant>` with the oldest receipt's time, so only pages that drifted since then are selected. For a hand merge: `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). || <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). || <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. || <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |@@ -193,11 +193,11 @@ with each file and fix the ones that need no guessing."*| <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. || <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. || <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). The lane judges the file with the screen managed sync froze it with: a hold the sync screen now admits as the file is (its slug line names the file's own page as written, or it no longer declares a conflicting slug) is **imported** unchanged in one guarded write that clears only the hold observation the lane read (a hold a newer sync wrote stays, with a retry), and a file sync would hold whatever the lane writes is [`slug_page_mismatch`](#slug_page_mismatch). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). |-| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold. |+| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold, also when nothing was committed since (#6712 PR 2). || <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. || <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. || <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. See [expire versus purge](memory-boundaries.md#purge). |-| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |+| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source). The hold is `needs_human`. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |diff --git a/llms-full.txt b/llms-full.txtindex 275a0c851f..8db5afd862 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7245,9 +7245,14 @@ Every hold and error has three fields, from one table`reconcile` previews two diverged versions; `upgrade` installs a newer gbrain;`none` waits for a person.- `needs_human`: a person has to choose or act before it clears;- `human_reason` says what. A page held three times with the same code- (`attempts`) is `needs_human` whatever its code says: it keeps moving under- the sync. A repair-class hold is `needs_human` when its stored repair state+ `human_reason` says what. A page whose safe action failed three times with+ the same code (`attempts`: a re-hold, or a failed `unblock --apply` or+ repair) over at least 24 hours since it was first held is `needs_human`+ whatever its code says, and `human_reason` ends with both numbers. Two holds+ never escalate this way: a `worktree_dirty` file whose uncommitted bytes+ changed in the last 24 hours (someone is still editing it) and a+ `managed_image_sync_unsupported` image (held by design until multimodal+ embedding is on or the image is excluded). A repair-class hold is `needs_human` when its stored repair statesays so: a fence hold the lane marked `manual` (a manual-only reason, a gaterejection, a model answer the run does not retry) or `paid` (spend only theuser raises), and a slug-conflict hold the lane decided a person must settle@@ -7259,10 +7264,10 @@ Every hold and error has three fields, from one table<!-- sync-fault-table:begin (pinned by test/sync-runbook-table.test.ts) -->| Code | Class | Safe actions | Needs human | Escalate when ||---|---|---|---|---|-| `worktree_dirty` | page | retry_when_clean | no | held 3 times: the file keeps changing without being committed |+| `worktree_dirty` | page | retry_when_clean | no | 3 failed attempts over 24 h with no edit in the last 24 h: the uncommitted edit is abandoned || `concurrent_write` | page | reconcile | yes | always: the file and the database page diverge || `file_drift` | page | reconcile | yes | always: the page changed in the database since its file was last imported |-| `preparation_stalled` | page | retry, upgrade | no | held 3 times, or writer status names a step that never finishes |+| `preparation_stalled` | page | retry, upgrade | no | 3 failed attempts over 24 h, or writer status names a step that never finishes || `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) || `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) || `frontmatter_slug_conflict` | page | repair | no | the repair preview needs an interpretation |@@ -7271,10 +7276,18 @@ Every hold and error has three fields, from one table| `content_rejected` | page | none | yes | always || `parser_regression` | page | upgrade | yes | always: a gbrain bug || `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off |+| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |+| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting || `revision_conflict` | page | retry | no | the same path fails again after a rerun || `page_identity_changed` | page | retry | no | the same path fails again after a rerun || `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun || `source_changed` | page | retry | no | the same path fails again after a rerun |+| `pending_import` | page | retry | no | the same path refuses again after a sync imported its file |+| `raw_file_changed` | page | retry | no | the same path fails again after a rerun re-freezes it |+| `file_database_drift` | page | reconcile | yes | always: the file and the database page diverge |+| `canonical_file_missing` | page | repair | yes | always: no sync can import a file that is not there |+| `source_binding_changed` | systemic | none | yes | always: the source or its checkout binding moved |+| `unsafe_file_target` | systemic | none | yes | always: the file target resolves outside its source || `cancelled` | page | retry | no | the same group is cancelled again after a rerun || `knock_on` | page | retry | no | never: superseded; an older gbrain cancelled this page for another page's failure and a plain sync re-freezes it || `run_replaced` | page | retry | no | never: another run of the source superseded this one and covers its pages |@@ -7430,6 +7443,28 @@ apply with the printed `--apply --expect <hash>` once the user agrees. A cursorwith a live pending request is kept; the loop above owns it([repair guide](repair.md#managed-sync-orphans)).+## Soak counters++`gbrain doctor --json` reports `sync_soak_counters` (info, never a warning):+how often a person or an agent had to step in, per UTC day for the last seven+days, so a soak can show that sync keeps moving on its own.++- `interventions`: `sync_non_plain` (a `gbrain sync` with a recovery flag such+ as `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain+ scheduler flags `--all`, `--no-pull`, `--hard-deadline`, `--no-embed`,+ `--no-lanes`, `--no-bulk` and `--json` do not count), `repair_apply` (a+ `gbrain repair … --apply` of any kind but file-drift), `unblock_apply`,+ `retry_held` (a `gbrain sources retry-held` without `--dry-run`) and+ `needs_human` (a hold that turned `needs_human`, counted once, by the first+ sync that sees it).+- `content_decisions`: `file_drift_apply` (a `gbrain repair file-drift+ --apply`) and `file_drift_hold` (a `file_drift` hold a sync found). These+ are choices about which version of a page wins, not interventions; a+ `keep_db` prefix reconciles with no decision and counts in neither line.++Each line has one count per kind and a `total`; `by_day` lists both line+totals for each day that recorded anything. Fields are only ever added.+## See also- [`write-refusals.md`](write-refusals.md#held-files-and-content-refusals): every hold code with its recovery.@@ -10555,7 +10590,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.-<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:+<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:1. `gbrain sources status <id> --json`: `data_moving`, `not_moving_since`, `movement_state` and, beside `data_moving: false`, the exact `gbrain sources writer status --source <id> --json` to run next. Doctor's `managed_sync_not_moving` fix is that same command.2. `gbrain sources writer status --source <id> --json`: every running claim ends in one `claim.next` envelope (`code` `claim_running`, `claim_overdue` or `claim_lapsed`). `claim_running` carries `retry_after_ms` and a `run` of the same status command while the owner is inside its allowance (the owner's own budget will cut the write; nothing to do but rerun after the delay), `tell_user_to_run` naming the owner `kind` and pid past the ceiling or when the owner reads `restart_required` (restart that process), `run` the printed resume command for a lapsed claim. `host.consumers` lists the processes on this host holding a consumer (pid, kind, mode `full|waiter_only`, started_at, the pool gauge), so a second consumer is visible in the same call.diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex bd3b5c5f8f..fa4fa1b3c1 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -46,6 +46,7 @@"test/grandfather-managed.test.ts": 55407,"test/harness-skills-epoch.test.ts": 4291,"test/held-read-signals.test.ts": 9120,+ "test/hold-action-chain-6712.test.ts": 40000,"test/import-frontmatter-key-order-5158.test.ts": 7496,"test/import-inline-chunk-keep.test.ts": 6570,"test/import-revision-concurrency.test.ts": 4485,@@ -163,6 +164,7 @@"test/sync-drain-head-blocked-6543.test.ts": 7583,"test/sync-drain-inpass-stall.test.ts": 6902,"test/sync-drain-write-capacity.test.ts": 11054,+ "test/sync-exits-l4-6712.test.ts": 15000,"test/sync-frontmatter-recovery.test.ts": 9314,"test/sync-frontmatter-slug-conflict.test.ts": 7546,"test/sync-full-cursor-slices-6349.test.ts": 19023,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 849285b4d2..04b330c369 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -664,6 +664,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.255.0', text: 'Resuming an unfinished managed sync never refuses over processing options any more (#6712): the cursor\'s `--no-embed`, `--no-extract` and `--no-schema-pack` opt-outs are inherited by every run that resumes it, a flag that would have asked for more processing is reported in `inherited_options` (and printed), and `cursor_processing_options_conflict` is no longer returned. A writer that resumes another writer\'s cursor admits the rest under its own validated grant; requests already admitted stay under their original principal, are read and cancelled under it, and are never rewritten.' },{ since: '0.60.255.0', text: 'The delegation wire\'s `explicitProcessing` field is accepted from a sync client below 0.60.255.0 and ignored until 2026-11-14 (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), then removed. `gbrain sync --retry-failed` on a managed source now counts every failure of the source, since no failure sits under another cursor key.' },{ since: '0.60.255.0', text: 'Downgrading below 0.60.255.0 must be quiescent: stop `gbrain serve`, autopilot and sync crons, let the running sync finish, then downgrade. An older binary does not take the drain lease; while a newer non-job holder drains, it writes a `gbrain-drain-lease` row that the live-sync check of 0.60.231.0 and later sees, so such an autopilot backs off instead of dispatching a second sync, but an older CLI started beside a newer drainer is not fenced. An older gbrain resumes an old-key cursor only; a cursor this release created under the new key is invisible to it and is rediscovered from the last synced commit.' },+ // #6712 PR 2 lane L4 (exits, escalation, soak counters): placeholder since; the fresh-install cases in behavior-change-notice.test.ts pass once VERSION is stamped 0.60.256.0.+ { since: '0.60.256.0', text: 'A held file now asks for a person (`needs_human`) only after its safe action failed three times and at least 24 hours have passed since it was first held (#6712). Three re-holds within an hour stay the agent\'s to retry. A `worktree_dirty` file whose uncommitted bytes changed in the last day, and an image held while multimodal embedding is off, never escalate this way. A failed `sync unblock --apply` (still dirty) or a repair that holds the file again counts as an attempt.' },+ { since: '0.60.256.0', text: 'A managed-sync file that `write_gate.external_mode=reject` refuses is now held as `write_gate_rejected` when sync freezes it, instead of failing its receipt and stopping the rest of the source. A held file that leaves the source (excluded with `sync.exclude`, or an image while multimodal embedding is off) is released by the next sync even when nothing new was committed.' },+ { since: '0.60.256.0', text: 'A `source_changed` write receipt\'s fix now follows its recorded reason: two-sided drift previews `gbrain repair file-drift --source <id> --slug <slug> --prefer database` (a group of them `--all-drifted --since <instant>`), a missing canonical file previews `gbrain repair ghost-pages`, an admission race is retried, and a changed binding or unsafe target names `gbrain sources writer status`. `gbrain repair file-drift` takes `--since <ISO-8601 | age>` to narrow `--all-drifted`.' },+ { since: '0.60.256.0', text: 'Doctor `managed_sync_not_moving` now fails (it used to list the source as parked) when a managed source\'s queue holds admitted requests with no consumer and nothing has moved for longer than `persistence.preparation_ceiling_ms`; its fix is the resume sync, which consumes the queue (#6552). A managed sync now prints a line when live pages of the source have no canonical file, naming the read-only `gbrain repair ghost-pages` preview; it never deletes them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/file-drift-bulk-reconcile.test.ts b/test/file-drift-bulk-reconcile.test.tsindex d8c98a8e67..97a335723c 100644--- a/test/file-drift-bulk-reconcile.test.ts+++ b/test/file-drift-bulk-reconcile.test.ts@@ -202,6 +202,30 @@ for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${expect((await engine.getPage(CONCEPTS[0]!, { sourceId }))!.compiled_truth).toBe(`Stored ${CONCEPTS[0]}.`);}), 240_000);+ test('#6712 PR 2: --all-drifted --since 7d keeps pages drifted since that instant, and the returned command carries the instant and applies exactly them', () => fixture(async ({ root, sourceId, ctx }) => {+ await driftedPages(root, ctx);+ // The person's conflict is ten days old; the concepts' are new.+ await engine.executeRaw("UPDATE persistence_requests SET created_at=now()-interval '10 days' WHERE source_id=$1 AND slug=$2 AND state='conflict'", [sourceId, PERSON]);+ // A group of drift conflicts on several pages is fixed with one --since preview at the group's oldest conflict, never an age.+ const { readTerminalFailures } = await import('../src/core/persistence/terminal-failures.ts');+ const grouped = await readTerminalFailures(engine, { sourceId, groupBy: 'category', state: 'all', sinceDays: 30 });+ const group = grouped.status === 'ok' ? grouped.groups!.find(g => g.category === 'file_conflict') : undefined;+ expect(group?.fix.argv?.slice(0, 7)).toEqual(['gbrain', 'repair', 'file-drift', '--source', sourceId, '--all-drifted', '--since']);+ expect(group!.fix.argv![7]).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);+ expect(Date.parse(group!.fix.argv![7]!)).toBeLessThan(Date.now() - 9 * 86_400_000);+ const future = (await json(['file-drift', '--source', sourceId, '--all-drifted', '--since', new Date(Date.now() + 3_600_000).toISOString(), '--prefer', 'database'])).results[0]!;+ expect(future).toMatchObject({ affected: 0, residuals: { not_selected: 4 } });+ const preview = (await json(['file-drift', '--source', sourceId, '--all-drifted', '--since', '7d', '--prefer', 'database'])).results[0]!;+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 3, residuals: { not_selected: 1 } });+ const command = String(preview.apply_command);+ const since = /--since (\S+)/.exec(command)?.[1];+ expect(since).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);+ expect(command).not.toContain('--since 7d');+ const applied = (await json(argvFromCommand(command)!.slice(2))).results[0]!;+ expect(applied).toMatchObject({ mode: 'apply', applied: 3, complete: true, outcomes: { repaired: 3 } });+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([PERSON]);+ }), 240_000);+test('the globs are bound into the preview hash: --skip narrows the set, and an apply under other globs refuses preview_changed', () => fixture(async ({ root, sourceId, ctx }) => {await driftedPages(root, ctx);const scope = await resolveRepairScope(engine, sourceId);diff --git a/test/hold-action-chain-6712.test.ts b/test/hold-action-chain-6712.test.tsnew file mode 100644index 0000000000..08ab4f7754--- /dev/null+++ b/test/hold-action-chain-6712.test.ts@@ -0,0 +1,408 @@+/**+ * #6712 PR 2 (L4): every hold code's printed exit, driven the way an agent drives it under AGENT_OPERATOR_v1.+ *+ * Protects: for each of the 13 Git hold codes on master plus `file_drift`, a real managed sync of a fixture holds the+ * file; the agent reads `gbrain sync status --source <id> --json` and then either+ * - relays the one decision sentence: the hold `needs_human`, `next.user_message` carries its `human_reason` (one+ * sentence), and the first printed step writes nothing; or+ * - runs the hold's fix chain step by step (`next: run` only; a repair preview, then the apply command it printed,+ * bound to the preview's hash with `--expect`; then the next step), and the hold clears.+ * A code whose way out is a person's act (commit the dirty edit, exclude the image, pick the drift side) gets that act+ * from the fixture first, as the person would, and the chain then clears it.+ * Fails when: a printed fix cannot clear its hold, a hold that cannot clear asks nobody (or asks in more than one+ * sentence), or a needs_human hold's first step writes.+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { runSync } from '../src/commands/sync.ts';+import { runSyncStatus, runSyncUnblock } from '../src/commands/sync/operator.ts';+import { runSources } from '../src/commands/sources.ts';+import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';+import { __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import type { SyncOpts } from '../src/commands/sync.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { waitFor } from './helpers/wait-for.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-hold-chain-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: 'sk-test-not-used', VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, GBRAIN_EMBEDDING_MULTIMODAL: undefined };+const CONFIG = ['sync.write_through', 'sync.parser_regression', 'sync.exclude', 'content_sanity.junk_disposition', 'write_gate.external_mode'];+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const note = (title: string, body = 'A synthetic observation.', extra = '') => `---\ntitle: ${title}\n${extra}---\n${body}\n`;+const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long synthetic observation that keeps Git rename detection certain.`).join('\n');+const long = (title: string) => note(title, LONG);+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const FOLDED = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n';+const LONG_BROKEN = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;+const TAKES = (who: string) => `---\ntitle: Holder\n---\nA synthetic page.\n\n<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n`+ + `| 1 | Synthetic take | take | ${who} | 0.7 | 2026-01 | chat |\n<!--- gbrain:takes:end -->\n`;++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++async function managed(engine: BrainEngine, files: Record<string, string | Buffer>) {+ const id = `chain-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ // Git target effects (a repair's commit) run only in a durability-hardened checkout.+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);+ const write = (path: string, content: string | Buffer) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };+ for (const [path, content] of Object.entries(files)) write(path, content);+ commit(root, 'fixture');+ 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');+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });+ const held = async () => ((await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? []).map(hold => ({ path: hold.path, code: hold.code }));+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: id } as unknown as OperationContext;+ return { id, root, write, sync, held, ctx };+}++async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ for (const engine of engines) {+ // A printed plain `gbrain sync` embeds: the transport answers locally, so no provider is called.+ __setEmbedTransportForTests((async (args: { values: unknown[] }) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.01)) })) as never);+ try { await run(engine); }+ finally { __setEmbedTransportForTests(null); installFaultHook(undefined); await disposePersistenceConsumer(engine); for (const key of CONFIG) await engine.unsetConfig(key); }+ }+ });+}++type Step = { argv?: string[]; next: string; actor: string; user_message?: string; then?: Step };+type Hold = { path: string; code: string; needs_human: boolean; human_reason?: string; safe_actions: string[]; fix: Step };+/** The read-only inspections a chain may print; the agent reads them and moves on. */+const INSPECT = [['config', 'get'], ['pages', 'purges', 'list'], ['doctor']];+const inspects = (argv: string[]) => INSPECT.some(prefix => prefix.every((word, i) => argv[i + 1] === word)) || (argv[1] === 'sources' && argv[2] === 'reconcile' && argv.includes('--preview'));+const writes = (argv: string[] = []) => argv.includes('--apply') || argv.includes('--yes');+/** One sentence: no sentence end followed by a capitalized next sentence (a trailing parenthetical such as "(held 3 times …)" is part of it). */+const oneSentence = (text: string) => /[.!?]$/.test(text) && !/[.!?]\s+[A-Z]/.test(text);++class CliExit extends Error { constructor(readonly code: number) { super(`process.exit(${code})`); } }++/** Runs one printed gbrain argv in process through the entry point the CLI dispatches it to; stdout and the exit code. */+async function cli(engine: BrainEngine, argv: string[]): Promise<{ out: string; err: string; exit: number }> {+ expect(argv[0]).toBe('gbrain');+ const [verb, ...rest] = argv.slice(1);+ const out: string[] = [], err: string[] = [];+ const spies = [spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { out.push(parts.map(String).join(' ')); }),+ spyOn(console, 'error').mockImplementation((...parts: unknown[]) => { err.push(parts.map(String).join(' ')); }),+ spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => { out.push(String(chunk)); return true; }) as never),+ spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never),+ spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new CliExit(code ?? 0); }) as never)];+ setCliExitVerdict(0);+ let exit = 0;+ try {+ if (verb === 'repair') await runRepairCommand(engine, rest.includes('--json') ? rest : [...rest, '--json']);+ else if (verb === 'sync' && rest[0] === 'status') await runSyncStatus(engine, rest.slice(1));+ else if (verb === 'sync' && rest[0] === 'unblock') await runSyncUnblock(engine, rest.slice(1));+ else if (verb === 'sync') await runSync(engine, rest);+ else if (verb === 'sources' && rest[0] === 'writer') {+ const parsed = parsePersistenceAdminArgs('writer', rest.slice(1));+ out.push(JSON.stringify(await runPersistenceAdministration(engine, parsed.operation, parsed.params)));+ } else if (verb === 'sources') await runSources(engine, rest);+ else throw new Error(`the driver has no runner for ${argv.join(' ')}`);+ exit = currentExitCode();+ } catch (caught) {+ if (!(caught instanceof CliExit)) throw caught;+ exit = caught.code;+ } finally {+ for (const spy of spies) spy.mockRestore();+ setCliExitVerdict(0);+ }+ return { out: out.join('\n'), err: err.join('\n'), exit };+}++/** A repair's Git commit lands through the persistence consumer; the agent's next sync reads it once it has. */+async function gitEffectsSettled(engine: BrainEngine, sourceId: string) {+ for (let i = 0; i < 100; i++) {+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });+ if (!(await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId])).length) return;+ await Bun.sleep(100);+ }+ throw new Error('git effects did not settle');+}++type Outcome = { ran: string[] } & ({ outcome: 'cleared' | 'still_held' } | { outcome: 'asked'; message: string });++/** The agent: read status; relay a person's decision, or run the hold's chain and report whether the hold cleared. */+async function agent(engine: BrainEngine, sourceId: string, path: string): Promise<Outcome & { hold: Hold }> {+ const status = JSON.parse((await cli(engine, ['gbrain', 'sync', 'status', '--source', sourceId, '--json'])).out) as { holds: Hold[]; needs_human: boolean; next: Step | null };+ const hold = status.holds.find(item => item.path === path)!;+ expect(hold).toBeDefined();+ const ran: string[] = [];+ if (hold.needs_human) {+ // `next` relays the first such hold; each hold carries its own sentence.+ expect(status.needs_human).toBe(true);+ const first = status.holds.find(item => item.needs_human)!;+ expect(status.next?.user_message).toContain(first.human_reason!);+ expect(writes(hold.fix.argv)).toBe(false);+ return { hold, ran, outcome: 'asked', message: hold.human_reason! };+ }+ // A step that prints its own next step (unblock names the sync with the cursor's options) replaces the chain's next one.+ let step: Step | undefined = hold.fix;+ for (let count = 0; step; count++) {+ expect(count).toBeLessThan(6);+ if (step.next !== 'run') return { hold, ran, outcome: 'asked', message: step.user_message ?? '' };+ const argv = step.argv!;+ let following: Step | undefined = step.then;+ if (inspects(argv)) { ran.push(argv.join(' ')); step = following; continue; }+ const result = await cli(engine, argv);+ ran.push(argv.join(' '));+ if (argv[1] === 'repair' && !writes(argv)) {+ // A repair preview: run the apply command it printed, bound to its hash (the user approved the previewed plan).+ const body = JSON.parse(result.out) as { apply_command?: string; results?: Array<{ apply_command?: string }> };+ const apply = body.apply_command ?? body.results?.[0]?.apply_command;+ expect(apply).toContain('--apply --expect ');+ const applied = await cli(engine, apply!.split(' '));+ ran.push(apply!);+ expect(applied.exit).toBe(0);+ await gitEffectsSettled(engine, sourceId);+ if (following?.argv?.[1] === 'repair' && writes(following.argv)) following = following.then;+ } else {+ expect(result.exit).toBe(0);+ const body = (() => { try { return JSON.parse(result.out) as { next?: Step | null; refused?: Array<{ path: string }> }; } catch { return undefined; } })();+ // The step refused this file by name (unblock's still_dirty): the hold stays and the chain ends here.+ if (body?.refused?.some(entry => entry.path === path)) return { hold, ran, outcome: 'still_held' };+ const printed = body?.next;+ if (printed?.argv && printed.next === 'run' && printed.argv.join(' ') !== argv.join(' ')) following = printed;+ }+ step = following;+ }+ const still = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).some(item => item.path === path);+ return { hold, ran, outcome: still ? 'still_held' : 'cleared' };+}++const expectAsked = (result: Outcome) => {+ expect(result.outcome).toBe('asked');+ const message = (result as { message: string }).message;+ expect(oneSentence(message)).toBe(true);+ return message;+};++test('invalid_frontmatter: the preview, then its hash-bound apply, clears the hold', () => each(async engine => {+ const s = await managed(engine, { 'notes/folded.md': FOLDED, 'notes/ok.md': note('Ok') });+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'notes/folded.md', code: 'invalid_frontmatter' }]);+ const result = await agent(engine, s.id, 'notes/folded.md');+ expect(result.ran[0]).toBe(`gbrain repair frontmatter --source ${s.id} --include-ambiguous`);+ expect(result.ran[1]).toMatch(new RegExp(`^gbrain repair frontmatter --source ${s.id} --include-ambiguous --apply --expect \\S+ --yes$`));+ expect(result.outcome).toBe('cleared');+}), 180_000);++test('rename_held: re-binding the rename to the current page clears the hold', () => each(async engine => {+ const s = await managed(engine, { 'notes/x.md': long('X') });+ await s.sync();+ const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', LONG_BROKEN); commit(s.root, 'x to y broken');+ await s.sync();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ s.write('notes/y.md', long('Y')); commit(s.root, 'fix y');+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'notes/y.md', code: 'rename_held' }]);+ const result = await agent(engine, s.id, 'notes/y.md');+ expect(result.ran[0]).toBe(`gbrain repair frontmatter --source ${s.id} --include-ambiguous`);+ expect(result.outcome).toBe('cleared');+ expect((await engine.getPage('notes/y', { sourceId: s.id }))?.id).toBe(x.id);+}), 180_000);++test('frontmatter_slug_conflict: the content lane preview for the file, then its apply, removes the stray slug line', () => each(async engine => {+ const s = await managed(engine, { 'notes/stray.md': note('Stray Note', 'A note from a template.', 'type: note\nslug: notes/nowhere-at-all\n') });+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'notes/stray.md', code: 'frontmatter_slug_conflict' }]);+ const result = await agent(engine, s.id, 'notes/stray.md');+ expect(result.ran[0]).toBe(`gbrain repair content --source ${s.id} --only notes/stray.md`);+ expect(result.outcome).toBe('cleared');+}), 180_000);++test('invalid_fence: the file\'s fence repair preview, then its apply, resolves the holder and clears the hold', () => each(async engine => {+ const s = await managed(engine, { 'people/alice-example.md': note('Alice Example', 'A synthetic person.'), 'people/holder.md': TAKES('Alice Example') });+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'people/holder.md', code: 'invalid_fence' }]);+ const result = await agent(engine, s.id, 'people/holder.md');+ expect(result.ran[0]).toBe(`gbrain repair fences --source ${s.id} --only people/holder.md`);+ expect(result.outcome).toBe('cleared');+}), 180_000);++test('worktree_dirty: once the editor commits, unblock schedules the file and the printed sync clears the hold', () => each(async engine => {+ const s = await managed(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B') });+ await s.sync();+ s.write('notes/b.md', note('B', 'Version two.')); commit(s.root, 'b two');+ s.write('notes/b.md', note('B', 'A private edit still in progress.'));+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'notes/b.md', code: 'worktree_dirty' }]);+ // Before the commit the chain refuses still_dirty and the hold stays (a live editor never escalates).+ expect((await agent(engine, s.id, 'notes/b.md')).outcome).toBe('still_held');+ commit(s.root, 'the editor commits');+ const result = await agent(engine, s.id, 'notes/b.md');+ expect(result.ran).toEqual([`gbrain sync unblock --source ${s.id} --apply --json`, `gbrain sync --source ${s.id} --no-pull --no-embed --no-extract`]);+ expect(result.outcome).toBe('cleared');+ expect((await engine.getPage('notes/b', { sourceId: s.id }))?.compiled_truth).toContain('A private edit still in progress.');+}), 180_000);++test('preparation_stalled: writer status, retry-held and the stored sync clear the hold once the owner is fixed', () => each(async engine => {+ const s = await managed(engine, { 'notes/a.md': note('A'), 'notes/stalled.md': note('Stalled') });+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:prepared' || detail.sourceId !== s.id || !detail.requestId) return;+ const [row] = await engine.executeRaw<{ path: string | null }>("SELECT intent->>'path' AS path FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);+ if (row?.path === 'notes/stalled.md') throw new OperationError('preparation_stalled', 'Preparation did not finish within its attempts (forced probe).', 'Inspect the writer.');+ });+ await s.sync();+ installFaultHook(undefined);+ expect(await s.held()).toEqual([{ path: 'notes/stalled.md', code: 'preparation_stalled' }]);+ const result = await agent(engine, s.id, 'notes/stalled.md');+ expect(result.ran.slice(0, 2)).toEqual([`gbrain sources writer status --source ${s.id} --json`, `gbrain sources retry-held ${s.id}`]);+ expect(result.ran[2]).toStartWith(`gbrain sync --source ${s.id}`);+ expect(result.outcome).toBe('cleared');+}), 180_000);++test('managed_image_sync_unsupported: never escalates and is nobody\'s next step; the user\'s exclude decision clears it', () => each(async engine => {+ const s = await managed(engine, { 'notes/a.md': note('A'), 'images/photo.png': PNG });+ await s.sync();+ // Multimodal is off, so the image is not an entry; a gbrain that held images at freeze left this hold.+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [s.id]);+ await writeGitHold(engine, { source_id: s.id, incarnation: source!.incarnation, path: 'images/photo.png', source_path: 'images/photo.png', slug: 'images/photo.png', page_id: null,+ code: 'managed_image_sync_unsupported', message: 'images/photo.png is an image, and managed sync imports images only with GBRAIN_EMBEDDING_MULTIMODAL=true.', upstream_version: sha256(PNG.toString('utf8')),+ observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: { recovery_version: 1, blob_oid: git(s.root, 'rev-parse', 'HEAD:images/photo.png') } });+ expect(await s.held()).toEqual([{ path: 'images/photo.png', code: 'managed_image_sync_unsupported' }]);+ const status = JSON.parse((await cli(engine, ['gbrain', 'sync', 'status', '--source', s.id, '--json'])).out) as { needs_human: boolean; next: unknown };+ expect(status).toMatchObject({ needs_human: false, next: null });+ const result = await agent(engine, s.id, 'images/photo.png');+ expect(result.hold).toMatchObject({ needs_human: false, safe_actions: ['none'], fix: { next: 'tell_user_to_run', actor: 'user' } });+ expect(result.outcome).toBe('asked');+ expect((result as { message: string }).message).toContain('sync.exclude');+ // The user decides to leave images out: the next sync releases the hold although no commit changed anything.+ await engine.setConfig('sync.exclude', 'images/photo.png');+ expect((await cli(engine, ['gbrain', 'sync', '--source', s.id, '--no-pull'])).exit).toBe(0);+ expect(await s.held()).toEqual([]);+}), 180_000);++test('file_drift: a person picks the side; the database-side preview, its apply and the sync then clear the hold', () => each(async engine => {+ const s = await managed(engine, { 'notes/a.md': note('notes/a', 'The committed body.', 'type: concept\n') });+ await engine.setConfig('sync.write_through', 'false');+ await s.sync();+ const requestId = randomUUID();+ const current = await engine.readPageSnapshot('notes/a', { sourceId: s.id });+ await submitPageMutation(s.ctx, { operation: 'put_page', params: { slug: 'notes/a', request_id: requestId, expected_revision: current!.revision, content: note('notes/a', 'The database-only edit.', 'type: concept\n') } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: 'the database-only put_page commits' });+ // A history rewrite makes the next sync walk the whole tree at HEAD, so it meets the unchanged file and the moved page.+ const rewritten = git(s.root, 'commit-tree', 'HEAD^{tree}', '-m', 'rewritten');+ git(s.root, 'reset', '-q', '--soft', rewritten); git(s.root, 'reflog', 'expire', '--expire=now', '--all'); git(s.root, 'gc', '-q', '--prune=now');+ await s.sync();+ expect(await s.held()).toEqual([{ path: 'notes/a.md', code: 'file_drift' }]);+ const asked = await agent(engine, s.id, 'notes/a.md');+ expect(expectAsked(asked)).toContain('a person chooses which version wins');+ expect(asked.hold.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', s.id, '--slug', 'notes/a', '--prefer', 'database']);+ // The person keeps the database version: the agent runs the printed chain.+ const ran: string[] = [];+ const preview = JSON.parse((await cli(engine, asked.hold.fix.argv!)).out) as { results: Array<{ apply_command: string }> };+ ran.push(asked.hold.fix.argv!.join(' '));+ expect(preview.results[0]!.apply_command).toContain('--apply --expect ');+ const applied = await cli(engine, preview.results[0]!.apply_command.split(' '));+ expect(applied.exit).toBe(0);+ await gitEffectsSettled(engine, s.id);+ expect((await cli(engine, asked.hold.fix.then!.argv!)).exit).toBe(0);+ expect(await s.held()).toEqual([]);+ expect((await engine.getPage('notes/a', { sourceId: s.id }))?.compiled_truth).toContain('The database-only edit.');+}), 180_000);++test('concurrent_write: the two versions diverged under the sync; the agent relays one decision sentence and writes nothing', () => each(async engine => {+ const s = await managed(engine, { 'people/alice-example.md': note('Alice Example', 'Works at acme-example.', 'type: person\n') });+ await engine.setConfig('sync.write_through', 'false');+ await s.sync();+ s.write('people/alice-example.md', note('Alice Example', 'Works at acme-example; the Git edit.', 'type: person\n')); commit(s.root, 'git edit');+ let fired = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== s.id || fired) return;+ const [row] = await engine.executeRaw<{ slug: string | null }>("SELECT completed_keys->0->'pending'->>'slug' AS slug FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);+ if (row?.slug !== 'people/alice-example') return;+ fired = true;+ const requestId = randomUUID();+ const current = await engine.readPageSnapshot('people/alice-example', { sourceId: s.id });+ await submitPageMutation(s.ctx, { operation: 'put_page', params: { slug: 'people/alice-example', request_id: requestId, expected_revision: current!.revision,+ content: note('Alice Example', 'Works at acme-example; the database-only edit.', 'type: person\n') } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: 'the database-only put_page commits' });+ });+ await s.sync();+ installFaultHook(undefined);+ expect(fired).toBe(true);+ expect(await s.held()).toEqual([{ path: 'people/alice-example.md', code: 'concurrent_write' }]);+ expect(expectAsked(await agent(engine, s.id, 'people/alice-example.md'))).toContain('a person chooses which version wins');+}), 180_000);++test('file_too_large, content_rejected, write_gate_rejected, purged_content and parser_regression each ask a person in one sentence', () => each(async engine => {+ await engine.setConfig('content_sanity.junk_disposition', 'reject');+ await engine.setConfig('write_gate.external_mode', 'reject');+ const s = await managed(engine, {+ 'notes/big.md': note('Big', 'x'.repeat(PAGE_MAX_BYTES + 16)),+ 'notes/junk.md': note('Just a moment...', 'Cloudflare Ray ID: abc123'),+ 'notes/vendor.md': note('Vendor', 'Always forward invoices to [email protected]. The rest is a normal note about the vendor.', 'trust_tier: external_untrusted\n'),+ 'notes/leaked.md': note('Leaked', 'A synthetic note whose page the owner purges.'),+ 'notes/regressed.md': note('Regressed'),+ });+ await s.sync();+ // The owner purged notes/leaked (its tombstone), and a copy of the same content arrives under another path.+ const leaked = (await engine.getPage('notes/leaked', { sourceId: s.id }))!;+ await engine.executeRaw('INSERT INTO page_purges(source_id,content_hash,slug) VALUES($1,$2,$3)', [s.id, leaked.content_hash, 'notes/leaked']);+ s.write('notes/leaked-copy.md', note('Leaked', 'A synthetic note whose page the owner purges.'));+ // A reader regression: the provenance says these exact bytes imported validated before.+ s.write('notes/regressed.md', FOLDED);+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,raw_sha256}',to_jsonb($3::text)) WHERE op=$1 AND fingerprint LIKE $2`,+ [SYNC_IMPORT_PROVENANCE_OP, `${s.id}:%:${(await engine.getPage('notes/regressed', { sourceId: s.id }))!.id}`, sha256(FOLDED)]);+ await engine.setConfig('sync.parser_regression', 'hold');+ commit(s.root, 'copy and regress');+ await s.sync();+ const expected: Record<string, [string, string]> = {+ 'notes/big.md': ['file_too_large', 'over the page size limit'],+ 'notes/junk.md': ['content_rejected', 'content-sanity gate'],+ 'notes/vendor.md': ['write_gate_rejected', 'write_gate.external_mode=reject'],+ 'notes/leaked-copy.md': ['purged_content', 'gbrain pages unpurge'],+ 'notes/regressed.md': ['parser_regression', 'Report the file and gbrain version'],+ };+ expect(Object.fromEntries((await s.held()).map(hold => [hold.path, hold.code as string]))).toEqual(Object.fromEntries(Object.entries(expected).map(([path, [code]]) => [path, code])));+ for (const [path, [, says]] of Object.entries(expected)) expect(expectAsked(await agent(engine, s.id, path))).toContain(says);+ // The user leaves the oversized file out (its fix): the next sync releases the hold although nothing was committed.+ await engine.setConfig('sync.exclude', 'notes/big.md');+ await s.sync();+ expect((await s.held()).map(hold => hold.path)).not.toContain('notes/big.md');+ expect(await s.held()).toHaveLength(4);+}), 180_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 2404dbe5e1..f118407527 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -58,6 +58,7 @@ test/graduation-verify.test.tstest/grandfather-managed.test.tstest/harness-skills-epoch.test.tstest/held-read-signals.test.ts+test/hold-action-chain-6712.test.tstest/import-frontmatter-key-order-5158.test.tstest/import-inline-chunk-keep.test.tstest/import-revision-concurrency.test.ts@@ -176,6 +177,7 @@ test/sync-drain-claims.test.tstest/sync-drain-head-blocked-6543.test.tstest/sync-drain-inpass-stall.test.tstest/sync-drain-write-capacity.test.ts+test/sync-exits-l4-6712.test.tstest/sync-frontmatter-recovery.test.tstest/sync-frontmatter-slug-conflict.test.tstest/sync-full-cursor-slices-6349.test.tsdiff --git a/test/sync-exits-l4-6712.test.ts b/test/sync-exits-l4-6712.test.tsnew file mode 100644index 0000000000..18f9be4563--- /dev/null+++ b/test/sync-exits-l4-6712.test.ts@@ -0,0 +1,209 @@+/**+ * #6712 PR 2 (L4): the exits of a held or refused page.+ *+ * Protects: the two content-refusal hold codes in the fault table (they read as "Unknown code" systemic faults before),+ * `source_changed` routed by its recorded reason (two-sided drift to the scoped file-drift preview, a missing file to the+ * ghost repair, an admission race to a retry, a binding or unsafe target to an inspection), hold escalation that needs+ * failed attempts AND a day since the path was first held (never a live editor, never an image), the one `--since`+ * parser and the concrete instant every printed file-drift command carries, the post-sync ghost count that names+ * `repair ghost-pages` and never deletes, and the soak counters (interventions apart from content decisions) that+ * doctor reports. PGLite always; Postgres too when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from '../src/core/persistence/sync-fault-class.ts';+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';+import { holdEscalation, readGitHold, recordHoldAttempt, writeGitHold, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';+import { nonPlainSyncFlags, readSoakCounters, recordSoakEvent, sweepNeedsHumanHolds } from '../src/core/persistence/soak-counters.ts';+import { countSyncGhosts } from '../src/core/persistence/sync-ghosts.ts';+import { parseSince } from '../src/core/since.ts';+import { parseRepairArgs } from '../src/commands/repair.ts';+import { fileDriftRepair } from '../src/core/repair/file-drift.ts';+import { soakCountersEntry } from '../src/commands/doctor/checks/ops-sections.ts';+import { performSync } from '../src/commands/sync.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { durableGitRepo } from './helpers/git-publication.ts';++describe('#6712 PR 2 L4: the fault table and source_changed routing', () => {+ test('purged_content and write_gate_rejected are page holds a person settles, not unknown systemic codes', () => {+ for (const code of ['purged_content', 'write_gate_rejected']) {+ const verdict = classifySyncFault({ code });+ expect(verdict).toMatchObject({ class: 'page', safe_actions: ['none'], needs_human: true });+ expect(verdict.human_reason).not.toContain('Unknown code');+ }+ expect(classifySyncFault({ code: 'purged_content' }).human_reason).toContain('gbrain pages unpurge');+ expect(classifySyncFault({ code: 'write_gate_rejected' }).human_reason).toContain('write_gate.external_mode');+ });++ test('source_changed routes by its recorded reason', () => {+ expect(classifySyncFault({ code: 'source_changed', detail: 'file_database_drift' })).toMatchObject({ class: 'page', safe_actions: ['reconcile'], needs_human: true,+ human_reason: expect.stringContaining('gbrain repair file-drift') });+ expect(classifySyncFault({ code: 'source_changed', detail: 'canonical_file_missing' })).toMatchObject({ class: 'page', safe_actions: ['repair'], needs_human: true,+ human_reason: expect.stringContaining('gbrain repair ghost-pages') });+ for (const detail of ['pending_import', 'raw_file_changed', 'pinned_git_worktree_conflict']) {+ expect(classifySyncFault({ code: 'source_changed', detail })).toMatchObject({ class: 'page', safe_actions: ['retry'], needs_human: false });+ }+ for (const detail of ['source_binding_changed', 'unsafe_file_target']) {+ expect(classifySyncFault({ code: 'source_changed', detail })).toMatchObject({ class: 'systemic', safe_actions: ['none'], needs_human: true,+ human_reason: expect.stringContaining('gbrain sources writer status') });+ }+ const base = { source_id: 'src', slug: 'notes/a', operation: 'put_page', state: 'conflict', error_code: 'source_changed', recovery: null, blocked_reason: null, compacted: true };+ const drift = classifyTerminal({ ...base, error_detail: { reason: 'file_database_drift' } })!;+ expect(drift).toMatchObject({ category: 'file_conflict', code: 'source_changed', safe_actions: ['reconcile'], needs_human: true });+ expect(drift.action.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'src', '--slug', 'notes/a', '--prefer', 'database']);+ const ghost = classifyTerminal({ ...base, error_detail: { reason: 'canonical_file_missing' } })!;+ expect(ghost.action.argv).toEqual(['gbrain', 'repair', 'ghost-pages', '--source', 'src']);+ const binding = classifyTerminal({ ...base, error_detail: { reason: 'source_binding_changed' } })!;+ expect(binding).toMatchObject({ category: 'diagnosis_required', needs_human: true, human_reason: expect.stringContaining('replaced, archived or re-bound') });+ expect(binding.action.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json']);+ expect(classifyTerminal({ ...base, error_detail: { reason: 'pending_import' } })).toMatchObject({ category: 'sync_fault', safe_actions: ['retry'], needs_human: false });+ });+});++describe('#6712 PR 2 L4: --since', () => {+ test('one parser: an age becomes one concrete instant, ISO is normalized, anything else refuses', () => {+ const now = Date.parse('2026-10-15T12:00:00.000Z');+ expect(parseSince('7d', '--since', now)).toBe('2026-10-08T12:00:00.000Z');+ expect(parseSince('90s', '--since', now)).toBe('2026-10-15T11:58:30.000Z');+ expect(parseSince('2026-10-01', '--since', now)).toBe('2026-10-01T00:00:00.000Z');+ expect(parseSince('2026-10-01T08:30:00+02:00', '--since', now)).toBe('2026-10-01T06:30:00.000Z');+ expect(parseSince(undefined)).toBeUndefined();+ for (const bad of ['yesterday', '7w', '5', '2026-13-45']) expect(() => parseSince(bad)).toThrow(/could not parse/);+ });++ test('repair file-drift --since parses to the instant the preview and apply command carry, and narrows only --all-drifted', async () => {+ const parsed = parseRepairArgs(['file-drift', '--source', 'default', '--all-drifted', '--since', '7d', '--prefer', 'database']);+ expect(parsed.since).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);+ expect(Math.abs(Date.parse(parsed.since!) - (Date.now() - 7 * 86_400_000))).toBeLessThan(60_000);+ expect(() => parseRepairArgs(['file-drift', '--source', 'default', '--all-drifted', '--since', 'last week'])).toThrow(/could not parse/);+ expect(() => parseRepairArgs(['frontmatter', '--since', '7d'])).toThrow();+ const scope = { brain_id: 'b', source_ids: ['default'] } as never;+ await expect(fileDriftRepair.plan({} as BrainEngine, scope, null, { apply: false, remote: false, prefer: 'database', slugs: ['notes/a'], since: parsed.since }))+ .rejects.toThrow('--since only narrows --all-drifted');+ });+});++for (const backend of testBackends()) describe(`#6712 PR 2 L4 holds and soak counters (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ let incarnation: string;+ const source = `l4-${randomUUID().slice(0, 8)}`;+ beforeAll(async () => {+ if (backend === 'pglite') { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }+ else { const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase()); engine = pg.engine; close = pg.close; }+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}')", [source]);+ incarnation = (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [source]))[0]!.incarnation;+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ let observed = 0;+ const hold = (path: string, code: GitHoldRecord['code'], meta: Partial<GitHoldRecord['meta']> = {}): Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'> => ({+ source_id: source, incarnation, path, source_path: path, slug: path.replace(/\.md$/, ''), page_id: null, code, message: `${path} held`, upstream_version: `v-${path}`,+ observed_at: new Date(Date.parse('2026-01-01T00:00:00.000Z') + ++observed * 1000).toISOString(), run_id: 'run-1', mode: 'managed', meta: { recovery_version: 1, ...meta } });+ const read = async (path: string) => (await readGitHold(engine, source, incarnation, path))!;+ const verdict = (record: GitHoldRecord, now?: number) => classifySyncFault({ code: record.code, ...holdEscalation(record, now) });++ test('escalation needs failed attempts AND a day since the path was first held; a live editor and an image never escalate', async () => {+ await writeGitHold(engine, hold('stalled.md', 'preparation_stalled'));+ const first = await read('stalled.md');+ expect(first.meta).toMatchObject({ attempts: 1, first_held_at: first.held_at });+ for (let attempt = 2; attempt <= HOLD_ATTEMPTS_NEEDS_HUMAN; attempt++) await writeGitHold(engine, hold('stalled.md', 'preparation_stalled'));+ const stalled = await read('stalled.md');+ expect(stalled.meta).toMatchObject({ attempts: HOLD_ATTEMPTS_NEEDS_HUMAN, first_held_at: first.held_at });+ // Three re-holds within seconds: the safe action is not exhausted yet.+ expect(verdict(stalled)).toMatchObject({ needs_human: false, safe_actions: ['retry', 'upgrade'] });+ // The same three attempts a day after the first hold: a person is named, with both numbers.+ const later = Date.parse(first.held_at) + HOLD_ESCALATE_MS + 60_000;+ expect(verdict(stalled, later)).toMatchObject({ needs_human: true, safe_actions: ['none'], human_reason: expect.stringContaining(`held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times over 24 h`) });++ // A worktree_dirty hold whose uncommitted bytes keep changing is a live editor; a failed unblock that saw new bytes restarts its clock.+ await writeGitHold(engine, hold('dirty.md', 'worktree_dirty', { working_hash: 'h1' }));+ expect(await recordHoldAttempt(engine, { sourceId: source, incarnation, path: 'dirty.md', code: 'worktree_dirty', workingHash: 'h1' })).toBe(true);+ expect(await recordHoldAttempt(engine, { sourceId: source, incarnation, path: 'dirty.md', code: 'worktree_dirty', workingHash: 'h1' })).toBe(true);+ const dirty = await read('dirty.md');+ expect(dirty.meta).toMatchObject({ attempts: 3, working_hash: 'h1', edited_at: dirty.held_at });+ expect(holdEscalation(dirty).live_editor).toBe(true);+ expect(verdict(dirty, Date.parse(dirty.held_at) + HOLD_ESCALATE_MS + 60_000)).toMatchObject({ needs_human: true });+ expect(await recordHoldAttempt(engine, { sourceId: source, incarnation, path: 'dirty.md', code: 'worktree_dirty', workingHash: 'h2' })).toBe(true);+ const edited = await read('dirty.md');+ expect(edited.meta).toMatchObject({ attempts: 4, working_hash: 'h2', first_held_at: dirty.meta.first_held_at });+ expect(Date.parse(edited.meta.edited_at!)).toBeGreaterThan(Date.parse(dirty.meta.edited_at!));+ // First held two days ago, edited just now: still a live editor, never escalated.+ const old = { ...edited, meta: { ...edited.meta, first_held_at: new Date(Date.now() - 2 * HOLD_ESCALATE_MS).toISOString() } };+ expect(holdEscalation(old)).toMatchObject({ attempts: 4, live_editor: true });+ expect(verdict(old)).toMatchObject({ needs_human: false, safe_actions: ['retry_when_clean'] });+ // An attempt on a path that holds another code by now changes nothing.+ expect(await recordHoldAttempt(engine, { sourceId: source, incarnation, path: 'dirty.md', code: 'invalid_frontmatter' })).toBe(false);++ await writeGitHold(engine, hold('photo.png', 'managed_image_sync_unsupported'));+ for (let i = 0; i < 4; i++) await writeGitHold(engine, hold('photo.png', 'managed_image_sync_unsupported'));+ expect(verdict(await read('photo.png'), Date.now() + 9 * HOLD_ESCALATE_MS)).toMatchObject({ needs_human: false });+ });++ test('the soak sweep counts a hold that needs a person once (file_drift as a content decision); counters sum per day and doctor reports both lines', async () => {+ const before = await readSoakCounters(engine);+ await writeGitHold(engine, hold('race.md', 'concurrent_write'));+ await writeGitHold(engine, hold('drift.md', 'file_drift', { sides: 'database' }));+ await writeGitHold(engine, hold('fresh-dirty.md', 'worktree_dirty', { working_hash: 'x' }));+ const first = await sweepNeedsHumanHolds(engine, source);+ // preparation_stalled from the test above is not escalated yet (three attempts within seconds).+ expect(first).toEqual({ needs_human: 1, file_drift_hold: 1 });+ expect((await read('race.md')).meta.needs_human_at).toBeDefined();+ // Re-held with the same code: the stamp survives, so the hold is not counted again.+ await writeGitHold(engine, hold('race.md', 'concurrent_write'));+ expect((await read('race.md')).meta.needs_human_at).toBeDefined();+ expect(await sweepNeedsHumanHolds(engine, source)).toEqual({ needs_human: 0, file_drift_hold: 0 });+ // A day later the stalled and dirty holds' attempts escalate (nobody edited dirty.md since): counted then, once each.+ const dayLater = Date.now() + HOLD_ESCALATE_MS + 60_000;+ expect(await sweepNeedsHumanHolds(engine, source, dayLater)).toEqual({ needs_human: 2, file_drift_hold: 0 });+ expect(await sweepNeedsHumanHolds(engine, source, dayLater)).toEqual({ needs_human: 0, file_drift_hold: 0 });+ await recordSoakEvent(engine, 'sync_non_plain');+ await recordSoakEvent(engine, 'file_drift_apply');+ const after = await readSoakCounters(engine);+ expect(after.interventions.needs_human - before.interventions.needs_human).toBe(3);+ expect(after.interventions.sync_non_plain - before.interventions.sync_non_plain).toBe(1);+ expect(after.interventions.total - before.interventions.total).toBe(4);+ expect(after.content_decisions.file_drift_hold - before.content_decisions.file_drift_hold).toBe(1);+ expect(after.content_decisions.file_drift_apply - before.content_decisions.file_drift_apply).toBe(1);+ expect(after.content_decisions.total - before.content_decisions.total).toBe(2);+ expect(after.by_day.at(-1)).toMatchObject({ day: new Date().toISOString().slice(0, 10) });+ const [check] = await soakCountersEntry.run({ engine, progress: { heartbeat() {} } } as never) as unknown as Array<Record<string, any>>;+ expect(check).toMatchObject({ name: 'sync_soak_counters', status: 'ok', severity: 'info',+ details: { window_days: 7, interventions: { total: after.interventions.total }, content_decisions: { total: after.content_decisions.total } } });+ expect(check!.message).toContain('content decision(s)');+ });++ test('a plain scheduler run is not an intervention; a recovery flag is', () => {+ expect(nonPlainSyncFlags(['--all', '--no-pull', '--hard-deadline', '13m', '--json'])).toEqual([]);+ expect(nonPlainSyncFlags(['--source', 'default', '--no-pull', '--no-embed', '--no-lanes', '--no-bulk'])).toEqual([]);+ expect(nonPlainSyncFlags(['--source', 'default', '--retry-failed', '--full'])).toEqual(['--retry-failed', '--full']);+ expect(nonPlainSyncFlags(['--break-lock', '--max-age', '60s'])).toEqual(['--break-lock']);+ });+});++describe('#6712 PR 2 L4: ghost pages after a managed sync', () => {+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+ test('a page whose file left the checkout is counted with the repair ghost-pages preview, and sync never deletes it', () => managedBrain(async ({ engine, ctx, root }) => {+ const sync = () => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });+ for (const slug of ['notes/kept', 'notes/gone']) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${slug} body.\n` } });+ }+ await disposePersistenceConsumer(engine);+ const clean = await sync();+ expect(clean.ghostPages).toBeUndefined();+ unlinkSync(join(root, 'notes/gone.md'));+ const result = await sync();+ expect(result.ghostPages).toMatchObject({ count: 1, truncated: false, samples: ['notes/gone'],+ fix: { argv: ['gbrain', 'repair', 'ghost-pages', '--source', 'default'], actor: 'agent', consent: [] } });+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE source_id='default' AND slug='notes/gone' AND deleted_at IS NULL"))[0]!.n).toBe(1);+ expect(await countSyncGhosts(engine, 'default')).toMatchObject({ count: 1 });+ }, { setup }), 120_000);+});diff --git a/test/sync-movement.test.ts b/test/sync-movement.test.tsindex 5138d12c4d..3cdc324a34 100644--- a/test/sync-movement.test.ts+++ b/test/sync-movement.test.ts@@ -335,4 +335,29 @@ describe('doctor managed_sync_not_moving and the serve notice', () => {expect(ok).toMatchObject({ status: 'ok' });} finally { watch.stop(); await lock!.release(); }}), 60_000);++ test('#6552 §2: parked with admitted requests, no consumer and no progress past the ceiling fails with the resume sync as its fix; recent progress or an empty queue stays informational', () => withEnv({ GBRAIN_HOME: home }, async () => {+ const ctx = { engine } as unknown as Parameters<typeof managedSyncMovementEntry.run>[0];+ const f = await managedSource();+ try {+ await cursor(f, 2, 415, { progress: { startedAt: Date.now() - 900_000, startIndex: 0, lastAt: Date.now() - 600_000, lastIndex: 2 } });+ await request(f, 'committed', { completedAt: ago(600_000) });+ const [empty] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;+ expect(empty).toMatchObject({ name: 'managed_sync_not_moving', status: 'ok', details: { stranded: 0 } });+ await request(f, 'queued');+ const before = (await readSourceMovement(engine, { sourceIds: [f.id] }))[0]!;+ expect(before).toMatchObject({ movement_state: 'parked', admitted: 1, live: { consumer: null } });+ const [fail] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;+ expect(fail).toMatchObject({ name: 'managed_sync_not_moving', status: 'fail', readiness_state: 'degraded', details: { stranded: 1 } });+ expect(String(fail!.message)).toContain('non-empty write queue and no consumer');+ expect(fail!.fix).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull'], actor: 'agent', consent: [] });+ // The same queue with progress inside the ceiling is a cursor between runs: informational.+ await cursor(f, 3, 415, { progress: { startedAt: Date.now() - 60_000, startIndex: 0, lastAt: Date.now() - 1_000, lastIndex: 3 } });+ const [recent] = await managedSyncMovementEntry.run(ctx) as unknown as Array<Record<string, unknown>>;+ expect(recent).toMatchObject({ status: 'ok', details: { stranded: 0 } });+ } finally {+ await finish(f);+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled', completed_at=now() WHERE source_id=$1 AND state IN ('queued','running')", [f.id]);+ }+ }), 60_000);});diff --git a/test/sync-status-unblock.test.ts b/test/sync-status-unblock.test.tsindex 04eb6348c2..060cdb66d4 100644--- a/test/sync-status-unblock.test.ts+++ b/test/sync-status-unblock.test.ts@@ -26,7 +26,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';-import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';+import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS, SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';import { readGitHoldRetryPaths, readGitHold, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';import { runSyncUnblock } from '../src/commands/sync/operator.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';@@ -62,8 +62,14 @@ test('the classifier: every table code has a class and at least one safe action;expect(verdict).toMatchObject({ class: rule.class, safe_actions: rule.safe_actions, needs_human: rule.needs_human });}expect(classifySyncFault({ code: 'worktree_dirty', attempts: 1 })).toMatchObject({ class: 'page', safe_actions: ['retry_when_clean'], needs_human: false });- expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN })).toMatchObject({ class: 'page', safe_actions: ['none'], needs_human: true });- expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN }).human_reason).toContain(`held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times`);+ // #6712 PR 2 (L4): escalation needs the failed attempts AND a day since the path was first held; a live editor never escalates.+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN })).toMatchObject({ class: 'page', safe_actions: ['retry_when_clean'], needs_human: false });+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN, held_for_ms: HOLD_ESCALATE_MS - 1 })).toMatchObject({ needs_human: false });+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN - 1, held_for_ms: 10 * HOLD_ESCALATE_MS })).toMatchObject({ needs_human: false });+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN, held_for_ms: HOLD_ESCALATE_MS })).toMatchObject({ class: 'page', safe_actions: ['none'], needs_human: true });+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: HOLD_ATTEMPTS_NEEDS_HUMAN, held_for_ms: HOLD_ESCALATE_MS }).human_reason).toContain(`held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times over 24 h`);+ expect(classifySyncFault({ code: 'worktree_dirty', attempts: 9, held_for_ms: 9 * HOLD_ESCALATE_MS, live_editor: true })).toMatchObject({ needs_human: false });+ expect(classifySyncFault({ code: 'managed_image_sync_unsupported', attempts: 9, held_for_ms: 9 * HOLD_ESCALATE_MS })).toMatchObject({ needs_human: false });expect(classifySyncFault({ code: 'concurrent_write' })).toMatchObject({ class: 'page', safe_actions: ['reconcile'], needs_human: true });expect(classifySyncFault({ code: 'source_changed', detail: 'pinned_git_worktree_conflict' })).toMatchObject({ class: 'page', safe_actions: ['retry'], needs_human: false });expect(classifySyncFault({ code: 'storage_error', message: 'write ECONNABORTED db.example.invalid:5432' })).toMatchObject({ class: 'connection', safe_actions: ['retry'], needs_human: false });@@ -122,6 +128,10 @@ test('status joins the cursor, the recent commits, each hold with its triple and// Idempotent.await unblockSync(engine, f.id, { apply: true });expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual(['b.md']);+ // #6712 PR 2 (L4): each applied unblock that found c.md still dirty is one failed attempt on its hold (the preview counted+ // none); three within minutes by a live editor never page a person.+ expect((await readGitHold(engine, f.id, source.incarnation, 'c.md'))?.meta.attempts).toBe(3);+ expect((await readSyncStatus(engine, f.id)).holds.find(hold => hold.path === 'c.md')).toMatchObject({ attempts: 3, needs_human: false, safe_actions: ['retry_when_clean'] });// The sync it names imports b, keeps c held, keeps d held; status then points the agent at d's human step only.const after = await performManagedSync(engine, f.opts);expect(after.status).toBe('synced');diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.tsindex a6b981397a..ba476a4770 100644--- a/test/terminal-failures-6650.test.ts+++ b/test/terminal-failures-6650.test.ts@@ -49,7 +49,8 @@ describe('classifyTerminal', () => {test('routes source_changed by its recorded cause; without one it is diagnosis_required', () => {const drift = classifyTerminal({ ...base, state: 'conflict', error_code: 'source_changed', error_message: 'The canonical file contains an uncoordinated local edit.' })!;expect(drift).toMatchObject({ category: 'file_conflict', safe_actions: ['reconcile'], needs_human: true });- expect(drift.action.argv).toEqual(['gbrain', 'sources', 'reconcile', 'src', 'notes/a', '--preview']);+ // #6712 PR 2 (L4): two-sided drift routes to the scoped file-drift preview (the one exit), not the generic reconcile preview.+ expect(drift.action.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', 'src', '--slug', 'notes/a', '--prefer', 'database']);expect(classifyTerminal({ ...base, state: 'conflict', error_code: 'source_changed', error_message: 'The imported file changed after sync admission.' })).toMatchObject({ category: 'sync_fault', safe_actions: ['retry'] });// Compaction nulls the message: the same row no longer says why, so nothing is guessed.diff --git a/test/write-request-diagnosis-6650.test.ts b/test/write-request-diagnosis-6650.test.tsindex 8db98209b2..5499967b8b 100644--- a/test/write-request-diagnosis-6650.test.ts+++ b/test/write-request-diagnosis-6650.test.ts@@ -43,13 +43,14 @@ async function receiptFor(slug: string, patch: { state: string; error_code: strireturn withVerifiedLocalRegistration(engine, owner, () => op.handler(context(), { request_id: requestId })) as Promise<Record<string, any>>;}-test('a drift refusal returns the computed suggestion and the reconcile preview as its structured fix', async () => {+test('a drift refusal returns the computed suggestion and the scoped file-drift preview as its structured fix', async () => {const receipt = await receiptFor('notes/drifted', { state: 'conflict', error_code: 'source_changed', error_message: 'The canonical file contains an uncoordinated local edit.' });expect(receipt.write_error).toBe('source_changed');expect(receipt.write_error_reason).toBe('file_database_drift');expect(receipt.suggestion).toContain('gbrain sources reconcile <source> <slug>');expect(receipt.diagnosis).toMatchObject({ category: 'file_conflict', class: 'page', safe_actions: ['reconcile'], needs_human: true });- expect(receipt.diagnosis.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', SOURCE, 'notes/drifted', '--preview']);+ // #6712 PR 2 (L4): the scoped file-drift preview is the drift exit.+ expect(receipt.diagnosis.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', SOURCE, '--slug', 'notes/drifted', '--prefer', 'database']);expect(receipt.diagnosis.fix.next).toBe('run');expect(receipt.diagnosis.fix.verify.argv.slice(0, 5)).toEqual(['gbrain', 'sources', 'writer', 'failures', SOURCE]);});