Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(projections): bound the claimable-write probe, keep the selected brain and restart the owner in drain steps (#5401)
garrytane17cc0b79e3b
diff --git a/llms-full.txt b/llms-full.txtindex 9738742f77..a64168fb88 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9183,7 +9183,7 @@ of making a duplicate.| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). || unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. || <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A slug containing `:` cannot be written through to a file on Windows. | Write it on a non-Windows host, or choose a slug without `:`. |-| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). | Check which key is in effect and replace it. |+| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |### Other error codesdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 94734cd684..1a59b27826 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3161 ratchet +1 fix wave 5 (#5401): projections drain help line; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts)+src/cli.ts 3162 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts)src/commands/autopilot.ts 1633 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.tssrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2187 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pagesdiff --git a/src/cli.ts b/src/cli.tsindex fd72ec9400..fb1eb16d2a 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1880,6 +1880,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',+ projections: 'projections drain rebuilds text projections against the local engine. Run `gbrain projections drain` on the brain host.',quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',};diff --git a/src/cli/commands/projections.ts b/src/cli/commands/projections.tsindex 53b760e93c..18fba7f75a 100644--- a/src/cli/commands/projections.ts+++ b/src/cli/commands/projections.ts@@ -45,7 +45,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<voidconst config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());if (config?.engine === 'pglite' && config.database_path && !config.database_url) {const holder = inspectLockHolder(config.database_path);- if (holder.held) { await refuse(projections.projectionOwnerResidentError(holder, config.database_path)); return; }+ if (holder.held) { await refuse(projections.projectionOwnerResidentError(holder, config.database_path, brainId)); return; }}const { createProgress } = await import('../../core/progress.ts');diff --git a/src/commands/doctor/checks/projection-readiness.ts b/src/commands/doctor/checks/projection-readiness.tsindex fe8c39a20a..c58a58ea00 100644--- a/src/commands/doctor/checks/projection-readiness.ts+++ b/src/commands/doctor/checks/projection-readiness.ts@@ -63,8 +63,9 @@ async function runProjectionResident(ctx: DoctorContext): Promise<Check[]> {const { persistenceSocketPathForConfig, requestPersistenceProjectionStatus } = await import('../../../core/persistence/ipc.ts');const { residentDrainSteps } = await import('../../projections.ts');let config: ReturnType<typeof persistenceConfigForBrain>;+ let brainId: string;try {- const brainId = resolveBrainId(getCliOptions().brain, process.cwd());+ brainId = resolveBrainId(getCliOptions().brain, process.cwd());config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());} catch { return checks; }if (config?.engine !== 'pglite' || !config.database_path || config.database_url) return checks;@@ -75,7 +76,7 @@ async function runProjectionResident(ctx: DoctorContext): Promise<Check[]> {if (socketPath) {try { status = await requestPersistenceProjectionStatus(socketPath); } catch { /* an older resident, or none listening */ }}- checks.push({ name: 'text_projection_readiness', ...residentProjectionReadiness(holder.pid, status, residentDrainSteps(holder.pid)) });+ checks.push({ name: 'text_projection_readiness', ...residentProjectionReadiness(holder.pid, status, residentDrainSteps(holder.pid, brainId)) });return checks;}diff --git a/src/commands/projections.ts b/src/commands/projections.tsindex 345e69a098..b65552f450 100644--- a/src/commands/projections.ts+++ b/src/commands/projections.ts@@ -91,26 +91,32 @@ export function projectionFailureNextAction(failure: ProjectionRebuildFailure):return 'run `gbrain doctor`; the page stays queued and `gbrain projections drain` tries it again on its next run';}-/** Stop, drain and restart commands for each way a resident owner can run. */-export function residentDrainSteps(pid: number | undefined): string {+/**+ * Stop, drain and restart commands for each way a resident owner can run. The+ * restart runs whether or not a page failed, so a drain exit of 1 never leaves+ * the owner stopped. `brain` keeps a mounted brain selected in every command.+ */+export function residentDrainSteps(pid: number | undefined, brain = 'host'): string {const uid = '$(id -u)';+ const drain = `gbrain projections drain${brain === 'host' ? '' : ` --brain ${brain}`}`;+ const cycle = (stop: string, start: string) => `${stop} && { ${drain}; ${start}; }`;return [`To drain faster, stop the owner, drain, then restart it:`,- ` gbrain serve service (launchd): launchctl bootout gui/${uid}/${SERVE_LAUNCHD_LABEL} && gbrain projections drain && launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${SERVE_LAUNCHD_LABEL}.plist`,- ` gbrain serve service (systemd): systemctl --user stop ${SERVE_SYSTEMD_UNIT} && gbrain projections drain && systemctl --user start ${SERVE_SYSTEMD_UNIT}`,- ` autopilot (launchd): launchctl bootout gui/${uid}/${autopilotLaunchdLabel()} && gbrain projections drain && launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${autopilotLaunchdLabel()}.plist`,- ` autopilot (systemd): systemctl --user stop ${AUTOPILOT_SYSTEMD_UNIT} && gbrain projections drain && systemctl --user start ${AUTOPILOT_SYSTEMD_UNIT}`,- ` a manual gbrain serve: stop it${pid ? ` (kill ${pid})` : ''}, run gbrain projections drain, then start gbrain serve again`,+ ` serve service (launchd): ${cycle(`launchctl bootout gui/${uid}/${SERVE_LAUNCHD_LABEL}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${SERVE_LAUNCHD_LABEL}.plist`)}`,+ ` serve service (systemd): ${cycle(`systemctl --user stop ${SERVE_SYSTEMD_UNIT}`, `systemctl --user start ${SERVE_SYSTEMD_UNIT}`)}`,+ ` autopilot (launchd): ${cycle(`launchctl bootout gui/${uid}/${autopilotLaunchdLabel()}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${autopilotLaunchdLabel()}.plist`)}`,+ ` autopilot (systemd): ${cycle(`systemctl --user stop ${AUTOPILOT_SYSTEMD_UNIT}`, `systemctl --user start ${AUTOPILOT_SYSTEMD_UNIT}`)}`,+ ` a manual gbrain serve: stop it${pid ? ` (kill ${pid})` : ''}, run ${drain}, then start gbrain serve again`,].join('\n');}/** DX-O5 refusal: the drain did not run because a resident process holds this PGLite brain. */-export function projectionOwnerResidentError(holder: LockHolderInfo, dataDir: string): OperationError {+export function projectionOwnerResidentError(holder: LockHolderInfo, dataDir: string, brain = 'host'): OperationError {const owner = `${holder.subcommand ? `gbrain ${holder.subcommand}` : 'a gbrain process'}${holder.pid ? ` (pid ${holder.pid})` : ''}`;return catalogueError('projection_owner_resident',`The PGLite brain at ${dataDir} is held by ${owner}, so the drain did not run.`,[- `The upgraded resident drains queued projections itself (up to 100 pages per pass, fewer while writes wait); watch the pending count with \`gbrain doctor\` (text_projection_readiness).`,- residentDrainSteps(holder.pid),+ `The upgraded resident drains queued projections itself (up to 100 pages per pass, fewer while writes wait); watch the pending count with \`gbrain doctor${brain === 'host' ? '' : ` --brain ${brain}`}\` (text_projection_readiness).`,+ residentDrainSteps(holder.pid, brain),].join('\n'));}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1a2d06fa70..2ac2490789 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex e164f06283..d99307321c 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -21,8 +21,11 @@ export const RESIDENT_PROJECTION_PAGES = 100;export const RESIDENT_PROJECTION_BUDGET_MS = 250;export const WRITE_WAITING_PROJECTION_PAGES = 2;-export async function runResidentProjectionInvocation(engine: BrainEngine, hostId: string, excludeRoots: string[], now: () => number = Date.now) {- const writesWaiting = publicationConcurrency(engine) > 0 && await hasClaimableWrite(engine, hostId, excludeRoots);+export async function runResidentProjectionInvocation(engine: BrainEngine, hostId: string, excludeRoots: string[],+ now: () => number = Date.now, signal?: AbortSignal) {+ // Advisory and bounded by the caller's signal: a probe that cannot answer+ // (for example behind a table lock) counts as a waiting write.+ const writesWaiting = publicationConcurrency(engine) > 0 && await hasClaimableWrite(engine, hostId, excludeRoots, signal).catch(() => true);return rebuildPendingPageProjections(engine, writesWaiting ? WRITE_WAITING_PROJECTION_PAGES : RESIDENT_PROJECTION_PAGES,{ deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now, retryCooldown: true });}@@ -257,7 +260,8 @@ export class PersistenceConsumer {.finally(() => { this.maintenanceWorker = undefined; });}if (!this.projectionWorker) this.projectionWorker = runResidentProjectionInvocation(this.engine, this.hostId,- [...this.activeRoots, ...this.rootRetryAfter.keys()])+ [...this.activeRoots, ...this.rootRetryAfter.keys()], Date.now, this.engine.kind === 'postgres'+ ? AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.opts.phaseMs ?? 5000)]) : undefined).catch(error => this.report(error)).finally(() => { this.projectionWorker = undefined; });// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,// proves that a previous process can no longer be publishing this root.diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 3374674492..268d15d482 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -197,9 +197,9 @@ export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULLAND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))`;/** #5401: whether `claimNextWrite` would find a row now. Read-only: no lock and no claim. */-export async function hasClaimableWrite(engine: SqlEngine, hostId: string, excludeRoots: string[] = []): Promise<boolean> {+export async function hasClaimableWrite(engine: SqlEngine, hostId: string, excludeRoots: string[] = [], signal?: AbortSignal): Promise<boolean> {const [row] = await engine.executeRaw<{ claimable: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r- LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${CLAIMABLE_WRITE_SQL} LIMIT 1) AS claimable`, [hostId, excludeRoots]);+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${CLAIMABLE_WRITE_SQL} LIMIT 1) AS claimable`, [hostId, excludeRoots], { signal });return row?.claimable === true;}diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 9a5e3aee69..04ccea0843 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -1108,6 +1108,25 @@"thinClient": "none","thinClientRoutedSubcommands": []},+ "projections": {+ "hasSwitchCase": false,+ "phase": "pre-connect-own-engine",+ "preConnectRules": [+ {+ "condition": "command === 'projections'",+ "connectsEngine": true,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": [+ "projections"+ ]+ }+ ],+ "thinClient": "refuse",+ "thinClientRoutedSubcommands": []+ },"protocol": {"hasSwitchCase": false,"phase": "pre-connect",@@ -1807,6 +1826,16 @@"thinClientCheck": false,"unconditionalFor": []},+ {+ "commands": [],+ "condition": "command !== 'hook'",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": false,+ "thinClientCheck": false,+ "unconditionalFor": []+ },{"commands": ["ask"diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex c81055b782..3ac9d41398 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -25,6 +25,7 @@" upgrade Self-update"," check-update [--json] Check for new versions"," repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",+ " projections drain [--limit n] Rebuild queued text projections now [--json]"," doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)"," integrations [subcommand] Manage integration recipes (senses + reflexes)","",@@ -230,6 +231,7 @@" upgrade Self-update"," check-update [--json] Check for new versions"," repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",+ " projections drain [--limit n] Rebuild queued text projections now [--json]"," doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)"," integrations [subcommand] Manage integration recipes (senses + reflexes)","",@@ -435,6 +437,7 @@" upgrade Self-update"," check-update [--json] Check for new versions"," repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",+ " projections drain [--limit n] Rebuild queued text projections now [--json]"," doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)"," integrations [subcommand] Manage integration recipes (senses + reflexes)","",diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex 2bfc9201ee..2db3c0b660 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -152,6 +152,7 @@"pages","pglite-repair","post-upgrade",+ "projections","protocol","providers","publish",@@ -235,6 +236,7 @@"pages","pglite-repair","post-upgrade",+ "projections","protocol","reindex","reinit-pglite",@@ -302,6 +304,7 @@"migrate","orphans","pages",+ "projections","repair","repair-jsonb","retrieval-upgrade",@@ -338,6 +341,7 @@"migrate","orphans","pages",+ "projections","quarantine","repair","repair-jsonb",diff --git a/test/projection-resident-doctor.test.ts b/test/projection-resident-doctor.test.tsindex da3fb4858b..44068517af 100644--- a/test/projection-resident-doctor.test.ts+++ b/test/projection-resident-doctor.test.ts@@ -71,7 +71,7 @@ test('doctor reports the resident backlog, its pid and the stop-drain-restart paexpect(draining[0]).toMatchObject({ name: 'text_projection_readiness', status: 'warn',details: { readiness: 'projection_pending', ready: false, pending: 3, failed: 0, owner_pid: process.pid } });expect(draining[0].message).toContain(`(pid ${process.pid}) holds this PGLite brain and is draining 3 queued text projections`);- expect(draining[0].message).toContain('systemctl --user stop gbrain-serve.service && gbrain projections drain');+ expect(draining[0].message).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }');expect(draining[0].message).toContain(`kill ${process.pid}`);const silent = await runEntry(doctorContext());diff --git a/test/projections-drain-cli.serial.test.ts b/test/projections-drain-cli.serial.test.tsindex 357cb89ea3..1b2763a201 100644--- a/test/projections-drain-cli.serial.test.ts+++ b/test/projections-drain-cli.serial.test.ts@@ -95,7 +95,7 @@ describe('gbrain projections drain', () => {expect(human.stderr).toContain('Error [projection_owner_resident]');expect(human.stderr).toContain(`(pid ${process.pid}), so the drain did not run.`);expect(human.stderr).toContain('watch the pending count with `gbrain doctor` (text_projection_readiness)');- expect(human.stderr).toContain('systemctl --user stop gbrain-serve.service && gbrain projections drain && systemctl --user start gbrain-serve.service');+ expect(human.stderr).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }');const json = await runCli(['projections', 'drain', '--json'], { home: healthyHome, timeoutMs: 30_000 });expect(json.exitCode).toBe(2);expect(JSON.parse(json.stdout)).toMatchObject({ error: 'projection_owner_resident', docs: 'docs/guides/repair.md#projection-owner-resident' });@@ -108,6 +108,8 @@ describe('gbrain projections drain', () => {const refused = await runCli(['projections', 'drain', '--brain', 'team-a'], { home: mountedHome, timeoutMs: 30_000 });expect(refused.exitCode).toBe(2);expect(refused.stderr).toContain(`The PGLite brain at ${join(mountedHome, 'team-a.pglite')} is held by`);+ expect(refused.stderr).toContain('`gbrain doctor --brain team-a`');+ expect(refused.stderr).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain --brain team-a; systemctl --user start gbrain-serve.service; }');} finally { await releaseLock(lock); }}, 120_000);});diff --git a/test/shared-skills-writer-boundary.serial.test.ts b/test/shared-skills-writer-boundary.serial.test.tsindex cd563676cb..8eb0aedaed 100644--- a/test/shared-skills-writer-boundary.serial.test.ts+++ b/test/shared-skills-writer-boundary.serial.test.ts@@ -19,6 +19,7 @@ import { importFromContent } from '../src/core/import-file.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer, writeResponse } from '../src/core/persistence/service.ts';+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';import { adoptSharedSkillpack } from '../src/core/shared-skills/publication.ts';import { setSharedSkillPolicy } from '../src/core/shared-skills/policy.ts';import { assertKnowledgePublicationAllowed } from '../src/core/shared-skills/knowledge-guard.ts';@@ -140,6 +141,9 @@ test('unresolvable stored file aliases fail closed with a metadata diagnostic inconst [page] = await f.engine.executeRaw<{ source_uri: string }>('SELECT source_uri FROM pages WHERE source_id=$1 AND slug=$2', ['default', row.slug]);expect(page.source_uri).toBe('file:///notes/%2F.md');+ // The running resident drains queued projections in the background (#5401);+ // finish that first so the snapshot below compares canonical state only.+ while ((await rebuildPendingPageProjections(f.engine, 100)).rebuilt > 0) { /* drain */ }const snapshot = await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' });await expect(submitPageMutation(f.ctx, { operation: 'put_page', params: {slug: row.slug, content: note, request_id: randomUUID(), expected_revision: snapshot!.revision,