Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): Git holds in sources status and retry-held; held pages name the hold (#5988)

garrytandb1c76eafd6e
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index e26ade76c2..914eaf1e0d 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -9,7 +9,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.
- `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account.
- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.
-- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys.
+- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.
- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.
- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through Gmail profile, Calendar primary calendar or People `me` (first enabled service that answers; none refuses), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.
- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index edaf491763..a556c72543 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -48,7 +48,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.serial.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
-- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
+- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.
diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsv
index d573c2cad8..42080cd462 100644
--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv
+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv
@@ -27,7 +27,7 @@ src/commands/serve-http-oauth.ts 1
src/commands/serve-http-registration.ts 1
src/commands/serve-http-webhooks.ts 4
src/commands/skillpack.ts 1
-src/commands/sources-retry-held.ts 3
+src/commands/sources-retry-held.ts 2
src/commands/upgrade.ts 7
src/core/agent-install/entry.ts 1
src/core/agent-install/shared-skills.ts 7
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index cde8edb60c..c90e62ec79 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
-src/commands/sources.ts 2020 ratchet +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
+src/commands/sources.ts 2022 ratchet +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note
src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.ts
index c55ed9c347..3a2b80d778 100644
--- a/src/commands/sources-retry-held.ts
+++ b/src/commands/sources-retry-held.ts
@@ -7,51 +7,99 @@
* retry-pointer row `--retry-failed` writes, so the next sync admits the item
* under a new request identity. Nothing runs now: the receipt says how many
* items are scheduled and prints the sync and status commands.
+ *
+ * #5988: on a Git source it records a re-screen request (op `sync-hold-retry`)
+ * for every held file; the next sync adds those paths to its manifest even if
+ * Git did not touch them, imports each one that now passes and keeps the rest
+ * held. Most holds re-screen by themselves (changed or deleted file, newer
+ * gbrain); the request covers causes outside the file.
*/
import type { BrainEngine } from '../core/engine.ts';
+import type { Action } from '../core/agent-output.ts';
import { OperationError } from '../core/ops/contract.ts';
import { managedBrain, readAllSourceHolds, readHoldRetryKeys, requestHoldRetry, writeHeldRetryPointer } from '../core/connectors/item-holds-store.ts';
+import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
+import { readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';
export interface RetryHeldReceipt {
source_id: string;
+ /** `connector`: held Google/GitHub items; `git`: held files of a Git source. */
+ kind: 'connector' | 'git';
dry_run: boolean;
scheduled: number;
- items: Array<{ key: string; code: string; action: 'would_retry' | 'retry_scheduled'; next_action: string }>;
+ items: Array<{ key: string; code: string; reason?: string; action: 'would_retry' | 'retry_scheduled'; next_action: string }>;
next_action: string;
+ /** Git sources with held files: the one next step (the sync that re-screens them, or the scheduling command after a dry run). */
+ fix?: Action;
+}
+
+interface Scheduled { items: Array<{ key: string; code: string; reason?: string; already: boolean }>; sync: string[] }
+
+async function scheduleConnectorItems(engine: BrainEngine, sourceId: string, incarnation: string, dryRun: boolean): Promise<Scheduled> {
+ const held = (await readAllSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.held ?? [];
+ const sync = ['gbrain', 'sync', '--source', sourceId];
+ if (!held.length) return { items: [], sync };
+ if (!dryRun) {
+ // Pointers first: a sync that sees the retry request must already find the replacement identity.
+ if (await managedBrain(engine)) for (const record of held) if (record.request_id) await writeHeldRetryPointer(engine, sourceId, record.request_id);
+ await requestHoldRetry(engine, sourceId, incarnation, held.map(record => record.key));
+ }
+ const already = new Set(dryRun ? await readHoldRetryKeys(engine, sourceId, incarnation) : []);
+ return { items: held.map(record => ({ key: record.key, code: record.code, already: already.has(record.key) })), sync };
+}
+
+async function scheduleGitFiles(engine: BrainEngine, sourceId: string, incarnation: string, dryRun: boolean): Promise<Scheduled> {
+ const held = (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [];
+ // Managed sync refuses to pull; the plain command is the classic one.
+ const sync = ['gbrain', 'sync', '--source', sourceId, ...(await managedBrain(engine) ? ['--no-pull'] : [])];
+ if (!held.length) return { items: [], sync };
+ if (!dryRun) await requestGitHoldRetry(engine, sourceId, incarnation, held.map(record => record.path));
+ const already = new Set(dryRun ? await readGitHoldRetryPaths(engine, sourceId, incarnation) : []);
+ return { items: held.map(record => ({ key: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),
+ already: already.has(record.path) })), sync };
+}
+
+function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): { text: string; fix: Action } {
+ const count = scheduled.items.length;
+ const sync = scheduled.sync.join(' ');
+ const verify = { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] };
+ const automatic = 'Most holds re-screen on the next sync by themselves (the file changed or was deleted, or a newer gbrain can read it); '
+ + 'a scheduled re-screen covers a cause outside the file, such as a conflicting page that has since moved.';
+ if (dryRun) return { text: `${count} held file(s) would be scheduled for a re-screen; run: gbrain sources retry-held ${sourceId}. ${automatic}`,
+ fix: { argv: ['gbrain', 'sources', 'retry-held', sourceId], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };
+ return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `
+ + `A file that still refuses stays held; preview its fix with: gbrain repair frontmatter --source ${sourceId}`,
+ fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };
}
export async function retryHeld(engine: BrainEngine, sourceId: string, opts: { dryRun?: boolean } = {}): Promise<RetryHeldReceipt> {
const [source] = await engine.executeRaw<{ incarnation: string; config: Record<string, unknown> }>(
'SELECT incarnation::text AS incarnation,config FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
if (!source) throw new OperationError('not_found', `Source "${sourceId}" was not found.`, 'List sources with: gbrain sources list');
- if (source.config.kind !== 'google' && source.config.kind !== 'github') {
- throw new OperationError('invalid_params', `Source "${sourceId}" is not a connector source; only Google and GitHub sources hold items.`,
- `For a Git source, re-attempt failed files with: gbrain sync --source ${sourceId} --retry-failed`);
- }
- const held = (await readAllSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.held ?? [];
+ const kind = isConnectorSourceKind(source.config.kind) ? 'connector' as const : 'git' as const;
const dryRun = opts.dryRun === true;
- const sync = `gbrain sync --source ${sourceId}`;
- const status = `gbrain sources status ${sourceId}`;
- if (!held.length) return { source_id: sourceId, dry_run: dryRun, scheduled: 0, items: [], next_action: `No held items for ${sourceId}.` };
- const managed = await managedBrain(engine);
- if (!dryRun) {
- // Pointers first: a sync that sees the retry request must already find the replacement identity.
- if (managed) for (const record of held) if (record.request_id) await writeHeldRetryPointer(engine, sourceId, record.request_id);
- await requestHoldRetry(engine, sourceId, source.incarnation, held.map(record => record.key));
- }
- const already = new Set(dryRun ? await readHoldRetryKeys(engine, sourceId, source.incarnation) : []);
- const items = held.map(record => ({ key: record.key, code: record.code,
- action: dryRun && !already.has(record.key) ? 'would_retry' as const : 'retry_scheduled' as const,
- next_action: dryRun ? 'Run the same command without --dry-run to schedule it.' : `Re-attempted on the next ${sync}.` }));
- return { source_id: sourceId, dry_run: dryRun, scheduled: dryRun ? 0 : held.length, items,
- next_action: dryRun ? `${held.length} held item(s) would be scheduled; run: gbrain sources retry-held ${sourceId}`
- : `${held.length} held item(s) scheduled; none has run yet. Run them now with: ${sync}, then verify with: ${status}` };
+ const scheduled = await (kind === 'connector' ? scheduleConnectorItems : scheduleGitFiles)(engine, sourceId, source.incarnation, dryRun);
+ const count = scheduled.items.length;
+ const sync = scheduled.sync.join(' ');
+ const step = kind === 'git' && count ? gitNextStep(sourceId, dryRun, scheduled) : undefined;
+ const next = !count ? `No held ${kind === 'connector' ? 'items' : 'files'} for ${sourceId}.`
+ : step ? step.text
+ : dryRun ? `${count} held item(s) would be scheduled; run: gbrain sources retry-held ${sourceId}`
+ : `${count} held item(s) scheduled; none has run yet. Run them now with: ${sync}, then verify with: gbrain sources status ${sourceId}`;
+ const items = scheduled.items.map(item => ({ key: item.key, code: item.code, ...(item.reason ? { reason: item.reason } : {}),
+ action: dryRun && !item.already ? 'would_retry' as const : 'retry_scheduled' as const,
+ next_action: dryRun ? 'Run the same command without --dry-run to schedule it.' : `${kind === 'git' ? 'Re-screened' : 'Re-attempted'} on the next ${sync}.` }));
+ return { source_id: sourceId, kind, dry_run: dryRun, scheduled: dryRun ? 0 : count, items, next_action: next, ...(step ? { fix: step.fix } : {}) };
}
export async function runRetryHeld(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
console.log('Usage: gbrain sources retry-held <id> [--dry-run] [--json]\n\n'
- + 'Re-attempt every held connector item of a Google or GitHub source on its next sync.\n'
+ + 'Re-attempt every held connector item of a Google or GitHub source on its next sync, or re-screen every\n'
+ + 'held file of a Git source on its next sync (most held files re-screen by themselves when they change).\n'
+ + 'Nothing runs now.\n'
+ ' --dry-run show what would be scheduled; change nothing\n --json print the receipt as JSON');
return;
}
@@ -62,6 +110,6 @@ export async function runRetryHeld(engine: BrainEngine, args: string[]): Promise
if (positional.length !== 1) throw new OperationError('invalid_params', 'Name one source.', 'Usage: gbrain sources retry-held <id> [--dry-run] [--json]');
const receipt = await retryHeld(engine, positional[0], { dryRun: args.includes('--dry-run') });
if (json) { console.log(JSON.stringify(receipt, null, 2)); return; }
- for (const item of receipt.items) console.log(` ${item.key} (${item.code}): ${item.action}`);
+ for (const item of receipt.items) console.log(` ${item.key} (${item.code}${item.reason ? `, ${item.reason}` : ''}): ${item.action}`);
console.log(receipt.next_action);
}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 5511f30f6c..3efee68a2a 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1207,10 +1207,12 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
// ── v0.40 sources status (D12) ──────────────────────────────
async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
- const json = args.includes('--json');
+ const json = args.includes('--json'), only = args.find(arg => !arg.startsWith('-'));
const { loadAllSources } = await import('../core/sources-load.ts');
const { computeAllSourceMetrics } = await import('../core/source-health.ts');
- const sources = await loadAllSources(engine, { includeArchived: false });
+ const statusView = await import('../core/persistence/connector-status.ts');
+ const sources = (await loadAllSources(engine, { includeArchived: false })).filter(source => !only || source.id === only);
+ if (only && !sources.length) throw statusView.statusSourceNotFound(only);
if (sources.length === 0) {
if (json) {
console.log(JSON.stringify({ schema_version: 1, sources: [] }, null, 2));
@@ -1240,7 +1242,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
}),
);
- const connectors = await (await import('../core/persistence/connector-status.ts')).readConnectorSourceStatuses(engine);
+ const connectors = await statusView.readConnectorSourceStatuses(engine, sources.map(source => source.id));
+ const gitHolds = await statusView.readGitHoldStatuses(engine, sources.map(source => source.id));
if (json) {
const enriched = metrics.map((m) => ({
...m,
@@ -1248,6 +1251,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
sync_holder: syncRunning.get(m.source_id) ?? null,
...(ingestion.get(m.source_id) ? { ingestion: ingestion.get(m.source_id) } : {}),
...(connectors.get(m.source_id) ? { connector: connectors.get(m.source_id) } : {}),
+ ...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}),
}));
console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));
return;
@@ -1285,8 +1289,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
console.log(` ${m.source_id.padEnd(20)} ${lag.padEnd(8)} ${embed.padEnd(7)} ${backfill.padEnd(9)} ${fails.padEnd(6)} ${queue.padEnd(6)} ${pages.padStart(8)} ${sync}`);
}
console.log('');
- const { connectorStatusLines } = await import('../core/persistence/connector-status.ts');
- for (const [sourceId, status] of connectors) for (const line of connectorStatusLines(sourceId, status)) console.log(line);
+ for (const [sourceId, status] of connectors) for (const line of statusView.connectorStatusLines(sourceId, status)) console.log(line);
+ for (const [sourceId, status] of gitHolds) for (const line of statusView.gitHoldStatusLines(sourceId, status)) console.log(line);
for (const m of metrics) {
const warns: string[] = [];
if (!m.local_path) warns.push('no local_path');
@@ -1930,9 +1934,9 @@ Subcommands:
when the source has data (pages/chunks/embeddings).
archive <id> Soft-delete: hide from search, preserve data for ${SOFT_DELETE_TTL_HOURS}h.
restore <id> [--no-federate] Un-archive a soft-deleted source.
- status [--json] v0.40.3.0 — read-only per-source dashboard:
+ status [<id>] [--json] v0.40.3.0 — read-only per-source dashboard:
last sync, staleness, page count,
- embedding coverage, unacked failures.
+ embedding coverage, unacked failures, held files.
--json emits {schema_version:1, ...} on
stdout for monitoring pipelines.
archived [--json] List soft-deleted sources and their expiry.
@@ -1974,7 +1978,7 @@ Subcommands:
doesn't exist. See gbrain doctor's
default_source_local_path check.
retry-held <id> [--dry-run] [--json]
- Re-attempt a Google or GitHub source's held items on its next sync.
+ Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.
set-path <id> --clear Clear a connector source's (google, github)
stale local_path; takes no path.
webhook <set|show|rotate|clear> <id> [options]
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index f5ce1390a5..7b638db189 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -3,7 +3,7 @@ import type { GitHoldItem } from '../core/persistence/sync-holds.ts';
const HOLD_LINES = 20;
-function holdLine(item: GitHoldItem, verb: string): string {
+export function holdLine(item: GitHoldItem, verb: string): string {
const where = [item.line !== undefined ? `line ${item.line}` : '', item.key ? `key "${item.key}"` : ''].filter(Boolean).join(', ');
const page = item.stale ? 'its page keeps its last good revision and is read-only for put_page until the file is repaired' : 'its page is missing until the file imports';
return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${where ? ` at ${where}` : ''}; ${page}. Next: ${item.fix.argv?.join(' ') ?? item.fix.why} (${item.docs})`;
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index f26201f3a3..bb05bb2598 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -10,6 +10,7 @@ import { resolveNoEmbed } from '../../core/sync-git.ts';
import type { SyncOpts } from '../sync.ts';
import { parseMissingPathMode } from './missing-path.ts';
import { intFlagValue } from '../../cli/flag-values.ts';
+import { usageError } from '../../cli/cli-error.ts';
import type { MissingPathMode } from './missing-path.ts';
export function printSyncHelp(): void {
@@ -119,7 +120,23 @@ See also:
/** setTimeout treats delays above 2^31-1 ms as ~1 ms; --interval stays within that bound. */
const MAX_WATCH_INTERVAL_SECONDS = Math.floor(2_147_483_647 / 1000);
+/**
+ * #5988: there is no `sync --retry-held`. Held files re-screen on the next
+ * sync by themselves; `sources retry-held` schedules a re-screen without
+ * running anything, so the refusal names it instead of acting as an alias.
+ */
+function retryHeldRefusal(args: string[]) {
+ const source = args.find((a, i) => args[i - 1] === '--source');
+ return usageError('gbrain sync has no --retry-held flag; held files are re-screened on the next sync, and sources retry-held schedules a re-screen for a source.',
+ `Run gbrain sources retry-held ${source ?? '<source-id>'}, then sync that source again without --retry-held.`, {
+ fix: { argv: ['gbrain', 'sources', 'retry-held', source ?? '<source-id>'], consent: [], actor: 'agent', requires_exclusive: false,
+ ...(source ? {} : { inputs: [{ name: 'source-id', how: 'gbrain sources status lists each source with its held files' }] }),
+ why: 'Most held files re-screen on the next sync by themselves (changed, deleted, or readable by a newer gbrain); retry-held schedules a re-screen of every held file of the source on its next sync and runs nothing now.',
+ verify: { argv: ['gbrain', 'sources', 'status', ...(source ? [source] : []), '--json'] } } });
+}
+
export function parseSyncFlags(args: string[]) {
+ if (args.includes('--retry-held')) throw retryHeldRefusal(args);
const repoPath = args.find((a, i) => args[i - 1] === '--repo') || undefined;
const watch = args.includes('--watch');
// #5931 (D4): timers coerce delays above 2^31-1 ms (and NaN/0) to ~1 ms, so a bad
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e63ffb78c1..6e5d3b4bd1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--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', '--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', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--image', '--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', '--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-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--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', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--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', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--image', '--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', '--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-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--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', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--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', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -100,7 +100,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],
'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--remediation-plan', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
@@ -119,10 +119,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
- 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.ts
index 6da81ad019..a5ae393963 100644
--- a/src/core/persistence/connector-status.ts
+++ b/src/core/persistence/connector-status.ts
@@ -2,11 +2,20 @@
* `gbrain sources status` view of each managed connector source's state row:
* upgrade recovery, account pin continuity, pending receipts and the last
* run's counts. Never includes the pinned account or installation id.
+ *
+ * #5988: also each Git source's held files (`readGitHoldStatuses`), shown
+ * beside connector holds. Only `sources status` and `sources retry-held` merge
+ * the two; `readAllSourceHolds`, `gbrain waiting` and doctor
+ * `connector_held_items` stay connector-only.
*/
import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { readManagedConnectorState, type ConnectorRunCounts, type UpgradeRecovery } from './connector-state.ts';
-import { readAllSourceHolds } from '../connectors/item-holds-store.ts';
+import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store.ts';
import type { ItemHoldRecord } from '../connectors/item-holds.ts';
+import { gitHoldItem, readGitSourceHolds, readSyncHoldPolicy, type GitHoldItem } from './sync-holds.ts';
+import { holdLine } from '../../commands/sync-diagnostics.ts';
/** Fix wave 4: `sources status` lists this many held items per source, then "+N more". */
export const HELD_STATUS_LIMIT = 10;
@@ -24,9 +33,10 @@ export interface ConnectorSourceStatus {
held_error?: string;
}
-export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, ConnectorSourceStatus>> {
+export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<Map<string, ConnectorSourceStatus>> {
const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
- "SELECT id,incarnation::text FROM sources WHERE NOT archived AND config->>'kind' IN ('google','github')");
+ "SELECT id,incarnation::text FROM sources WHERE NOT archived AND config->>'kind' IN ('google','github') AND ($1::text[] IS NULL OR id=ANY($1::text[]))",
+ [sourceIds ?? null]);
const statuses = new Map<string, ConnectorSourceStatus>();
for (const source of sources) {
const state = await readManagedConnectorState(engine, source.id, source.incarnation);
@@ -77,3 +87,44 @@ export function heldItemLines(sourceId: string, held: ItemHoldRecord[]): string[
lines.push(` re-attempt them on the next sync: gbrain sources retry-held ${sourceId}`);
return lines;
}
+
+/** `sources status <id>` naming no registered, unarchived source. */
+export function statusSourceNotFound(sourceId: string) {
+ return opError('not_found', `Source "${sourceId}" was not found (or is archived).`, 'List the registered sources, then run sources status with one of their ids.',
+ { fix: readFix('Lists the registered sources and their ids, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+}
+
+/** A Git source's held files: the outstanding count and up to `sync.hold_cap` of them in detail. */
+export interface GitHoldStatus {
+ count: number;
+ items: GitHoldItem[];
+ truncated?: true;
+ /** The command that runs the next sync of this source (managed brains sync with --no-pull). */
+ sync_argv: string[];
+}
+
+/** Held files of each listed source that has any (sources with none are absent). */
+export async function readGitHoldStatuses(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceIds: string[]): Promise<Map<string, GitHoldStatus>> {
+ const out = new Map<string, GitHoldStatus>();
+ if (!sourceIds.length) return out;
+ const sources = await readGitSourceHolds(engine, { sourceIds });
+ if (!sources.length) return out;
+ const { cap } = await readSyncHoldPolicy(engine);
+ const managed = await managedBrain(engine);
+ for (const source of sources) {
+ out.set(source.sourceId, { count: source.count, items: source.holds.slice(0, cap).map(gitHoldItem),
+ ...(source.count > cap ? { truncated: true as const } : {}),
+ sync_argv: ['gbrain', 'sync', '--source', source.sourceId, ...(managed ? ['--no-pull'] : [])] });
+ }
+ return out;
+}
+
+/** Held files: up to HELD_STATUS_LIMIT per source with each one's next step, then the re-screen and retry commands. */
+export function gitHoldStatusLines(sourceId: string, status: GitHoldStatus): string[] {
+ const lines = [` ${sourceId}: ${status.count} held file(s): not imported, and they do not block sync. A page whose newer file is held keeps its last good revision and is read-only for put_page until the file is repaired.`];
+ for (const item of status.items.slice(0, HELD_STATUS_LIMIT)) lines.push(` ${holdLine(item, 'Held').trim()} Held since ${day(item.held_since)}.`);
+ if (status.count > HELD_STATUS_LIMIT) lines.push(` +${status.count - HELD_STATUS_LIMIT} more; --json lists ${status.truncated ? `the first ${status.items.length}` : 'all'}`);
+ lines.push(` Most holds re-screen on the next sync by themselves (the file changed or was deleted, or a newer gbrain can read it): ${status.sync_argv.join(' ')}`);
+ lines.push(` to re-screen the held files on that sync even if nothing changed: gbrain sources retry-held ${sourceId}`);
+ return lines;
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 354120ce73..25d3dcef54 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1,7 +1,7 @@
import { isEmbedSkipped } from '../embed-skip.ts';
import { isQuarantined } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
-import { join, relative } from 'node:path';
+import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
@@ -9,12 +9,14 @@ import { importFromContent, type ParsedPage } from '../import-file.ts';
import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import type { Action } from '../agent-output.ts';
+import { shellQuote, type Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { pageIdentityError } from './page-identity.ts';
import { contentRefusalError } from '../import-screen.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
+import { gitHoldFix, readGitHold } from './sync-holds.ts';
+import { heldFileMessage } from './verb-errors.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
@@ -160,6 +162,8 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// Withdrawal overlays intentionally precede physical mirroring. The ledger
// is applied by the import preparation and cannot be undone by this check.
if (digest(actual) !== digest(expected)) {
+ const held = await heldFileRefusal(engine, row, root, path, 'drift');
+ if (held) throw held;
const error = new OperationError('source_changed', 'The canonical file contains an uncoordinated local edit.',
`On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`);
error.detail = 'file_database_drift';
@@ -167,11 +171,32 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
}
} else if (before && !snapshot && content !== null && sha256(before) !== sha256(content)
&& !(options.capture && sha256(before) === options.capture.hash)) {
- throw new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');
+ throw await heldFileRefusal(engine, row, root, path, 'occupied')
+ ?? new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');
}
return { path, root, content, expectedBeforeHash: before ? sha256(before) : null };
}
+/**
+ * #5988: a drift or occupied-path refusal whose file sync holds names the hold
+ * instead of reconciliation: the page stays read-only for put_page until the
+ * file is repaired. Two point reads, only when the refusal already fires.
+ */
+async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'slug'>, root: string, path: string,
+ kind: 'drift' | 'occupied'): Promise<OperationError | null> {
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [row.source_id]);
+ const hold = source ? await readGitHold(engine, row.source_id, source.incarnation, relative(root, path).split(sep).join('/')) : null;
+ if (!hold) return null;
+ const fix = gitHoldFix(hold);
+ const where = [hold.meta.line !== undefined ? `line ${hold.meta.line}` : '', hold.meta.key ? `key "${hold.meta.key}"` : ''].filter(Boolean).join(', ');
+ const error = opError('source_changed', heldFileMessage(kind, hold.code),
+ `Sync holds ${hold.path} in source ${row.source_id} (${hold.code}${hold.meta.reason ? `, ${hold.meta.reason}` : ''}${where ? ` at ${where}` : ''}) because gbrain cannot import it, `
+ + `so ${kind === 'drift' ? `page ${row.slug} keeps its last good revision and` : `page ${row.slug} does not exist yet and its path`} is read-only for put_page until the file is repaired; retrying this write refuses the same way. `
+ + `Repair the file first (${shellQuote(fix.argv ?? [])}: ${fix.why}), then submit the intended write with a new request_id. Neither copy was overwritten.`, { fix });
+ if (kind === 'drift') error.detail = 'file_database_drift';
+ return error;
+}
+
/**
* Receipt reason for a page write that publishes no file. Invariant: for a
* bound row, prepareFileTarget returns no target only for a live declared
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 779e824f19..e1c6eb1e39 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -12,6 +12,7 @@ import { assertMutationProtocol } from './protocol.ts';
import { pendingWriteHint } from './health.ts';
import { receiptDeliveredHint } from './connector-errors.ts';
import { contentRefusalFromReceipt } from '../import-screen.ts';
+import { heldFileDiagnostic } from './verb-errors.ts';
import { isMissingPageMessage } from './page-identity.ts';
interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
@@ -155,11 +156,13 @@ export function writeResponse(row: WriteRequest): Record<string, unknown> {
const delivered = isTerminal(row) ? receiptDeliveredHint(row) : null;
// #5988: a content refusal reports its typed code, reason, key and line, and the content fix.
const content = isTerminal(row) ? contentRefusalFromReceipt(row.error_code, row.error_message) : null;
+ // The page's file is held by sync: name the repair, so the caller does not retry into the same refusal.
+ const held = isTerminal(row) && reason === 'source_changed' ? heldFileDiagnostic(row.error_message, row.source_id) : null;
const error = new OperationError(reason, !isTerminal(row) ? 'The write is accepted and is still pending.'
: row.error_message ?? 'The write did not commit.', !isTerminal(row)
? pendingWriteHint(receipt)
- : delivered?.suggestion ?? content?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
- if (delivered?.detail) error.detail = delivered.detail;
+ : delivered?.suggestion ?? content?.suggestion ?? held?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
+ if (delivered?.detail ?? held?.reason) error.detail = delivered?.detail ?? held?.reason;
if (content) {
if (content.code !== reason) error.canonical = content.code;
if (content.reason) error.reason = content.reason;
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index ea68f1064a..e584e40a08 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -11,7 +11,29 @@ export function frontmatterSlugConflictMessage(path: string, found: string, expe
return `The frontmatter slug "${found}" in ${path} conflicts with its path, which expects slug "${expected}". Remove \`slug:\` or make it match the path.`;
}
+/** #5988: the page's canonical file is held by sync; the code says why gbrain cannot import it. Location-free, so receipts may keep it. */
+const 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\.$/;
+
+export function heldFileMessage(kind: 'drift' | 'occupied', code: string): string {
+ return kind === 'drift'
+ ? `The canonical file is held by sync (${code}) and differs from the page; the page is read-only for put_page until the file is repaired.`
+ : `A file held by sync (${code}) occupies the canonical page path; the page is read-only for put_page until the file is repaired.`;
+}
+
+/** The diagnostic of a held-file refusal message (null for any other message); `sourceId` fills the commands when the caller knows it. */
+export function heldFileDiagnostic(message: string | null | undefined, sourceId = '<source>'): { reason: string; message: string; suggestion: string } | null {
+ const held = message ? HELD_FILE.exec(message) : null;
+ if (!held) return null;
+ return { reason: held[1] === 'and differs from the page' ? 'file_database_drift' : 'canonical_path_occupied', message: message!,
+ suggestion: `Sync holds this page's file because gbrain cannot import it; gbrain sources status ${sourceId} names the file, line and key. `
+ + 'The page keeps its last good revision and refuses put_page until the file is repaired, so retrying this write refuses the same way. '
+ + `On the source host, repair the file first (frontmatter holds: preview the fix with gbrain repair frontmatter --source ${sourceId} and apply it; file_too_large: split the file), `
+ + 'then submit the intended write with a new request_id. Neither copy was overwritten.' };
+}
+
export function writeFailureDiagnostic(code: string, message?: string | null): { reason: string; message: string; suggestion: string } {
+ const held = code === 'source_changed' ? heldFileDiagnostic(message) : null;
+ if (held) return held;
if (code === 'source_changed') {
if (message === 'The canonical file contains an uncoordinated local edit.') return {
reason: 'file_database_drift', message: 'The canonical file and database disagree. Neither copy was overwritten.',
diff --git a/test/sync-hold-surfaces.test.ts b/test/sync-hold-surfaces.test.ts
new file mode 100644
index 0000000000..0e6ff7da17
--- /dev/null
+++ b/test/sync-hold-surfaces.test.ts
@@ -0,0 +1,258 @@
+/**
+ * #5988 Lane B item 5: Git holds outside sync itself. `sources status <id>`
+ * filters to the source and lists its held files (X2 fields, text and JSON);
+ * `sources retry-held` schedules a re-screen of a Git source's held files;
+ * `sync --retry-held` refuses with the pointer; Git holds never block writer
+ * deactivation or activation (X14); a put_page refused over a held file names
+ * the hold instead of reconciliation (E26).
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { retryHeld, runRetryHeld } from '../src/commands/sources-retry-held.ts';
+import { parseSyncFlags } from '../src/commands/sync/args.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';
+import { heldFileMessage, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';
+import { readGitHold, readGitHoldRetryPaths, writeGitHold, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { writerAdminState } from '../src/core/persistence/admin-intent.ts';
+import { carryLegacyFailCounts } from '../src/core/connectors/item-holds.ts';
+import { connectorCheckpointKey, connectorIdentity } from '../src/core/persistence/connector-identity.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { put } from './helpers/wave-fixture.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+
+type HoldInput = Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'>;
+
+const incarnationOf = async (engine: BrainEngine, sourceId: string) =>
+ (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]))[0].incarnation;
+
+const hold = (sourceId: string, incarnation: string, path: string, extra: Partial<HoldInput> = {}): HoldInput => ({
+ source_id: sourceId, incarnation, path, source_path: path, slug: path.replace(/\.md$/, ''), page_id: null, code: 'invalid_frontmatter',
+ message: 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.', upstream_version: `sha-${path}`,
+ observed_at: '2026-10-01T00:00:00.000Z', run_id: 'run-1', mode: 'managed',
+ meta: { reason: 'needs_interpretation', key: 'title', line: 2, recovery_version: 1 }, ...extra,
+});
+
+async function captured(run: () => Promise<void>): Promise<string> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ try { await run(); } finally { log.mockRestore(); warn.mockRestore(); }
+ return lines.join('\n');
+}
+
+describe('sources status and retry-held on Git sources', () => {
+ let engine: PGLiteEngine;
+ let home: string;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-hold-surfaces-'));
+ for (const id of ['notes-git', 'other-git']) {
+ mkdirSync(join(home, id));
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, join(home, id)]);
+ }
+ await engine.putPage('notes/stale', { type: 'note', title: 'Stale', compiled_truth: 'Old body.' }, { sourceId: 'notes-git' });
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='notes-git' AND slug='notes/stale'");
+ const notes = await incarnationOf(engine, 'notes-git');
+ await writeGitHold(engine, hold('notes-git', notes, 'notes/stale.md', { page_id: Number(page.id) }));
+ await writeGitHold(engine, hold('notes-git', notes, 'notes/huge.md', { code: 'file_too_large', message: 'File too large (12 MB).', upstream_version: null,
+ meta: { recovery_version: 1 } }));
+ await writeGitHold(engine, hold('other-git', await incarnationOf(engine, 'other-git'), 'other/a.md'));
+ }, 120_000);
+
+ afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);
+
+ test('sources status <id> --json lists only that source, with its held files and their X2 fields', async () => {
+ const doc = JSON.parse(await captured(() => runSources(engine, ['status', 'notes-git', '--json'])));
+ expect(doc.sources.map((s: { source_id: string }) => s.source_id)).toEqual(['notes-git']);
+ const holds = doc.sources[0].git_holds;
+ expect(holds).toMatchObject({ count: 2, sync_argv: ['gbrain', 'sync', '--source', 'notes-git'] });
+ expect(holds.truncated).toBeUndefined();
+ const byPath = Object.fromEntries(holds.items.map((item: { path: string }) => [item.path, item]));
+ expect(byPath['notes/stale.md']).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2, stale: true,
+ docs: 'docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation',
+ fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', 'notes-git', '--include-ambiguous'] } });
+ expect(typeof byPath['notes/stale.md'].held_since).toBe('string');
+ expect(byPath['notes/huge.md']).toMatchObject({ code: 'file_too_large', stale: false, docs: 'docs/guides/write-refusals.md#file_too_large' });
+ expect(byPath['notes/huge.md'].fix.why).toContain('size limit is fixed');
+
+ const all = JSON.parse(await captured(() => runSources(engine, ['status', '--json'])));
+ expect(all.sources.find((s: { source_id: string }) => s.source_id === 'other-git').git_holds.count).toBe(1);
+ expect(all.sources.find((s: { source_id: string }) => s.source_id === 'default').git_holds).toBeUndefined();
+ });
+
+ test('sources status <id> text names each held file, its next step and the re-screen commands; other sources are not listed', async () => {
+ const text = await captured(() => runSources(engine, ['status', 'notes-git']));
+ expect(text).toContain('notes-git: 2 held file(s): not imported, and they do not block sync.');
+ expect(text).toContain('read-only for put_page until the file is repaired');
+ expect(text).toMatch(/Held notes\/stale\.md: invalid_frontmatter \(needs_interpretation\) at line 2, key "title"; .* Next: gbrain repair frontmatter --source notes-git --include-ambiguous/);
+ expect(text).toMatch(/Held notes\/huge\.md: file_too_large; its page is missing until the file imports\. Next: gbrain config get sync\.exclude/);
+ expect(text).toContain('Most holds re-screen on the next sync by themselves');
+ expect(text).toContain('gbrain sync --source notes-git');
+ expect(text).toContain('gbrain sources retry-held notes-git');
+ expect(text).not.toContain('other-git');
+ });
+
+ test('sources status <unknown id> refuses with not_found and the list command', async () => {
+ await expect(runSources(engine, ['status', 'missing-src'])).rejects.toMatchObject({ code: 'not_found',
+ fix: { argv: ['gbrain', 'sources', 'list', '--json'] } });
+ });
+
+ test('retry-held on a Git source: --dry-run changes nothing; the real run records a re-screen of every held path', async () => {
+ const dry = await retryHeld(engine, 'notes-git', { dryRun: true });
+ expect(dry).toMatchObject({ kind: 'git', dry_run: true, scheduled: 0, fix: { argv: ['gbrain', 'sources', 'retry-held', 'notes-git'] } });
+ expect(dry.items.map(item => [item.key, item.action])).toEqual([['notes/huge.md', 'would_retry'], ['notes/stale.md', 'would_retry']]);
+ expect(await readGitHoldRetryPaths(engine, 'notes-git', await incarnationOf(engine, 'notes-git'))).toEqual([]);
+
+ const text = await captured(() => runRetryHeld(engine, ['notes-git']));
+ expect(text).toContain('notes/stale.md (invalid_frontmatter, needs_interpretation): retry_scheduled');
+ expect(text).toContain('2 held file(s) scheduled for a re-screen; none has run yet.');
+ expect(text).toContain('Most holds re-screen on the next sync by themselves');
+ expect(text).toContain('Run it now with: gbrain sync --source notes-git,');
+ expect(text).toContain('gbrain repair frontmatter --source notes-git');
+ expect((await readGitHoldRetryPaths(engine, 'notes-git', await incarnationOf(engine, 'notes-git'))).sort()).toEqual(['notes/huge.md', 'notes/stale.md']);
+
+ const json = JSON.parse(await captured(() => runRetryHeld(engine, ['notes-git', '--json'])));
+ expect(json).toMatchObject({ source_id: 'notes-git', kind: 'git', scheduled: 2, fix: { argv: ['gbrain', 'sync', '--source', 'notes-git'] } });
+ expect((await retryHeld(engine, 'notes-git', { dryRun: true })).items.every(item => item.action === 'retry_scheduled')).toBe(true);
+ expect((await retryHeld(engine, 'default')).next_action).toBe('No held files for default.');
+ });
+});
+
+describe('gbrain sync --retry-held', () => {
+ test('is refused with a typed error pointing at sources retry-held', () => {
+ expect(CLI_FLAG_REGISTRY.sync).toContain('--retry-held');
+ let error: any;
+ try { parseSyncFlags(['--retry-held', '--source', 'notes-git']); } catch (e) { error = e; }
+ expect(error).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'retry-held', 'notes-git'],
+ verify: { argv: ['gbrain', 'sources', 'status', 'notes-git', '--json'] } } });
+ expect(error.message).toContain('no --retry-held flag');
+ expect(error.suggestion).toContain('gbrain sources retry-held notes-git');
+ try { parseSyncFlags(['--retry-held']); } catch (e) { error = e; }
+ expect(error.fix.argv).toEqual(['gbrain', 'sources', 'retry-held', '<source-id>']);
+ expect(error.fix.inputs).toEqual([expect.objectContaining({ name: 'source-id' })]);
+ });
+});
+
+describe('a page whose file is held refuses put_page naming the hold', () => {
+ let engine: PGLiteEngine;
+ let home: string;
+ let root: string;
+ let worktreeId: string;
+ const sourceId = 'held-drift';
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-held-drift-'));
+ root = join(home, 'source'); mkdirSync(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ worktreeId = (await claimWorktree(engine, sourceId, root)).worktree_id;
+ }, 60_000);
+ afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);
+
+ async function seed(slug: string) {
+ await engine.putPage(slug, { type: 'note', title: 'Held', compiled_truth: 'Last good body' }, { sourceId });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [`${slug}.md`, sourceId, slug]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const file = join(root, `${slug}.md`);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));
+ return { snapshot, file, row: { source_id: sourceId, worktree_id: worktreeId, slug } };
+ }
+
+ test('drift over a held file names the hold, keeps file_database_drift, and points at repair instead of reconcile', async () => {
+ const { snapshot, file, row } = await seed('notes/held');
+ writeFileSync(file, readFileSync(file, 'utf8').replace(/^title:.*$/m, 'title: Broken\n continued tweet text'));
+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ detail: 'file_database_drift',
+ suggestion: expect.stringContaining('gbrain sources reconcile') });
+ await writeGitHold(engine, hold(sourceId, await incarnationOf(engine, sourceId), 'notes/held.md', { page_id: Number(snapshot.page.id) }));
+ let error: any;
+ try { await prepareFileTarget(engine, row, snapshot, 'Replacement'); } catch (e) { error = e; }
+ expect(error).toMatchObject({ code: 'source_changed', detail: 'file_database_drift', message: heldFileMessage('drift', 'invalid_frontmatter'),
+ fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', sourceId, '--include-ambiguous'] } });
+ expect(error.suggestion).toContain('Sync holds notes/held.md in source held-drift (invalid_frontmatter, needs_interpretation at line 2, key "title")');
+ expect(error.suggestion).toContain('read-only for put_page until the file is repaired');
+ expect(error.suggestion).not.toContain('sources reconcile');
+ expect(error.message).not.toContain('continued tweet text');
+ });
+
+ test('an unindexed held file occupying a new page path names the hold', async () => {
+ const file = join(root, 'notes', 'new-held.md');
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, '---\ntitle: Broken\n continued\n---\nBody\n');
+ const row = { source_id: sourceId, worktree_id: worktreeId, slug: 'notes/new-held' };
+ await expect(prepareFileTarget(engine, row, null, 'Rendered')).rejects.toMatchObject({ message: 'An unindexed file already occupies the canonical page path.' });
+ await writeGitHold(engine, hold(sourceId, await incarnationOf(engine, sourceId), 'notes/new-held.md'));
+ await expect(prepareFileTarget(engine, row, null, 'Rendered')).rejects.toMatchObject({ code: 'source_changed',
+ message: heldFileMessage('occupied', 'invalid_frontmatter'), suggestion: expect.stringContaining('does not exist yet') });
+ });
+
+ test('receipts keep only the location-free message; the diagnostic maps it to the same reasons with the repair command', () => {
+ expect(writeFailureDiagnostic('source_changed', heldFileMessage('drift', 'invalid_frontmatter'))).toMatchObject({ reason: 'file_database_drift',
+ message: heldFileMessage('drift', 'invalid_frontmatter'), suggestion: expect.stringContaining('gbrain repair frontmatter --source <source>') });
+ const occupied = writeFailureDiagnostic('source_changed', heldFileMessage('occupied', 'file_too_large'));
+ expect(occupied.reason).toBe('canonical_path_occupied');
+ expect(occupied.suggestion).toContain('refuses put_page until the file is repaired');
+ expect(writeFailureDiagnostic('source_changed', 'The canonical file contains an uncoordinated local edit.').suggestion).toContain('gbrain sources reconcile');
+ });
+});
+
+describe('Git holds and writer mode changes (X14)', () => {
+ const gmailConfig = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+ const admin = (engine: BrainEngine, operation: string, params: Record<string, unknown> = {}) =>
+ runPersistenceAdministration(engine, operation as never, params) as Promise<Record<string, any>>;
+
+ test('holds survive activation, never block deactivation, and survive it unchanged; uncarriable connector holds still block', () => managedBrain(async ({ engine, ctx, root }) => {
+ const incarnation = await incarnationOf(engine, 'default');
+ const before = await readGitHold(engine, 'default', incarnation, 'notes/held.md');
+ expect(before).toMatchObject({ path: 'notes/held.md', code: 'invalid_frontmatter' });
+
+ // A managed brain re-screens with --no-pull.
+ expect((await retryHeld(engine, 'default', { dryRun: true })).fix?.argv).toEqual(['gbrain', 'sources', 'retry-held', 'default']);
+ expect((await retryHeld(engine, 'default')).fix?.argv).toEqual(['gbrain', 'sync', '--source', 'default', '--no-pull']);
+
+ // A held page refuses put_page through the coordinated write path with the hold named.
+ await put(ctx, 'notes/held', 'Last good body.');
+ writeFileSync(join(root, 'notes', 'held.md'), '---\ntitle: Broken\n continued tweet text\n---\n\nNewer body.\n');
+ const current = (await engine.readPageSnapshot('notes/held', { sourceId: 'default' }))!;
+ const refused = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/held', request_id: randomUUID(), expected_revision: current.revision,
+ content: '---\ntype: note\ntitle: notes/held\n---\n\nAgent edit.\n' } }).then(() => null, (e: unknown) => e as Record<string, any>);
+ expect(refused).not.toBeNull();
+ const suggestion = String(refused!.suggestion);
+ expect(suggestion).toContain('gbrain repair frontmatter --source default');
+ expect(suggestion).toContain('retrying this write refuses the same way');
+ expect(refused).toMatchObject({ code: 'source_changed', detail: 'file_database_drift', message: heldFileMessage('drift', 'invalid_frontmatter') });
+ expect(JSON.stringify(refused)).not.toContain('sources reconcile');
+
+ const gmailIncarnation = await incarnationOf(engine, 'gmail-x');
+ const key = connectorCheckpointKey('gmail-x', gmailIncarnation, connectorIdentity('google', gmailConfig, null));
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector',$1,$2::text::jsonb)`,
+ [key, JSON.stringify([{ state: { history_id: 'h1', item_holds: carryLegacyFailCounts(undefined, { 'thread-1': 3 }, id => id, '2026-10-01T00:00:00.000Z') } }])]);
+
+ const dry = await admin(engine, 'writer_deactivate', { dry_run: true });
+ expect(dry.blockers.map((b: { kind: string; source_id?: string }) => `${b.kind}:${b.source_id ?? ''}`)).toEqual(['connector_holds:gmail-x']);
+ await expect(admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine) }))
+ .rejects.toMatchObject({ code: 'writer_not_quiesced' });
+
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [key]);
+ const done = await admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine) });
+ expect(done).toMatchObject({ mode: 'classic', deactivated: true, blockers: [] });
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/held.md')).toEqual(before);
+ expect((await readGitHoldRetryPaths(engine, 'default', incarnation))).toEqual(['notes/held.md']);
+ // Classic mode re-screens with plain sync.
+ expect((await retryHeld(engine, 'default')).fix?.argv).toEqual(['gbrain', 'sync', '--source', 'default']);
+ }, { setup: async ({ engine }) => {
+ await engine.executeRaw('INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::text::jsonb)', ['gmail-x', JSON.stringify(gmailConfig)]);
+ await writeGitHold(engine, hold('default', await incarnationOf(engine, 'default'), 'notes/held.md', { run_id: randomUUID() }));
+ } }), 180_000);
+});