Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a resolved page no longer stops its managed source silently (#6858)
garrytan5dc3495812a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e43fbce190..07403739fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,29 @@ 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] - 2026-10-16++**A page that stops a managed sync no longer stops its source silently, and gbrain stops rewriting busy files just to refresh an assessment marker.** On a managed Postgres brain one page write was resolved the documented way (`gbrain repair stuck-recovery --keep disk`), and its source then indexed nothing for 21 hours (#6858). The request ended `conflict` / `source_changed` with a message no classifier knew, so the run parked `blocked_by_failures`. Every autopilot freshness sync job returned that parked run and was recorded `completed`, so nothing retried and nothing alerted. The trigger was gbrain itself: managed sync rewrote the canonical file of an oversized page only to refresh its `embed_skip` marker, whose `assessed_at` changes whenever the body does, and that rewrite was the publication an agent's own edit of the hot file collided with.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| `repair stuck-recovery --keep disk` abandons a managed sync import | the run parked `blocked_by_failures` until `sync --retry-failed` | the next plain sync retries the page after the rest of its run: it imports the kept file when it is committed, holds it `worktree_dirty` when it is an uncommitted edit, and syncs the rest of the source in the same pass |+| The `--keep disk` result for any other write | named only `sources reconcile … --preview` | names both follow-ups in order: `sources reconcile … --preview --auto-additive` (still preview-first), then `gbrain sync --source <id> --no-pull`; a sync import names the plain sync |+| An autopilot (or any) `sync` job whose managed run is blocked, stalled or capped | `completed`, with the parked result | `dead`; the error names the stop and the run's `next` command, and `jobs get` keeps `outcome`, `drain` and `next` in the job's progress |+| A managed sync run blocked on a page | `sync_failures` warned and failed only after 72 h | new doctor check `managed_sync_blocked`: warns at once and fails after an hour, with `gbrain sync status --source <id> --json` as its fix |+| get_brain_health with a source blocked over an hour | `ok` | `attention`, with a `sync_blocked` count band (no source names) |+| A managed sync import of an oversized, quarantined or flagged page | rewrote the canonical file with the gate's marker (a file publication with a recovery record, every time the body changed) | stores the marker in the database only and leaves the file as committed; a file whose marker is missing or stale is not file/database drift |++### What you need to do++Nothing. Markers already written into files stay where they are (nothing rewrites files on upgrade), and a later import of the same file no longer touches them. If your monitoring treats a dead `sync` job as an incident, that is now the intended signal: `gbrain sync status --source <id> --json` names the page and its exit. A plain `gbrain sync` retrying a failure an earlier run recorded comes with #6712 PR 3; until then the `next` command a blocked run prints may still say `--retry-failed`.++### Still open on #6858++Preparation cost that scales with the repository instead of the diff (ask 5) and a supported low-latency mode (ask 6) are tracked separately.+## [0.60.268.0] - 2026-10-16**Security: remote entity cards and context packs no longer carry open loops.** Since v0.47.0.0, an `entity` card built for a remote caller (any MCP client, stdio or HTTP) listed the open loops whose counterparty is that entity: the loop summary, its due date and its `loop_id`. Loop rows have no visibility or source grant of their own, so the card showed them even when the loop's commitment fact was private, and since v0.60.167.0 (#5504) also when the loop lives in a source outside the caller's grant, such as a connected Google source. `context_pack` and `delta` build their threads from the same card, so they carried the same loops. Remote cards now skip loop-backed threads; their fact and timeline threads are unchanged.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex e52dec1db3..a23957232b 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -40,6 +40,7 @@| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` || [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` || [The drain stopped `drain_stalled` with `cause: owner_wedged_here`](#managed-sync-not-moving) | before the ceiling: wait `retry_after_ms`, then rerun `next.command` (`safe_to_loop` is true); past it: restart the owner process the stop names (`gbrain serve`, the jobs worker or autopilot), then `gbrain sources retry-held <id>` and the same sync | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer status --source <id> --json` (the claim is gone or publishing), then `gbrain sources writer movement <id>` |+| [A managed sync run is blocked: doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health `sync_blocked` is not `none`](#managed-sync-blocked) | `gbrain sync status --source <id> --json` names the page the run stopped on, its fault class and its exit (a hold to reconcile, a repair to preview, or the resume command); `gbrain jobs get <id> --json` shows the same `next` in the dead job's progress | agent; a reconcile or repair apply after the user agrees | the step's own consent | `gbrain doctor --only managed_sync_blocked --json` is ok, and the next freshness job ends `completed` || [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` || [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` || [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |@@ -142,6 +143,8 @@ 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-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.+<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.diff --git a/llms-full.txt b/llms-full.txtindex 9142b18918..51a616242d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10584,6 +10584,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` || [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` || [The drain stopped `drain_stalled` with `cause: owner_wedged_here`](#managed-sync-not-moving) | before the ceiling: wait `retry_after_ms`, then rerun `next.command` (`safe_to_loop` is true); past it: restart the owner process the stop names (`gbrain serve`, the jobs worker or autopilot), then `gbrain sources retry-held <id>` and the same sync | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer status --source <id> --json` (the claim is gone or publishing), then `gbrain sources writer movement <id>` |+| [A managed sync run is blocked: doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health `sync_blocked` is not `none`](#managed-sync-blocked) | `gbrain sync status --source <id> --json` names the page the run stopped on, its fault class and its exit (a hold to reconcile, a repair to preview, or the resume command); `gbrain jobs get <id> --json` shows the same `next` in the dead job's progress | agent; a reconcile or repair apply after the user agrees | the step's own consent | `gbrain doctor --only managed_sync_blocked --json` is ok, and the next freshness job ends `completed` || [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` || [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` || [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |@@ -10686,6 +10687,8 @@ 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-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.+<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.diff --git a/src/commands/doctor/brain-health-bands.ts b/src/commands/doctor/brain-health-bands.tsindex 05984caf11..9f5483a6c6 100644--- a/src/commands/doctor/brain-health-bands.ts+++ b/src/commands/doctor/brain-health-bands.ts@@ -7,7 +7,8 @@** Capacity is brain-wide host state (one band for the brain and every* principal), read from the shared 60 s capacity snapshot (`cachedCapacitySnapshot`); write failures are scoped to the caller's readable sources. A- * section that could not be read is `unknown`, never a clear band. Answers are+ * section that could not be read is `unknown`, never a clear band. A source whose managed sync run stays blocked past+ * the doctor threshold (#6858) turns the status to `attention`. Answers are* cached per engine and scope for 60 s, so a polling agent costs one read a* minute.*/@@ -18,6 +19,7 @@ import { readCapacityThresholds } from '../../core/persistence/capacity-forecastimport { cachedTerminalSummary } from '../serve-http-metrics.ts';import { readEmbeddingState } from '../../core/embedding-state.ts';import { readGhostPages } from '../../core/ghost-pages.ts';+import { MANAGED_SYNC_BLOCKED_FAIL_MS, readBlockedManagedSyncs } from '../../core/persistence/sync-blocked.ts';export const BRAIN_HEALTH_TTL_MS = 60_000;export type CountBand = 'none' | '1-9' | '10-99' | '100-999' | '1000+' | 'unknown';@@ -36,6 +38,8 @@ export interface BrainHealthBands {unsearchable: { band: CountBand; lower_bound: boolean };/** Live pages whose canonical file is gone on the owner host; `reason` when not counted here (for example not_owner_host). */ghost_pages: { band: CountBand; reason?: string };+ /** #6858: sources whose managed sync run has been blocked on a page longer than the doctor `managed_sync_blocked` threshold. */+ sync_blocked: { band: CountBand };/** The read-only command an operator runs on the brain host for the full report. */host_command: string[];}@@ -55,7 +59,7 @@ export function readBrainHealthBands(engine: BrainEngine, opts: { sourceIds?: st}async function computeBands(engine: BrainEngine, sourceIds: string[] | undefined): Promise<BrainHealthBands> {- const [capacity, failures, unsearchable, ghostPages] = await Promise.all([+ const [capacity, failures, unsearchable, ghostPages, syncBlocked] = await Promise.all([Promise.all([cachedCapacitySnapshot(engine), readCapacityThresholds(engine)]).then(([snapshot, thresholds]) => snapshot.status !== 'ok'? { capacity: 'unknown' as const, days: 'unknown' as const, max_pct_band: 'unknown' as const, forecast: 'unavailable' as const }@@ -73,10 +77,14 @@ async function computeBands(engine: BrainEngine, sourceIds: string[] | undefinedreadGhostPages(engine, { sampleLimit: 0, ...(sourceIds ? { sourceIds } : {}) }).then((g): { band: CountBand; reason?: string } => g.status === 'known' ? { band: countBand(g.count) } : { band: 'unknown', ...(g.reason ? { reason: g.reason } : {}) }).catch(() => ({ band: 'unknown' as const })),+ readBlockedManagedSyncs(engine, sourceIds)+ .then((blocked): { band: CountBand } => ({ band: countBand(new Set(blocked.filter(b => Date.now() - Date.parse(b.blocked_since) > MANAGED_SYNC_BLOCKED_FAIL_MS).map(b => b.source_id)).size) }))+ .catch(() => ({ band: 'unknown' as const })),]);- const bands = { capacity: { band: capacity.capacity, days: capacity.days, max_pct_band: capacity.max_pct_band, forecast: capacity.forecast }, write_failures: failures, unsearchable, ghost_pages: ghostPages };+ const bands = { capacity: { band: capacity.capacity, days: capacity.days, max_pct_band: capacity.max_pct_band, forecast: capacity.forecast }, write_failures: failures, unsearchable, ghost_pages: ghostPages,+ sync_blocked: syncBlocked };const unknown = bands.capacity.band === 'unknown' || failures.band === 'unknown';const attention = bands.capacity.band === 'low' || bands.capacity.band === 'critical' || (failures.active_blockers !== 'none' && failures.active_blockers !== 'unknown')- || (ghostPages.band !== 'none' && ghostPages.band !== 'unknown');+ || (ghostPages.band !== 'none' && ghostPages.band !== 'unknown') || (syncBlocked.band !== 'none' && syncBlocked.band !== 'unknown');return { schema_version: 1, status: attention ? 'attention' : unknown ? 'unknown' : 'ok', ...bands, host_command: ['gbrain', 'doctor', '--tier', 'ops', '--json'] };}diff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.tsnew file mode 100644index 0000000000..2307e3da3b--- /dev/null+++ b/src/commands/doctor/checks/managed-sync-blocked.ts@@ -0,0 +1,42 @@+/**+ * managed_sync_blocked (#6858 ask 3): a source whose managed sync run stopped on a recorded failure (or a page receipt+ * that did not commit) and has stayed stopped for longer than `MANAGED_SYNC_BLOCKED_FAIL_MS` fails the check. The run+ * resumes nothing by itself while it is blocked, so the source stops indexing even though every freshness sync job and+ * the other sources look healthy (#6858: one source stopped 21 h while every job reported `completed`). A run blocked+ * for less than the threshold warns. Reads the durable cursor and failure rows only; names sources, codes and ages, never+ * paths or receipt text.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';+import { MANAGED_SYNC_BLOCKED_FAIL_MS, readBlockedManagedSyncs } from '../../../core/persistence/sync-blocked.ts';+import { agentFix, checkError } from '../check-fix.ts';++const DOCS = 'docs/guides/troubleshooting.md#managed-sync-blocked';++async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const blocked = await readBlockedManagedSyncs(connectedEngine(ctx), doctorSourceIds(ctx));+ if (!blocked.length) {+ checks.push({ name: 'managed_sync_blocked', status: 'ok', message: 'No managed sync run is blocked.' });+ return checks;+ }+ const now = Date.now();+ const over = blocked.filter(b => now - Date.parse(b.blocked_since) > MANAGED_SYNC_BLOCKED_FAIL_MS);+ const first = over[0] ?? blocked[0]!;+ const minutes = (since: string) => Math.max(0, Math.floor((now - Date.parse(since)) / 60_000));+ const list = blocked.map(b => `${b.source_id} (${b.code}, blocked ${minutes(b.blocked_since)} min)`).join('; ');+ checks.push({ name: 'managed_sync_blocked', status: over.length ? 'fail' : 'warn', readiness_state: 'degraded',+ details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },+ message: `${list}: the managed sync run is stopped on a page that did not commit, so the source indexes nothing new until it is cleared`+ + `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}. Freshness sync jobs for the source end dead with the run's next step instead of completed.`,+ fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],+ 'Read-only: names the page the run stopped on, its fault class and the next step (a hold to reconcile, a repair to preview, or the resume command).',+ 'managed_sync_blocked', { docs: DOCS }) });+ } catch (error) {+ checks.push(checkError('managed_sync_blocked', 'read blocked managed sync runs', error, { details: { health: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const managedSyncBlockedEntry: DoctorEntry = { name: 'managed_sync_blocked', emits: ['managed_sync_blocked'], run: runManagedSyncBlockedCheck };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex e0aafeab7f..75cf57568b 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -119,6 +119,7 @@ import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';+import { managedSyncBlockedEntry } from './checks/managed-sync-blocked.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';import {@@ -165,6 +166,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [persistenceCapacityEntry,terminalFailuresEntry,managedSyncMovementEntry,+ managedSyncBlockedEntry,persistenceCompactionEntry,soakCountersEntry,serveBuildDriftEntry,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 65e65498fe..0aa9c61743 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -724,6 +724,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.267.0', text: '`purge_fact` now saves each page it rewrites as a version before dropping the purged fence row, and its version redaction then removes the claim from that version as from every other, so `get_versions` and `gbrain history` list one more snapshot per page a fact purge rewrites. The snapshot holds the page as it stood before the purge, without the purged claim.' },// Remote open-loop hotfix (GBRA-120).{ since: '0.60.268.0', text: 'Remote callers (every MCP transport) no longer get open-loop-backed threads on `entity` cards, or in `context_pack` and `delta`, which build on those cards: no loop summary, `due` or `loop_id`. Use `open_loops`, which reads loops only in granted sources. The trusted local CLI still sees them on `gbrain entity`, and in `context_pack` / `delta` with `include_private`. Remote `open_loops` grouped results no longer rank counterparties by backlink counts.' },+ // #6858 (GBRA-121; Garry: "take care of fixing" #6858 asks 1-4). `since` is a placeholder equal to the branch's VERSION; the integrator sets it to the merge-slot stamp by hand.+ { since: '0.60.268.0', text: 'A durable `sync` job (autopilot freshness included) whose managed run stops on something only a person clears (a run blocked on a page, a stalled drain holder, a write cap) now ends `dead` instead of `completed`: its error names the stop and the run\'s `next` command, and `gbrain jobs get <id> --json` keeps `outcome`, `drain` and `next` in the job\'s progress. New doctor check `managed_sync_blocked` warns as soon as a source\'s run is blocked and fails after an hour (fix: `gbrain sync status --source <id> --json`), and `get_brain_health` gains a `sync_blocked` count band that turns its status to `attention` past the same hour.' },+ { since: '0.60.268.0', text: 'A managed sync import whose stuck publication `gbrain repair stuck-recovery --keep disk` abandoned is retried by the next plain sync after the rest of its run (imported when the kept file is committed, held `worktree_dirty` when it is an uncommitted edit) instead of parking the run `blocked_by_failures`; the `--keep disk` result now names both follow-ups (`sources reconcile … --preview --auto-additive`, then `gbrain sync --source <id> --no-pull`), or the plain sync for a sync import.' },+ { since: '0.60.268.0', text: 'Managed sync no longer rewrites a canonical file only to add or refresh the content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`): they are stored in the database and the file stays as committed, so an oversized page agents keep appending to is no longer republished on every import. A file whose marker is missing or carries another `assessed_at` is not file/database drift. Markers already in files are left alone.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 83ffa4ae98..047e526a48 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -74,11 +74,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],+ 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 148417c6c5..9e486f5988 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -289,6 +289,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['stale_frontmatter_keys','maintenance_write_drift','managed_sync_not_moving',+ // #6858: a managed sync run stopped on a page that did not commit, failed past an hour (doctor/checks/managed-sync-blocked.ts).+ 'managed_sync_blocked','persistence_session_timeouts',// #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).'two_consumers_on_host',diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.tsindex 07a93dfcdd..9e38a28f95 100644--- a/src/core/minions/handlers/sync.ts+++ b/src/core/minions/handlers/sync.ts@@ -4,6 +4,8 @@import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import { resolveJobPull } from './job-pull.ts';+import { UnrecoverableError } from '../errors.ts';+import type { SyncResult } from '../../../commands/sync.ts';export function makeSyncHandler(engine: BrainEngine): MinionHandler {return async (job) => {@@ -188,6 +190,14 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {await progress.flush();const drained = await settleJobDrain(engine, job, result, sourceId ?? 'default', plan);+ // #6858: a drain stopped on something only a person clears (a blocked run, a stalled holder, a cap) does not end `completed`:+ // the job ends dead with the run's next step, and its progress keeps the drain fields `jobs get` would otherwise have shown.+ if (drained.incomplete === true && (await import('../../persistence/sync-drain.ts')).jobDisposition(result, sourceId ?? 'default') === 'needs_operator') {+ const { outcome, drain, next } = drained as { outcome?: string; drain?: SyncResult['drain']; next?: { command?: string; why?: string } };+ await job.updateProgress({ blocked: true, outcome, drain, next }).catch(() => undefined);+ throw new UnrecoverableError(`Managed sync of source ${sourceId ?? 'default'} is ${result.status === 'blocked_by_failures' ? 'blocked' : 'stopped'}`+ + ` (${drain?.stop_reason ?? result.status}${drain?.remaining != null ? `, ${drain.remaining} entries left` : ''}). ${next?.why ?? ''}${next?.command ? ` Next: ${next.command}` : ''}`.trim());+ }return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };};}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 14f66fdabc..207eb187e0 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -67,6 +67,7 @@ import { fenceWhere } from '../fence-repair/refusal.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';import { fenceRepairCommit } from './effect-model.ts';+import { withoutSafetyAssessments } from './reconcile-safety.ts';import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } from './page-purge.ts';import { withTrustKeep } from './context.ts';import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';@@ -164,7 +165,7 @@ export function readCanonicalAsImported(bytes: string, sourcePath: string): { co*/export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytes: string, snapshot: PageSnapshot,sourcePath: string | (() => Promise<string>), activePack?: ParseOpts['activePack']): Promise<boolean> {- const expected = digest(canonical(snapshot.page, snapshot.tags));+ const expected = digest(canonical({ ...snapshot.page, frontmatter: withoutSafetyAssessments(snapshot.page.frontmatter ?? {}) }, snapshot.tags));const matches = async (content: string, inferred: boolean) => {const parsed = parseMarkdown(content, slug, { activePack });// #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file@@ -180,7 +181,7 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytconst type = parsed.typeExplicit && !inferred ? parsed.type : snapshot.page.type;// Withdrawal overlays intentionally precede physical mirroring. The ledger// is applied by the import preparation and cannot be undone by this check.- const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),+ const actual = canonical({ ...parsed, frontmatter: withoutSafetyAssessments(parsed.frontmatter), type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals, { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges }) }, parsed.tags);return digest(actual) === expected;};diff --git a/src/core/persistence/reconcile-safety.ts b/src/core/persistence/reconcile-safety.tsindex 8fa2f6e562..a5212c3153 100644--- a/src/core/persistence/reconcile-safety.ts+++ b/src/core/persistence/reconcile-safety.ts@@ -12,3 +12,10 @@ export function stabilizeSafetyAssessments(frontmatter: Record<string, unknown>,else if (assessmentAt) frontmatter[key] = { ...marker, assessed_at: assessmentAt };}}++/** The gate's own assessments (re-derived from the bytes on every import) are database state, never a reason to rewrite or refuse a canonical file. */+export function withoutSafetyAssessments(frontmatter: Record<string, unknown>): Record<string, unknown> {+ const rest = { ...frontmatter };+ for (const key of RECONCILE_SAFETY_KEYS) delete rest[key];+ return rest;+}diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.tsindex 1e28feb2c0..5617be38d2 100644--- a/src/core/persistence/recovery-resolve.ts+++ b/src/core/persistence/recovery-resolve.ts@@ -56,6 +56,7 @@ import { withFilesystemPublication } from './filesystem-guard.ts';import { readHeadBlockers } from './head-blocker.ts';import { previewChangedError } from './preview-approval.ts';import { faultPoint } from './fault-points.ts';+import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';export const RESOLUTION_OP = 'stuck-recovery-resolution';export type KeepChoice = 'prior' | 'disk';@@ -299,7 +300,7 @@ export async function readResolutions(engine: BrainEngine, previewHash: string):async function abandonWrite(engine: BrainEngine, row: WriteRequest, previewHash: string): Promise<void> {if (!row.error_code) {await engine.transaction(tx => completeWrite(tx, row, 'conflict', {}, { code: 'source_changed',- message: `Publication abandoned by gbrain repair stuck-recovery --keep disk (preview ${previewHash.slice(0, 12)}): the canonical file was kept as edited on disk.` }));+ message: `${KEEP_DISK_ABANDONED_PREFIX} (preview ${previewHash.slice(0, 12)}): the canonical file was kept as edited on disk.` }));return;}const recorded = new OperationError(row.error_code, row.error_message ?? 'Publication failed before database completion.',@@ -312,8 +313,16 @@ const sameIdentity = (row: WriteRequest | null, item: StuckRecovery) => !!row?.r&& digest(identityOf(recoveryFiles(row.recovery), row.recovery)) === digest(item.identity);function nextStep(item: StuckRecovery, keep: KeepChoice, state: string): string {+ const sync = `gbrain sync --source ${item.source_id} --no-pull`;+ // #6858: a managed sync import is the next sync's to finish: it retries the page after the manifest end (sync-page-fault.ts fileChangedAfterAdmission).+ if (keep === 'disk' && item.operation === 'submit_job') return `The bytes on disk are kept and the sync import's publication was abandoned (request ${state}). This command does not mark the page repaired. `+ + `Next: ${sync}. That sync retries ${item.slug} after the rest of its run and imports the kept file when it is committed at the run's target; an uncommitted edit is held (worktree_dirty) and the rest of the source syncs. `+ + `If a hold remains, gbrain sync status --source ${item.source_id} --json names it and its exit (commit the file, or gbrain sources reconcile ${item.source_id} ${item.slug} --brain host --preview).`;if (keep === 'disk') return `The bytes on disk are kept and the write's publication was abandoned (request ${state}); the database page still holds the content before the write, `- + `so the page shows as file/database drift until it is reconciled. Next: gbrain sources reconcile ${item.source_id} ${item.slug} --brain host --preview. This command does not mark the page repaired.`;+ + 'so the page shows as file/database drift until it is reconciled. This command does not mark the page repaired. Next, in order: '+ + `1) gbrain sources reconcile ${item.source_id} ${item.slug} --brain host --preview --auto-additive (writes nothing; when the file only adds to the page it fills the decisions in, `+ + 'and you apply the written preview with --from after the user agrees; anything else lists the decisions a person makes); '+ + `2) ${sync}, so a sync run that waits on this source resumes.`;return state === 'queued' ? 'The prior bytes are back on disk and the write was requeued: the resident writer publishes it again on its next pass.': `The prior bytes are back on disk and the write ended ${state}; read its receipt with gbrain write-request -- ${item.request_id}.`;}diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.tsnew file mode 100644index 0000000000..30ac3d5dd5--- /dev/null+++ b/src/core/persistence/sync-blocked.ts@@ -0,0 +1,22 @@+/**+ * #6858 ask 3: the managed sync runs that are stopped, not draining. An unfinished cursor whose stop is recorded (a+ * `managed-sync-failure` row under its key) or whose pending page receipt ended without committing resumes nothing by+ * itself; doctor `managed_sync_blocked` and get_brain_health read it. An unfinished cursor waiting on a queued or+ * running request (`sync_incomplete`) is draining and not listed, and a failure whose cursor is gone is an orphan+ * (`gbrain repair managed-sync-orphans`), not a blocked run.+ */+import type { BrainEngine } from '../engine.ts';+import { readManagedSyncFailures } from './sync-failures.ts';++/** A run blocked longer than this fails doctor `managed_sync_blocked` and turns get_brain_health to `attention`. */+export const MANAGED_SYNC_BLOCKED_FAIL_MS = 60 * 60_000;++export interface BlockedManagedSync { source_id: string; code: string; run_id: string; blocked_since: string }++export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: string[]): Promise<BlockedManagedSync[]> {+ const cursors = new Set((await engine.executeRaw<{ fingerprint: string }>(+ "SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'")).map(row => row.fingerprint));+ return (await readManagedSyncFailures(engine, sourceIds))+ .filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key))+ .map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen }));+}diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.tsindex 23a3888e59..1e1525302f 100644--- a/src/core/persistence/sync-page-fault.ts+++ b/src/core/persistence/sync-page-fault.ts@@ -38,6 +38,7 @@ import type { SyncIntent } from './sync-prepare.ts';import type { HeldEntry } from './sync-screen.ts';import type { GitHoldMeta, GitHoldRecord } from './sync-holds.ts';import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';+import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';export { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';@@ -210,10 +211,14 @@ export function pinnedWorktreeConflict(done: Pick<WriteRequest, 'state' | 'error&& ['Newer working-tree bytes and the current page disagree with this pinned Git import.', 'Newer code file bytes disagree with the pinned import.', CANONICAL_WRITEBACK_CONFLICT].includes(done.error_message ?? '');}-/** The receipt of an import whose file bytes changed between admission and publication (`raw_file_changed` in verb-errors.ts). */+/**+ * The receipt of an import whose file bytes changed between admission and publication (`raw_file_changed` in verb-errors.ts),+ * or (#6858) whose stuck publication `gbrain repair stuck-recovery --keep disk` abandoned, keeping the file as edited on disk.+ */export function fileChangedAfterAdmission(done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message'>): boolean {return done.state !== 'committed' && done.error_code === 'source_changed'- && ['The imported file changed after sync admission.', 'The canonical file changed after preparation.', 'The canonical file changed during preparation.'].includes(done.error_message ?? '');+ && (['The imported file changed after sync admission.', 'The canonical file changed after preparation.', 'The canonical file changed during preparation.'].includes(done.error_message ?? '')+ || (done.error_message ?? '').startsWith(KEEP_DISK_ABANDONED_PREFIX));}/** A `revision_conflict` receipt whose page really moved (its live revision differs from the frozen one); run-level conflicts stay blocking. */diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 5d44020e93..5906c88537 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -26,6 +26,7 @@ import { abortSegmentedStaging, materializedSnapshot, sealSegmentedPage } from 'import { fenceBody, withoutBody } from '../page-body/page-shape.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';+import { withoutSafetyAssessments } from './reconcile-safety.ts';import { digest, sha256 } from './digest.ts';import { preserveProtectedTakes } from './protected-takes.ts';import { getWorktreeBinding } from './ownership.ts';@@ -693,7 +694,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst renderedPage = { ...(base ? withoutBody(base.page) : { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;const canonical = (page: Pick<typeof parsed, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) => ({ type: page.type, title: page.title, body: page.compiled_truth,- timeline: page.timeline ?? '', frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() });+ timeline: page.timeline ?? '', frontmatter: withoutSafetyAssessments(page.frontmatter), tags: [...new Set(tags)].sort() });// A move re-infers an implicit type from the new location, as a fresh import there would.const renamedType = renamed && parsedInput.typeExplicit !== true ? parsedInput.type : undefined;const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical({ ...ready.parsedPage, type: renamedType ?? ready.parsedPage.type }, tags));diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 4edd52a196..4f3af7446f 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -21,6 +21,8 @@ export function frontmatterSlugConflictMessage(path: string, found: string, expeconst HELD_FILE = /^(?:The canonical file is held by sync|A file held by sync) \(([a-z_]+)\) (and differs from the page|occupies the canonical page path); the page is read-only for put_page until the file is repaired\.$/;/** #6693: the refusal of a page write whose file holds a committed Git change sync has not imported yet (pending-import.ts). */+/** #6858: the receipt prefix of a write `gbrain repair stuck-recovery --keep disk` abandoned: its canonical file was kept as edited on disk. */+export const KEEP_DISK_ABANDONED_PREFIX = 'Publication abandoned by gbrain repair stuck-recovery --keep disk';export const PENDING_IMPORT_MESSAGE = 'The canonical file holds a committed Git change that sync has not imported yet.';export function heldFileMessage(kind: 'drift' | 'occupied', code: string): string {@@ -65,7 +67,7 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {suggestion: 'Inspect the exact working-tree bytes and pinned Git version, including CRLF/LF differences. Preserve local edits; do not normalize or discard them automatically. If the file and database disagree, preview gbrain sources reconcile <source> <slug> --brain <brain> --preview on the source host.',};if (['The imported file changed after sync admission.', 'The canonical file changed after preparation.',- 'The canonical file changed during preparation.'].includes(message ?? '')) return {+ 'The canonical file changed during preparation.'].includes(message ?? '') || (message ?? '').startsWith(KEEP_DISK_ABANDONED_PREFIX)) return {reason: 'raw_file_changed', message: 'The source file bytes changed after this request was accepted.',suggestion: 'Review the changed file before starting a corrected attempt. Exact byte checks remain required even when Git reports a clean file.',};diff --git a/src/core/repair/stuck-recovery.ts b/src/core/repair/stuck-recovery.tsindex 8a3713f21b..0c7dc1ae30 100644--- a/src/core/repair/stuck-recovery.ts+++ b/src/core/repair/stuck-recovery.ts@@ -20,7 +20,7 @@ const CHOICE_TEXT: Record<KeepChoice, string> = {prior: 'discard the edit: write the recorded prior bytes back (unlink the file when the prior was a create); the owner then finishes the recovery by its own rule, '+ 'so a request with no recorded failure is requeued and its write publishes again, and one with a failure ends with it',disk: 'keep the edit and abandon the write: the request ends conflict (source_changed), or with the failure it already recorded, and its recovery record is '- + 'cleared; the database page keeps the content before the write, so reconcile the page afterwards',+ + 'cleared; the database page keeps the content before the write, so reconcile the page afterwards (a managed sync import is retried by the next sync instead)',};function item(recovery: StuckRecovery, index: number, hash: string, keep: KeepChoice): RecoveryItem {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 92472188c0..db59d84b64 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -631,6 +631,13 @@"name": "managed_sync_not_moving","status": "ok"},+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "No managed sync run is blocked.",+ "name": "managed_sync_blocked",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 9677738d65..bc7a7ae5ec 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -634,6 +634,13 @@"name": "managed_sync_not_moving","status": "ok"},+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "No managed sync run is blocked.",+ "name": "managed_sync_blocked",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 4f1243add9..d1efba3d5d 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -628,6 +628,13 @@"name": "managed_sync_not_moving","status": "ok"},+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "No managed sync run is blocked.",+ "name": "managed_sync_blocked",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex a354504bb6..9a28d5b82a 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -265,6 +265,10 @@"category": "ops","name": "managed_sync_not_moving"},+ {+ "category": "ops",+ "name": "managed_sync_blocked"+ },{"category": "ops","name": "persistence_compaction"diff --git a/test/managed-sync-blocked-job-6858.test.ts b/test/managed-sync-blocked-job-6858.test.tsnew file mode 100644index 0000000000..e29e41c8eb--- /dev/null+++ b/test/managed-sync-blocked-job-6858.test.ts@@ -0,0 +1,116 @@+/**+ * #6858 ask 3: a managed sync run stopped on a page that did not commit is no longer invisible. On master every autopilot+ * freshness sync job returned the parked run and ended `completed` (one source stopped 21 h with every job green). Now+ * the job ends dead with the run's next step in its error and progress, doctor `managed_sync_blocked` warns at once and+ * fails past an hour, and get_brain_health turns to `attention` with a `sync_blocked` band. Synthetic content only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { UnrecoverableError } from '../src/core/minions/errors.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 { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';+import { managedSyncBlockedEntry } from '../src/commands/doctor/checks/managed-sync-blocked.ts';+import { readBrainHealthBands } from '../src/commands/doctor/brain-health-bands.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-6858-blocked-'));+const engines: BrainEngine[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string, message: string): string { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); }+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+// A pinned import whose canonical correction (a fixable facts fence) must rewrite a file that holds newer uncommitted bytes.+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const fixable = (body: string) => `---\ntitle: Fixable\n---\n${body}\n\n${FB}\n${FH}\n| 1 | Sentinelzq8 partners with an example vendor | partnership | 1.0 | private | medium | 2026-01-01 | | chat | |\n${FBE}\n`;++function job(id: number, data: Record<string, unknown>, progress: unknown[]): MinionJobContext {+ return { id, name: 'sync', data, attempts_made: 0, signal: new AbortController().signal, shutdownSignal: new AbortController().signal, deadlineAtMs: Date.now() + 120_000,+ updateProgress: async (p: unknown) => { progress.push(p); }, updateTokens: async () => undefined, log: async () => undefined,+ isActive: async () => true, readInbox: async () => [] } as unknown as MinionJobContext;+}++/** A managed source whose next sync stops blocked_by_failures (the old hold policy, sync.holds=fail, keeps the refusal a run failure). */+async function blockedSource(engine: BrainEngine) {+ const id = `blocked-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);+ const root = join(home, id); mkdirSync(join(root, 'people'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, 'a.md'), note('Alpha one.'));+ commit(root, 'one');+ 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');+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');+ writeFileSync(join(root, 'a.md'), note('Alpha two.')); writeFileSync(join(root, 'people/fixable.md'), fixable('A synthetic page.'));+ commit(root, 'two');+ writeFileSync(join(root, 'people/fixable.md'), fixable('A synthetic page, edited while the catch-up drained.'));+ return { id, root };+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'");+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('#6858: a freshness sync job whose managed run is blocked ends dead with the next step; doctor and get_brain_health go red past the threshold', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ let nth = 0;+ for (const engine of engines) {+ const s = await blockedSource(engine);+ const ctx = { engine } as unknown as DoctorContext;+ const check = async () => (await managedSyncBlockedEntry.run(ctx)) as Check[];+ expect(await check()).toEqual([expect.objectContaining({ name: 'managed_sync_blocked', status: 'ok' })]);+ await engine.setConfig('sync.holds', 'fail');+ const progress: unknown[] = [];+ let thrown: unknown;+ try {+ await makeSyncHandler(engine)(job(920_001 + nth, { sourceId: s.id, repoPath: s.root, pull: false, auto_embed_backfill: false, embed_reason: 'autopilot_freshness' }, progress));+ } catch (error) { thrown = error; } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }+ // Before #6858 the handler returned the parked run (status blocked_by_failures) and the worker recorded the job completed.+ expect(thrown).toBeInstanceOf(UnrecoverableError);+ expect((thrown as Error).message).toContain(`Managed sync of source ${s.id} is blocked`);+ expect((thrown as Error).message).toContain('Next: gbrain sync');+ expect(progress.at(-1)).toMatchObject({ blocked: true, outcome: 'blocked', next: { safe_to_loop: false } });++ const blocked = await readBlockedManagedSyncs(engine, [s.id]);+ expect(blocked).toEqual([expect.objectContaining({ source_id: s.id, code: 'source_changed' })]);+ const [warned] = await check();+ expect(warned).toMatchObject({ name: 'managed_sync_blocked', status: 'warn', fix: { argv: ['gbrain', 'sync', 'status', '--source', s.id, '--json'] } });+ expect(warned!.message).not.toContain('fixable.md');+ const fresh = await readBrainHealthBands(engine, { sourceIds: [s.id] }, Date.now() + 1_000_000 + nth);+ expect(fresh.sync_blocked.band).toBe('none');++ // Blocked for two hours: the check fails and the remote health bands ask for attention.+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,first_seen}',to_jsonb((now() - interval '2 hours')::text))+ WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1`, [s.id]);+ const [failed] = await check();+ expect(failed).toMatchObject({ name: 'managed_sync_blocked', status: 'fail' });+ expect(failed!.message).toContain(`${s.id} (source_changed, blocked 1`);+ const stale = await readBrainHealthBands(engine, { sourceIds: [s.id] }, Date.now() + 2_000_000 + nth);+ expect(stale).toMatchObject({ status: 'attention', sync_blocked: { band: '1-9' } });+ nth++;+ await disposePersistenceConsumer(engine);+ }+}), 240_000);diff --git a/test/managed-sync-gate-markers-6858.test.ts b/test/managed-sync-gate-markers-6858.test.tsnew file mode 100644index 0000000000..0b2a191025--- /dev/null+++ b/test/managed-sync-gate-markers-6858.test.ts@@ -0,0 +1,89 @@+/**+ * #6858 ask 4: gbrain's own oversized-page screen must not rewrite a canonical file just to stamp its assessment.+ * The gate's markers (`embed_skip`, `content_flag`, `quarantine`) are re-derived from the bytes on every import and+ * `assessed_at` changes whenever the body does, so on master every managed sync import of an oversized page that agents+ * append to became a canonical writeback: a file publication with a recovery record, the window an agent's own edit of+ * the same hot file collides with (`unexpected_file_bytes`, the source's writer lane halted). The markers are database+ * state now: the import leaves the file as committed, and a file whose marker is missing or stale is not file/database+ * drift. Synthetic content only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.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 { fileMatchesSnapshot } from '../src/core/persistence/page-prepare.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-6858-markers-'));+const engines: BrainEngine[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const line = 'An example observation appended by an agent to a busy page.\n';+const page = (n: number) => '---\ntitle: Hot Example\ntype: person\n---\n\n' + line.repeat(n);+const SLUG = 'people/hot-example';++async function managedSource(engine: BrainEngine) {+ const id = `markers-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);+ const root = join(home, id); mkdirSync(join(root, 'people'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, 'people/hot-example.md'), page(60));+ 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');+ return { id, root, file: join(root, 'people/hot-example.md'), opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+}+const fileRecoveries = (engine: BrainEngine, id: string) => engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND publication_started", [id, SLUG]).then(rows => rows[0]!.n);++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+ for (const engine of engines) await engine.setConfig('content_sanity.bytes_block', '2000');+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('#6858: a managed sync of an oversized page stores embed_skip in the database and never rewrites the canonical file for it', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const s = await managedSource(engine);+ const committed = readFileSync(s.file, 'utf8');+ expect((await performManagedSync(engine, s.opts)).status).toBe('first_sync');+ expect(readFileSync(s.file, 'utf8')).toBe(committed);+ expect(git(s.root, 'status', '--porcelain')).toBe('');+ const first = (await engine.readPageSnapshot(SLUG, { sourceId: s.id }))!;+ expect((first.page.frontmatter as Record<string, { reason?: string }>).embed_skip?.reason).toBe('oversized');+ expect(await fileRecoveries(engine, s.id)).toBe(0);+ // An agent appends to the hot page and commits: the import re-assesses it (new bytes, new assessed_at) with no file publication.+ writeFileSync(s.file, committed + line); const appended = readFileSync(s.file, 'utf8');+ commit(s.root, 'agent append');+ expect((await performManagedSync(engine, s.opts)).status).toBe('synced');+ expect(readFileSync(s.file, 'utf8')).toBe(appended);+ expect(git(s.root, 'status', '--porcelain')).toBe('');+ expect(await fileRecoveries(engine, s.id)).toBe(0);+ const second = (await engine.readPageSnapshot(SLUG, { sourceId: s.id }))!;+ expect(second.page.compiled_truth.split(line.trim()).length - 1).toBe(61);+ expect((second.page.frontmatter as Record<string, { reason?: string }>).embed_skip?.reason).toBe('oversized');+ // A file that carries no marker, or one with another assessed_at, still matches its page: neither is file/database drift.+ expect(await fileMatchesSnapshot(engine, SLUG, appended, second, 'people/hot-example.md')).toBe(true);+ const stale = appended.replace('type: person\n', "type: person\nembed_skip:\n reason: oversized\n bytes: 1\n assessed_at: '2026-10-15T21:27:12.000Z'\n");+ expect(await fileMatchesSnapshot(engine, SLUG, stale, second, 'people/hot-example.md')).toBe(true);+ expect(await fileMatchesSnapshot(engine, SLUG, appended + 'A real edit.\n', second, 'people/hot-example.md')).toBe(false);+ }+}), 240_000);diff --git a/test/managed-sync-keep-disk-6858.test.ts b/test/managed-sync-keep-disk-6858.test.tsnew file mode 100644index 0000000000..d1bfb6b1a8--- /dev/null+++ b/test/managed-sync-keep-disk-6858.test.ts@@ -0,0 +1,138 @@+/**+ * #6858 ask 1: a managed sync import whose publication recovery parked on `unexpected_file_bytes` (a marker stamped into+ * its canonical file while the publication was in flight, then the connection dropped, so the recovery recorded no+ * failure), resolved the documented way (`gbrain repair stuck-recovery --keep disk`). The request then ends+ * `conflict` / `source_changed` with the abandonment message, which no classifier knew: the run parked+ * `blocked_by_failures` and every later plain sync returned the same parked run. The abandoned page is a changed-file+ * page fault now: it is retried after the manifest end in the same pass, imported when the disk bytes are HEAD's+ * (the lossless case), held `worktree_dirty` when they are an uncommitted edit, and the rest of the source drains.+ * Synthetic content only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { fileChangedAfterAdmission } from '../src/core/persistence/sync-page-fault.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { withEnv } from './helpers/with-env.ts';+import { stuckRecoveryFixture } from './helpers/stuck-recovery-fixture.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-keep-disk-6858-'));+const engines: BrainEngine[] = [];+const roots: string[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string, message = 'synthetic content'): string { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); }+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+// A pinned import whose canonical correction (a fixable facts fence: `partnership` maps to `fact`) rewrites the file, so its publication carries a recovery record.+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const fixable = (body: string, marker = '') => `---\ntitle: Fixable\n${marker}---\n${body}\n\n${FB}\n${FH}\n| 1 | Sentinelzq8 partners with an example vendor | partnership | 1.0 | private | medium | 2026-01-01 | | chat | |\n${FBE}\n`;+const STAMP = 'embed_skip:\n reason: oversized\n assessed_at: 2026-10-15T21:27:12.000Z\n';++async function fixture(engine: BrainEngine, files: Record<string, string>) {+ const id = `keepdisk-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) writeFileSync(join(root, path), body);+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, noBulk: true } };+}++/** Version two of a, b (the correctable page) and c; b's publication is stamped mid-flight and its connection drops, then --keep disk resolves it. */+async function abandonedMidRun(engine: BrainEngine, stamped: (root: string) => void) {+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': fixable('Beta one.'), 'c.md': note('Gamma one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), fixable('Beta two.')); writeFileSync(join(f.root, 'c.md'), note('Gamma two.'));+ const pin = commit(f.root, 'version two');+ let fired = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'publication:prepared' || detail.sourceId !== f.id || fired) return;+ const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id=$1', [detail.requestId]);+ if (row?.slug !== 'b') return;+ fired = true;+ writeFileSync(join(f.root, 'b.md'), fixable('Beta two.', STAMP));+ throw Object.assign(new Error('write ECONNRESET'), { code: 'ECONNRESET' });+ });+ let first;+ try { first = await performManagedSync(engine, f.opts); } finally { installFaultHook(undefined); }+ expect(fired).toBe(true);+ expect(first).toMatchObject({ status: 'partial', managedWrite: { slug: 'b', reason: 'unexpected_file_bytes' } });+ stamped(f.root);+ const fx = stuckRecoveryFixture(engine, roots);+ const preview = await fx.repair(f.id);+ expect(preview.affected).toBe(1);+ const applied = await fx.repair(f.id, { apply: true, expect: preview.preview_hash, keep: 'disk' });+ expect(applied.outcomes).toEqual({ resolved: 1 });+ // The follow-up names the plain sync that finishes the abandoned import, not a reconcile first.+ expect(String(applied.outcome_items![0]!.detail!.next)).toContain(`Next: gbrain sync --source ${f.id} --no-pull.`);+ const [abandoned] = await engine.executeRaw<Pick<WriteRequest, 'state' | 'error_code' | 'error_message'>>(+ "SELECT state,error_code,error_message FROM persistence_requests WHERE source_id=$1 AND slug='b' ORDER BY created_at DESC LIMIT 1", [f.id]);+ expect(abandoned).toMatchObject({ state: 'conflict', error_code: 'source_changed' });+ expect(abandoned.error_message ?? '').toContain('--keep disk');+ expect(fileChangedAfterAdmission(abandoned)).toBe(true);+ // The in-process consumer backs off after the dropped connection; the next sync starts a fresh one, as a restarted owner would.+ await disposePersistenceConsumer(engine);+ return { f, pin };+}++/** Resumes until the run settles; the in-process consumer may return a pass or two partial while it drains c. */+async function settle(engine: BrainEngine, opts: Parameters<typeof performManagedSync>[1]) {+ let result = await performManagedSync(engine, opts);+ for (let i = 0; i < 8 && result.status === 'partial' && result.reason === 'writer_pending'; i++) { await new Promise(r => setTimeout(r, 1000)); result = await performManagedSync(engine, opts); }+ return result;+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ installFaultHook(undefined);+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('#6858: a page abandoned by repair stuck-recovery --keep disk with uncommitted disk bytes is held worktree_dirty and the rest of the run drains', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const { f, pin } = await abandonedMidRun(engine, () => {});+ const resumed = await settle(engine, f.opts);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'b.md', code: 'worktree_dirty' }] });+ expect(resumed.failedFiles ?? 0).toBe(0);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('Gamma two.');+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Beta one.');+ expect(readFileSync(join(f.root, 'b.md'), 'utf8')).toBe(fixable('Beta two.', STAMP));+ }+}), 240_000);++test('#6858: when the kept disk bytes are HEAD (the lossless --keep disk case) the re-freeze imports them in the same pass', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const { f, pin } = await abandonedMidRun(engine, root => { commit(root, 'the stamped bytes are committed'); });+ const resumed = await settle(engine, f.opts);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin });+ expect(resumed.held ?? []).toEqual([]);+ expect(resumed.failedFiles ?? 0).toBe(0);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Beta two.');+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('Gamma two.');+ }+}), 240_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex fab049ff7d..01bd5193ba 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -98,6 +98,7 @@ test/managed-maintenance-links.test.tstest/managed-sweep-corpus-windows.test.tstest/managed-sweep-refused-window-retry.test.tstest/managed-sweep-timeline.test.ts+test/managed-sync-blocked-job-6858.test.tstest/managed-sync-bulk.test.tstest/managed-sync-checkpoint-replaced.test.tstest/managed-sync-chunker-version.test.ts@@ -105,9 +106,11 @@ test/managed-sync-concurrent-write-hold.test.tstest/managed-sync-connection-loss.test.tstest/managed-sync-drain.test.tstest/managed-sync-foreground-priority.test.ts+test/managed-sync-gate-markers-6858.test.tstest/managed-sync-group-completion.test.tstest/managed-sync-group-uncommitted-head.test.tstest/managed-sync-images-5493.test.ts+test/managed-sync-keep-disk-6858.test.tstest/managed-sync-lanes.test.tstest/managed-sync-orphans-incarnation-6518.test.tstest/managed-sync-page-fault-holds.test.tsdiff --git a/test/repair-stuck-recovery.test.ts b/test/repair-stuck-recovery.test.tsindex e559635c71..a81882566a 100644--- a/test/repair-stuck-recovery.test.ts+++ b/test/repair-stuck-recovery.test.ts@@ -146,6 +146,9 @@ describe('gbrain repair stuck-recovery', () => {expect(next).toContain(`gbrain sources reconcile ${s.sourceId} page --brain host --preview`);expect(next).not.toContain('file-drift');expect(next).toContain('does not mark the page repaired');+ // #6858: both follow-ups, in order: the additive-aware reconcile preview, then the sync that resumes the source.+ expect(next).toContain(`--preview --auto-additive`);+ expect(next.indexOf('--auto-additive')).toBeLessThan(next.indexOf(`gbrain sync --source ${s.sourceId} --no-pull`));expect(readFileSync(join(String(result.outcome_items![0]!.detail!.backup_dir), '0.prior'), 'utf8')).toBe(PRIOR);}));