Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/6712-pr2
garrytan09ee9fb01a27
diff --cc docs/guides/write-refusals.mdindex 09a3b8c779,30c9893533..0210ffe496--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@@ -193,11 -193,11 +193,11 @@@ with each file and fix the ones that ne| <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. || <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. || <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). The lane judges the file with the screen managed sync froze it with: a hold the sync screen now admits as the file is (its slug line names the file's own page as written, or it no longer declares a conflicting slug) is **imported** unchanged in one guarded write that clears only the hold observation the lane read (a hold a newer sync wrote stays, with a retry), and a file sync would hold whatever the lane writes is [`slug_page_mismatch`](#slug_page_mismatch). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). |-| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold. |+| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold, also when nothing was committed since (#6712 PR 2). || <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. |-| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |-| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). |-| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |+| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. A managed-sync hold re-screens on every sync, so either clears it on the next one. |- | <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host; a managed-sync hold re-screens on every sync, so the next one imports it. See [expire versus purge](memory-boundaries.md#purge). |++| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host; a managed-sync hold re-screens on every sync, so the next one imports it. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). |+| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source); an owner allow rule (`gbrain trust allow`) covering the source and the file's path admits it at freeze exactly as at preparation. The hold is `needs_human`, and every sync re-screens it, so the setting switched or an allow rule added clears it on the next sync. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |diff --cc src/core/behavior-change-notice.tsindex b82c39a5e2,f650b33340..a66cb087da--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -696,18 -696,10 +696,22 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.261.0', text: 'The update check (the startup `UPGRADE_AVAILABLE` marker, `gbrain check-update`, `gbrain self-upgrade`, doctor\'s `self_upgrade_health` and the `auto` channel) now reads the version at the `latest-stable` tag, the published release `bun update` installs, instead of master\'s `VERSION`. A version stamped on master but not yet released is no longer announced, and `auto` no longer tries to install it (#6718, #6828).' },{ since: '0.60.261.0', text: 'A `gbrain upgrade` whose install step leaves the same version running now prints `No newer version was installed` instead of `Upgrade complete`, and keeps `last_upgrade`, the pending-update marker and the `JUST_UPGRADED` breadcrumb as they were. The `auto` channel no longer exits for a relaunch after such a swap and no longer records the target known-bad: it audits the attempt as `skipped` and retries after 24 hours. A version is recorded known-bad only when it was installed and then failed, under the version actually installed.' },{ since: '0.60.261.0', text: '`gbrain doctor` (`self_upgrade_health`) now warns when `self_upgrade.failed_versions` holds a version the audit proves was never installed (an earlier release reported a no-op swap as swapped and recorded it known-bad, #6828), so `auto` would skip that release forever. `gbrain self-upgrade --clear-never-installed` previews the entries and the swap that recorded each; `--apply` removes exactly those. A post-upgrade failure recorded with no installable target (`latest`, `unknown`) now clears from `upgrade_errors` once the binary is past the version it failed from.' },+ // #6831 + #6816 hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.262.0', text: 'A managed Google or GitHub connector item whose content matches a page purge tombstone is now skipped, and the rest of the sync continues (#6831). Before, the pages guard\'s `purged_content` refusal of that one item ended the whole sync job, and every later sync of the source died the same way. Skipped items are listed in `gbrain sources status` ("skipped as purged content"), and `gbrain pages unpurge <slug>` lets one back in. Every other failed connector write still ends the run.' },+ { since: '0.60.262.0', text: 'A connector source whose syncs keep ending on an error now says so (#6831): `gbrain sources status` names the error, the item and a read-only next step, and reads STOPPED after 3 failed runs in a row; `gbrain sync status --json` adds `connector_last_error` with that read-only fix; doctor `sync_freshness` warns about a STOPPED source even when its last good sync was recent (fails past the fail age). `last_error`, `state` and `next` are unchanged for connector sources.' },+ { since: '0.60.262.0', text: 'A `claude-cli` usage-policy refusal ("API Error: <model> can\'t help with this ... https://www.anthropic.com/legal/aup", and the older "violate our Usage Policy" and "safeguards flagged this" wordings) is now a provider content block (`claude_cli_usage_policy`, #6816): `extract_atoms` tombstones the item after its consecutive-failure limit instead of re-sending it every run, and with `chat_fallback_on_refusal: false` the prompt is not sent on to the next model in `chat_fallback_chain`. Other `claude-cli` errors are unchanged.' },+ // #6712 PR 2 lane L3 (flags and config keys): `since` is a placeholder until the merge-slot stamp.- { since: '0.60.262.0', text: 'Five `sync.*` config keys are no longer read (#6712): `sync.bulk_max_txn_ms`, `sync.hold_cap`, `sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Set `GBRAIN_SYNC_BULK_MAX_TXN_MS`, `GBRAIN_SYNC_HOLD_CAP`, `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, `GBRAIN_SYNC_HOLD_ESCALATE_PCT` or `GBRAIN_SYNC_PARSER_REGRESSION` in the environment of the process that syncs instead; a value stored on the brain is kept but not applied, so a tuned brain runs with the defaults (15000, 500, 50, 5, stop) until the variable is set. `gbrain doctor --only sync_config_keys` lists stored values that stopped applying, `gbrain config get <key>` prints the value in effect and where it comes from, and `gbrain config set` of a retired key warns, names the variable and writes nothing (exit 0).' },- { since: '0.60.262.0', text: '`sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`, `sync.waive_batch` and `sync.bulk` are rollback keys (#6712): `false` still restores the earlier behavior a notice named, and they stay honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`), but `config set` now writes them with a note that they are not tunables and help text no longer recommends them. `sync.foreground_priority` is accepted without `--force` (it was refused as an unknown key). A serve or PGLite owner that receives a retired field from an older sync client (`explicitProcessing` today) prints one `[gbrain notice]` naming it and its window, and the PGLite owner lane accepts `--lanes N` and `--no-lanes` (ignored there) instead of refusing them.' },++ { since: '0.60.263.0', text: 'Five `sync.*` config keys are no longer read (#6712): `sync.bulk_max_txn_ms`, `sync.hold_cap`, `sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Set `GBRAIN_SYNC_BULK_MAX_TXN_MS`, `GBRAIN_SYNC_HOLD_CAP`, `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, `GBRAIN_SYNC_HOLD_ESCALATE_PCT` or `GBRAIN_SYNC_PARSER_REGRESSION` in the environment of the process that syncs instead; a value stored on the brain is kept but not applied, so a tuned brain runs with the defaults (15000, 500, 50, 5, stop) until the variable is set. `gbrain doctor --only sync_config_keys` lists stored values that stopped applying, `gbrain config get <key>` prints the value in effect and where it comes from, and `gbrain config set` of a retired key warns, names the variable and writes nothing (exit 0).' },++ { since: '0.60.263.0', text: '`sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`, `sync.waive_batch` and `sync.bulk` are rollback keys (#6712): `false` still restores the earlier behavior a notice named, and they stay honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`), but `config set` now writes them with a note that they are not tunables and help text no longer recommends them. `sync.foreground_priority` is accepted without `--force` (it was refused as an unknown key). A serve or PGLite owner that receives a retired field from an older sync client (`explicitProcessing` today) prints one `[gbrain notice]` naming it and its window, and the PGLite owner lane accepts `--lanes N` and `--no-lanes` (ignored there) instead of refusing them.' },+ // #6712 PR 2 lane L5 (truthful receipts, fast status). `since` is a placeholder until the merge-slot stamp.- { since: '0.60.262.0', text: 'A managed `gbrain sync` returns `synced` when its checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) now runs after the drain lease is released, bounded at 5 minutes, and a second sync can take the lease while it runs. A tail that fails, is cut short or gets no time keeps the run `synced` and adds a `[gbrain notice sync_tail_degraded]` with its fix (`gbrain extract --stale --source <id>`); a tail a crash skipped runs on the next sync of the source.' },- { since: '0.60.262.0', text: 'The `drain_stalled` cause `no_admission` is retired: a sync pass that admits nothing with no unfinished request stops `drain_stalled` / `no_progress` with the same step and statement, a delegated run no longer falls back to its own consumer for it, and the transaction-pooler warning line is gone. Scripts matching `no_admission` should match `no_progress`.' },- { since: '0.60.262.0', text: 'A plain `gbrain sync status` skips the terminal-failure summary, the checkpoint blocker list and the cursor list (their fields stay, empty or `unknown`, with `terminal_failures_read` / `checkpoint_blockers_read` / `cursors_read` set to `not_read` and a `--detail` fix); `gbrain sync status --detail` reads them. New fields: `state`, `reason`, `oldest_blocker`, `recovery`, and `public_category` on holds, `last_error`, receipts and doctor `sync_failures`.' },++ { since: '0.60.263.0', text: 'A managed `gbrain sync` returns `synced` when its checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) now runs after the drain lease is released, bounded at 5 minutes, and a second sync can take the lease while it runs. A tail that fails, is cut short or gets no time keeps the run `synced` and adds a `[gbrain notice sync_tail_degraded]` with its fix (`gbrain extract --stale --source <id>`); a tail a crash skipped runs on the next sync of the source.' },++ { since: '0.60.263.0', text: 'The `drain_stalled` cause `no_admission` is retired: a sync pass that admits nothing with no unfinished request stops `drain_stalled` / `no_progress` with the same step and statement, a delegated run no longer falls back to its own consumer for it, and the transaction-pooler warning line is gone. Scripts matching `no_admission` should match `no_progress`.' },++ { since: '0.60.263.0', text: 'A plain `gbrain sync status` skips the terminal-failure summary, the checkpoint blocker list and the cursor list (their fields stay, empty or `unknown`, with `terminal_failures_read` / `checkpoint_blockers_read` / `cursors_read` set to `not_read` and a `--detail` fix); `gbrain sync status --detail` reads them. New fields: `state`, `reason`, `oldest_blocker`, `recovery`, and `public_category` on holds, `last_error`, receipts and doctor `sync_failures`.' },+ // #6712 PR 2 lane L4 (exits, escalation, soak counters): placeholder since; the fresh-install cases in behavior-change-notice.test.ts pass once VERSION is stamped.- { since: '0.60.262.0', text: 'A held file now asks for a person (`needs_human`) only after its safe action failed three times and at least 24 hours have passed since it was first held (#6712). Three re-holds within an hour stay the agent\'s to retry. A `worktree_dirty` file whose uncommitted bytes changed in the last day, and an image held while multimodal embedding is off, never escalate this way. A failed `sync unblock --apply` (still dirty) or a repair that holds the file again counts as an attempt.' },- { since: '0.60.262.0', text: 'A managed-sync file that `write_gate.external_mode=reject` refuses is now held as `write_gate_rejected` when sync freezes it, instead of failing its receipt and stopping the rest of the source. A held file that leaves the source (excluded with `sync.exclude`, or an image while multimodal embedding is off) is released by the next sync even when nothing new was committed. Every sync re-screens a `write_gate_rejected`, `content_rejected` or `purged_content` hold, so switching the setting, an owner allow rule or `gbrain pages unpurge` clears it.' },- { since: '0.60.262.0', text: 'A `source_changed` write receipt\'s fix now follows its recorded reason: two-sided drift previews `gbrain repair file-drift --source <id> --slug <slug> --prefer database` (a group of them `--all-drifted --since <instant>`), a missing canonical file previews `gbrain repair ghost-pages`, an admission race is retried, and a changed binding or unsafe target names `gbrain sources writer status`. `gbrain repair file-drift` takes `--since <ISO-8601 | age>` to narrow `--all-drifted`.' },- { since: '0.60.262.0', text: 'Doctor `managed_sync_not_moving` now fails (it used to list the source as parked) when a managed source\'s queue holds admitted requests with no consumer and nothing has moved for longer than `persistence.preparation_ceiling_ms`; its fix is the resume sync, which consumes the queue (#6552). A managed sync now prints a line when live pages of the source have no canonical file, naming the read-only `gbrain repair ghost-pages` preview; it never deletes them.' },++ { since: '0.60.263.0', text: 'A held file now asks for a person (`needs_human`) only after its safe action failed three times and at least 24 hours have passed since it was first held (#6712). Three re-holds within an hour stay the agent\'s to retry. A `worktree_dirty` file whose uncommitted bytes changed in the last day, and an image held while multimodal embedding is off, never escalate this way. A failed `sync unblock --apply` (still dirty) or a repair that holds the file again counts as an attempt.' },++ { since: '0.60.263.0', text: 'A managed-sync file that `write_gate.external_mode=reject` refuses is now held as `write_gate_rejected` when sync freezes it, instead of failing its receipt and stopping the rest of the source. A held file that leaves the source (excluded with `sync.exclude`, or an image while multimodal embedding is off) is released by the next sync even when nothing new was committed. Every sync re-screens a `write_gate_rejected`, `content_rejected` or `purged_content` hold, so switching the setting, an owner allow rule or `gbrain pages unpurge` clears it.' },++ { since: '0.60.263.0', text: 'A `source_changed` write receipt\'s fix now follows its recorded reason: two-sided drift previews `gbrain repair file-drift --source <id> --slug <slug> --prefer database` (a group of them `--all-drifted --since <instant>`), a missing canonical file previews `gbrain repair ghost-pages`, an admission race is retried, and a changed binding or unsafe target names `gbrain sources writer status`. `gbrain repair file-drift` takes `--since <ISO-8601 | age>` to narrow `--all-drifted`.' },++ { since: '0.60.263.0', text: 'Doctor `managed_sync_not_moving` now fails (it used to list the source as parked) when a managed source\'s queue holds admitted requests with no consumer and nothing has moved for longer than `persistence.preparation_ceiling_ms`; its fix is the resume sync, which consumes the queue (#6552). A managed sync now prints a line when live pages of the source have no canonical file, naming the read-only `gbrain repair ghost-pages` preview; it never deletes them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/persistence/sync-status.tsindex c588f3db3e,d1726e994f..a9b849a107--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@@ -104,35 -95,13 +104,40 @@@ export interface SyncStatuscursors: SyncStatusCursor[];/** #6650: the source's terminal write receipts that did not commit, summarized (`terminal-failures.ts`); `unknown` when the bounded read timed out. */terminal_failures: SyncTerminalSummary;+ /**+ * #6831: for a Google or GitHub connector source, the error its connector runs keep ending on (null once a run+ * finishes). Connector runs keep no managed-sync cursor, so this never sets `last_error`, the cursor's `next` or `needs_human`.+ */+ connector_last_error: import('./connector-status.ts').ConnectorLastError | null;next: Action | null;+ /**+ * #6712 PR 2 (L5): the source's state in the sync outcome vocabulary (`synced` | `resumable` | `blocked`) and why+ * (`SYNC_STATUS_REASONS`). Never `synced` while a probe this read relies on did not answer.+ */+ state: SyncStatusState;+ reason: SyncStatusReason;+ /** #6712 PR 2: the source's oldest unfinished request (its running one first), bounded; works without a cursor. `unknown` when the read timed out. */+ oldest_blocker: { status: 'ok'; request: { request_id: string; state: string; phase: string | null; step: string | null; lapsed: boolean; blocked_by: { predicate: string; state: string | null; intervention: boolean } | null } | null }+ | { status: 'unknown'; reason: string };+ /** #6712 PR 2: requests of the source still holding a publication recovery record (they hold their root), bounded. */+ recovery: { status: 'ok'; count: number; first: { request_id: string; slug: string; blocked: boolean } | null } | { status: 'unknown'; reason: string };+ /**+ * #6712 PR 2: whether each heavy read ran. A plain `sync status` skips them (the fields keep their types: arrays stay+ * empty, `terminal_failures` reads `unknown`); `not_read` carries the `--detail` command that runs them. An agent never+ * reads an empty skipped field as "none".+ */+ checkpoint_blockers_read: SyncStatusRead;+ cursors_read: SyncStatusRead;+ terminal_failures_read: SyncStatusRead;}+export type SyncStatusState = 'synced' | 'resumable' | 'blocked';+/** Why the source is in its state; one closed list. */+export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',+ 'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked'] as const;+export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];+export type SyncStatusRead = { status: 'read' } | { status: 'not_read'; fix: Action };+/** The bound of each default probe (the oldest blocker, the recovery records). */+export const SYNC_STATUS_PROBE_MS = 2_000;export type SyncTerminalSummary = { status: 'unknown'; reason: string } | {status: 'ok'; window_days: number; active_blockers: Array<{ kind: 'recovery' | 'checkpoint'; request_id: string; slug?: string; category: string }>;@@@ -281,75 -237,15 +286,76 @@@ export async function readSyncStatus(en: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`: `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }: null;- const blockers = await checkpointBlockers(engine, header);+ const [oldest, recovery] = await Promise.all([oldestBlocker(engine, sourceId), recoveryProbe(engine, sourceId)]);+ const notRead = (field: string): { status: 'not_read'; fix: Action } => ({ status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--detail', '--json'], consent: [], actor: 'agent',+ requires_exclusive: false, why: `This status skipped the ${field} read (a heavy read); --detail runs it. Read-only.` } });+ const blockers = detail ? await checkpointBlockers(engine, header) : { checkpoint_blockers: [] };// #6650: a receipt still holding a recovery record holds its root, so a source with nothing else to do names it as `next`.- const { recovery_next, ...terminal } = await terminalSummary(engine, sourceId, blockers.checkpoint_blockers);+ const { recovery_next, ...terminal } = detail ? await terminalSummary(engine, sourceId, blockers.checkpoint_blockers)+ : { status: 'unknown' as const, reason: 'not_read: run sync status with --detail', recovery_next: recovery.status === 'ok' && recovery.first ? recoveryAction(sourceId, recovery.first) : undefined };+ const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);+ const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0 });return { source_id: sourceId, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),- resume_argv: resume, ...blockers, cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),- terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? null };+ resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],- terminal_failures: terminal, next: next ?? recovery_next ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,++ terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Action+ : stateReason === 'status_unknown' ? { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `The oldest-blocker or recovery probe did not answer within ${SYNC_STATUS_PROBE_MS / 1000} s, so this status does not know the state (it is not reported synced). Rerun it after a short wait; gbrain doctor --json checks the database if it keeps timing out.` } satisfies Action : null),+ state, reason: stateReason,+ oldest_blocker: oldest, recovery, checkpoint_blockers_read: detail ? { status: 'read' } : notRead('checkpoint blocker list'),+ cursors_read: detail ? { status: 'read' } : notRead('live cursor'), terminal_failures_read: detail ? { status: 'read' } : notRead('terminal-failure summary') };+}++/** #6712 PR 2: the state and its reason, from what this read saw; a probe that did not answer never yields `synced`. */+function statusState(s: { human: boolean; oldest: SyncStatus['oldest_blocker']; recovery: SyncStatus['recovery']; liveJob: boolean; unfinished: boolean; lastError: boolean;+ actionable: boolean; holds: boolean }): [SyncStatusState, SyncStatusReason] {+ if (s.human) return ['blocked', 'needs_human'];+ if (s.recovery.status === 'ok' && s.recovery.first?.blocked) return ['blocked', 'recovery_blocked'];+ if (s.oldest.status === 'ok' && s.oldest.request?.blocked_by?.intervention && s.oldest.request.state === 'queued') return ['blocked', 'head_blocked'];+ if (s.liveJob) return ['resumable', 'live_job'];+ if (s.unfinished) return ['resumable', 'cursor_unfinished'];+ if (s.lastError) return ['resumable', 'last_error'];+ if (s.actionable) return ['resumable', 'holds_actionable'];+ if (s.recovery.status === 'ok' && s.recovery.count > 0) return ['resumable', 'recovery_pending'];+ if (s.oldest.status === 'ok' && s.oldest.request) return ['resumable', 'request_pending'];+ if (s.oldest.status !== 'ok' || s.recovery.status !== 'ok') return ['resumable', 'status_unknown'];+ return ['synced', s.holds ? 'held_by_design' : 'nothing_pending'];+}++/** #6712 PR 2: the source's oldest unfinished request, read through the drain's own bounded head probe. */+async function oldestBlocker(engine: BrainEngine, sourceId: string): Promise<SyncStatus['oldest_blocker']> {+ const head = engineStallProbe(engine, sourceId).head!;+ try {+ const row = await Promise.race([head(), new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`no answer within ${SYNC_STATUS_PROBE_MS} ms`)), SYNC_STATUS_PROBE_MS + 1_000).unref?.())]);+ if (!row) return { status: 'ok', request: null };+ return { status: 'ok', request: { request_id: row.write_request_id ?? row.request_id ?? '', state: row.head_state, phase: row.claim?.phase ?? null, step: row.claim?.step ?? null, lapsed: row.claim?.lapsed === true,+ blocked_by: row.blocked_by ? { predicate: row.blocked_by.predicate, state: row.blocked_by.state, intervention: row.blocked_by.intervention } : null } };+ } catch (error) {+ return { status: 'unknown', reason: error instanceof Error ? error.message : String(error) };+ }+}++/** #6712 PR 2: the source's requests holding a publication recovery record, bounded; it needs no cursor. */+async function recoveryProbe(engine: BrainEngine, sourceId: string): Promise<SyncStatus['recovery']> {+ try {+ const rows = await engine.executeRaw<{ n: number | string; request_id: string | null; slug: string | null; blocked: boolean | null }>(+ `SELECT (SELECT count(*) FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL) AS n, f.request_id::text AS request_id, f.slug,+ f.blocked_reason IN ('unexpected_staging_bytes','unexpected_file_bytes') AS blocked+ FROM (SELECT 1) one LEFT JOIN LATERAL (SELECT request_id, slug, blocked_reason FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL ORDER BY sequence LIMIT 1) f ON true`, [sourceId], { timeoutMs: SYNC_STATUS_PROBE_MS, signal: AbortSignal.timeout(SYNC_STATUS_PROBE_MS + 500) });+ const row = rows[0];+ const count = Number(row?.n ?? 0);+ return { status: 'ok', count, first: count && row?.request_id ? { request_id: row.request_id, slug: row.slug ?? '', blocked: row.blocked === true } : null };+ } catch (error) {+ return { status: 'unknown', reason: error instanceof Error ? error.message : String(error) };+ }+}++/** The recovery record's next step, as the terminal-failure summary names it (`classifyTerminal`'s recovery verdict). */+function recoveryAction(sourceId: string, first: { request_id: string; slug: string; blocked: boolean }): Action {+ return classifyTerminal({ request_id: first.request_id, source_id: sourceId, slug: first.slug, operation: 'submit_job', state: 'running', error_code: null, recovery: true,+ blocked_reason: first.blocked ? 'unexpected_file_bytes' : null, compacted: false })!.action;}/**