Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(cli): gbrain projections drain with named exits (#5401)
garrytanb7a2978a57bf
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 026437d0de..3ea4cd9b3e 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -52,6 +52,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.+- `src/commands/projections.ts` + `src/cli/commands/projections.ts` — `gbrain projections drain [--limit <n>] [--json]` (#5401). Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried); `--limit` caps pages tried. Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or `projection_owner_resident` when a process holds the selected PGLite brain, checked with `persistenceConfigForBrain` before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). `residentDrainSteps` gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: `projection-drain.test.ts` (both engines via `test/e2e/projection-drain-postgres.test.ts`), `projections-drain-cli.serial.test.ts`.- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`. Resident-delegated embedding requires explicit --yes; --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 26527e0240..03d1c20b72 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -31,6 +31,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/persistence/orphan-bindings.ts": ["test/e2e/sources-remove-bindings.test.ts"],// Fix wave 5 shared commit: preview-bound approved sets in op_checkpoints."src/core/persistence/preview-approval.ts": ["test/e2e/preview-approval-postgres.test.ts"],+ // Fix wave 5 #5401: projection drain CLI and the budgeted resident drain.+ "src/commands/projections.ts": ["test/e2e/projection-drain-postgres.test.ts"],+ "src/core/persistence/consumer.ts": ["test/e2e/projection-drain-postgres.test.ts"],+ "src/core/persistence/journal.ts": ["test/e2e/projection-drain-postgres.test.ts"],"src/core/persistence/deactivation.ts": ["test/e2e/persistence-deactivate-race.test.ts", "test/e2e/fix-wave-4-integration.test.ts"],// SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger."src/core/skillopt/**": [@@ -103,7 +107,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/search-exclude.test.ts","test/e2e/search-swamp.test.ts",],- "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],+ "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-drain-postgres.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],"src/core/embedding-input-hash.ts": ["test/e2e/projection-embedding-input-hash.test.ts"],// Evidence delivery (return_unit): the release-gate leak canaries and the// engine / product-path parity suite.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex dee1654df5..a595f5e7ab 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 3158 ratchet +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 3159 ratchet +1 fix wave 5 (#5401): projections drain help line; +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 37f90faeb1..069c79db18 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2900,6 +2900,7 @@ SETUPupgrade Self-updatecheck-update [--json] Check for new versionsrepair [<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/src/cli/command-table.ts b/src/cli/command-table.tsindex 86fba5fedb..aa7eea42a7 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -182,6 +182,9 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// System One decide: local CLI only (calibrate, receipts and proposals are trusted-local); help and a// key-only probe answer without a brain, so the module opens its own engine.{ name: 'decide', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/decide.ts') },+ // #5401: projections drain refuses a resident-held PGLite brain before any engine opens, so the+ // module opens its own engine. Trusted local CLI only (not an operation).+ { name: 'projections', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/projections.ts') },// Dispatched by handleCliOnly's explicit deferred-persistence step (never by the table step).// selfHelp: v0.39.3.0 WARN-5: capture's detailed HELP constant (src/commands/capture.ts:90+) wasdiff --git a/src/cli/commands/projections.ts b/src/cli/commands/projections.tsnew file mode 100644index 0000000000..53b760e93c--- /dev/null+++ b/src/cli/commands/projections.ts@@ -0,0 +1,74 @@+/**+ * `gbrain projections drain`: pre-connect dispatch that opens its own engine,+ * so the PGLite resident-owner refusal (#5401, exit 2) happens before any+ * engine opens. The record lives in src/cli/command-table.ts.+ */+import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';+import type { CliDispatchContext } from '../command-table.ts';++export async function run(args: string[], ctx: CliDispatchContext): Promise<void> {+ const projections = await import('../../commands/projections.ts');+ if (args.length === 0 || args.includes('--help') || args.includes('-h')) {+ console.log(projections.PROJECTIONS_HELP);+ return;+ }+ const json = args.includes('--json');+ const { OperationError } = await import('../../core/ops/contract.ts');+ const { reportPersistenceCliError } = await import('../../commands/persistence-delegate.ts');+ const refuse = async (error: InstanceType<typeof OperationError>) => {+ await reportPersistenceCliError(error, json);+ setCliExitVerdict(2);+ };+ const limitAt = args.indexOf('--limit');+ const limitValue = limitAt === -1 ? undefined : args[limitAt + 1];+ const known = new Set(['drain', '--json', '--limit', ...(limitValue === undefined ? [] : [limitValue])]);+ const unknown = args.find(arg => !known.has(arg));+ if (args[0] !== 'drain' || unknown !== undefined) {+ await refuse(new OperationError('invalid_params', `Unknown projections argument '${unknown ?? args[0]}'.`,+ 'Run `gbrain projections drain [--limit <n>] [--json]`.', projections.PROJECTION_DRAIN_DOCS));+ return;+ }+ const limit = limitValue === undefined ? undefined : Number(limitValue);+ if (limitAt !== -1 && (!Number.isSafeInteger(limit) || limit! < 1)) {+ await refuse(new OperationError('invalid_params', `--limit needs a positive whole number of pages, not '${limitValue ?? ''}'.`,+ 'Run `gbrain projections drain --limit 1000`, or omit --limit to drain everything queued.', projections.PROJECTION_DRAIN_DOCS));+ return;+ }++ const { loadConfig } = await import('../../core/config.ts');+ const { getCliOptions } = await import('../../core/cli-options.ts');+ const { resolveBrainId } = await import('../../core/brain-resolver.ts');+ const { loadMounts } = await import('../../core/brain-registry.ts');+ const { persistenceConfigForBrain } = await import('../../core/persistence/local-client.ts');+ const { inspectLockHolder } = await import('../../core/pglite-lock.ts');+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());+ const 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; }+ }++ const { createProgress } = await import('../../core/progress.ts');+ const { cliOptsToProgressOptions } = await import('../../core/cli-options.ts');+ const engine = await ctx.connectEngine();+ try {+ const result = await projections.drainProjections(engine, { limit, progress: createProgress(cliOptsToProgressOptions(getCliOptions())) });+ if (json) {+ const { limited: _limited, ...payload } = result;+ await writeStdoutFinal(JSON.stringify(payload) + '\n');+ } else {+ for (const failure of result.failed) {+ console.error(`failed: ${failure.source_id}/${failure.slug}: ${failure.reason}\n next: ${projections.projectionFailureNextAction(failure)}`);+ }+ const summary = `projections drain: ${result.rebuilt} rebuilt, ${result.superseded} superseded, ${result.failed.length} failed, ${result.remaining} remaining.`;+ const tail = result.remaining === 0 ? ' The projection backlog is empty.'+ : result.limited ? ` Stopped at --limit ${limit}; run \`gbrain projections drain\` again to continue.`+ : result.failed.length ? ' Failed pages stay queued; fix them as shown above, then run `gbrain projections drain` again.'+ : ' Rows queued during this run are left for the next run or the resident owner.';+ await writeStdoutFinal(summary + tail + '\n');+ }+ if (result.failed.length) setCliExitVerdict(1);+ } finally {+ await finishCliTeardown({ engine });+ }+}diff --git a/src/commands/projections.ts b/src/commands/projections.tsnew file mode 100644index 0000000000..345e69a098--- /dev/null+++ b/src/commands/projections.ts@@ -0,0 +1,116 @@+/**+ * `gbrain projections drain` (#5401): rebuilds queued Markdown and code text+ * projections in-process, in batches of up to 100, until every row queued+ * before the run started has been tried once. Trusted local CLI only; it is not+ * an operation, so MCP and remediation cannot run it.+ *+ * Postgres: safe beside a resident owner, because each page is rebuilt under+ * its page lock with a revision recheck. PGLite: a resident owner holds the+ * datastore, so the command refuses before opening the engine and the+ * resident drains the backlog itself.+ */+import type { BrainEngine } from '../core/engine.ts';+import type { OperationError } from '../core/ops/contract.ts';+import { catalogueError } from '../core/error-catalogue.ts';+import type { LockHolderInfo } from '../core/pglite-lock.ts';+import type { ProgressReporter } from '../core/progress.ts';+import {+ projectionBacklog, rebuildPendingPageProjections, type ProjectionRebuildFailure,+} from '../core/page-state/projections.ts';+import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';+import { AUTOPILOT_SYSTEMD_UNIT } from './autopilot.ts';+import { autopilotLaunchdLabel } from '../core/autopilot-paths.ts';++export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';+const BATCH = 100;++export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--limit <n>] [--json]++Rebuild queued Markdown and code text projections now, in batches of up to 100,+until every row queued before the run started has been tried once.++ --limit <n> Try at most n pages in this run (default: no cap)+ --json Print {rebuilt, superseded, failed, remaining} to stdout++Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run+(projection_owner_resident: a resident gbrain process holds this PGLite brain+and drains it itself).++On Postgres the drain is safe while \`gbrain serve\` runs. Progress goes to stderr.+Docs: ${PROJECTION_DRAIN_DOCS}+`;++export interface ProjectionDrainResult {+ rebuilt: number;+ superseded: number;+ failed: ProjectionRebuildFailure[];+ remaining: number;+ limited: boolean;+}++export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter } = {}): Promise<ProjectionDrainResult> {+ const [{ runStart }] = await engine.executeRaw<{ runStart: string }>('SELECT now()::text AS "runStart"');+ // PGLite's clock can be coarse: wait until it passes the run start, so a page+ // that fails in this run is stamped after it and is not tried again.+ while (!(await engine.executeRaw<{ passed: boolean }>('SELECT now()>$1::text::timestamptz AS passed', [runStart]))[0]?.passed) {+ await new Promise(resolve => setTimeout(resolve, 1));+ }+ const total = (await projectionBacklog(engine)).pending;+ opts.progress?.start('projections.drain', opts.limit === undefined ? total : Math.min(total, opts.limit));+ const failed: ProjectionRebuildFailure[] = [];+ let rebuilt = 0;+ let superseded = 0;+ let tried = 0;+ try {+ while (opts.limit === undefined || tried < opts.limit) {+ const failuresBefore = failed.length;+ const batch = await rebuildPendingPageProjections(engine, Math.min(BATCH, (opts.limit ?? Infinity) - tried),+ { notAfter: runStart, onFailure: failure => failed.push(failure) });+ const attempted = batch.rebuilt + batch.superseded + failed.length - failuresBefore;+ if (attempted === 0) break;+ rebuilt += batch.rebuilt;+ superseded += batch.superseded;+ tried += attempted;+ opts.progress?.tick(attempted, `${rebuilt} rebuilt, ${failed.length} failed`);+ }+ } finally {+ opts.progress?.finish();+ }+ const remaining = (await projectionBacklog(engine)).pending;+ return { rebuilt, superseded, failed, remaining, limited: opts.limit !== undefined && tried >= opts.limit && remaining > 0 };+}++/** The next step for one failed page, from the preparation error it reported. */+export function projectionFailureNextAction(failure: ProjectionRebuildFailure): string {+ if (failure.reason.startsWith('Code projection requires a recorded source path')) {+ return `restore frontmatter.file or source_path on ${failure.slug}, then run \`gbrain projections drain\` again`;+ }+ if (failure.reason.startsWith('This page kind requires its source importer')) {+ return `re-import it from its source: \`gbrain sync --source ${failure.source_id}\``;+ }+ 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 {+ const uid = '$(id -u)';+ 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`,+ ].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 {+ 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),+ ].join('\n'));+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex bf2878ab6d..1a2d06fa70 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -84,6 +84,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'projections': ['--brain', '--enable-dcr', '--force', '--help', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--max-rss', '--no-inject', '--no-worker', '--now', '--once', '--pause', '--port', '--public-url', '--reason', '--remove', '--repo', '--resume', '--source', '--status', '--surface', '--swap-only', '--target', '--uninstall', '--user'],'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],diff --git a/test/e2e/projection-drain-postgres.test.ts b/test/e2e/projection-drain-postgres.test.tsnew file mode 100644index 0000000000..a8e1bd0bf2--- /dev/null+++ b/test/e2e/projection-drain-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../projection-drain.test.ts'));diff --git a/test/projection-drain.test.ts b/test/projection-drain.test.tsnew file mode 100644index 0000000000..d8f8bfa4a7--- /dev/null+++ b/test/projection-drain.test.ts@@ -0,0 +1,248 @@+/**+ * #5401: the projection drain command and the budgeted resident drain. Clock+ * and per-page cost are injected; no assertion depends on wall-clock time.+ * PGLite here; test/e2e/projection-drain-postgres.test.ts runs the same file on+ * PostgreSQL, where the concurrent owner schedules also run.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { rebuildPendingPageProjections, projectionBacklog } from '../src/core/page-state/projections.ts';+import { runResidentProjectionInvocation } from '../src/core/persistence/consumer.ts';+import { claimNextWrite, hasClaimableWrite } from '../src/core/persistence/journal.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { drainProjections } from '../src/commands/projections.ts';+import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let sourceSeq = 0;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+});++/** Each test drains its own source: earlier tests' rows are gone or out of scope. */+async function clearQueue(engine: BrainEngine) {+ await engine.executeRaw('DELETE FROM page_projection_jobs');+ await engine.executeRaw("DELETE FROM persistence_requests WHERE state IN ('queued','running')");+}++async function backlog(engine: BrainEngine, pages: number): Promise<string> {+ await clearQueue(engine);+ const sourceId = `drain-${++sourceSeq}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ for (let i = 0; i < pages; i++) {+ await engine.putPage(`notes/n-${String(i).padStart(4, '0')}`, { type: 'note', title: `Note ${i}`, compiled_truth: `Example note ${i} about a sample topic.` }, { sourceId });+ }+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1', [sourceId]);+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id=$1+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason,updated_at=now()`, [sourceId]);+ return sourceId;+}++/** A clock that advances by the injected per-page cost (half per transaction: lock, then install). */+function costed(engine: BrainEngine, costMs: number) {+ const clock = { t: 0, now: () => clock.t };+ const transaction = engine.transaction.bind(engine);+ const proxy = new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>) => { clock.t += costMs / 2; return transaction(run); };+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;+ } });+ return { engine: proxy, clock };+}++const pending = async (engine: BrainEngine) => (await projectionBacklog(engine)).pending;++test('a budgeted rebuild starts no page after the deadline, and the resident invocation uses the 250 ms budget', async () => {+ for (const engine of engines) {+ await backlog(engine, 40);+ const direct = costed(engine, 40);+ expect(await rebuildPendingPageProjections(direct.engine, 100, { deadlineMs: 250, now: direct.clock.now })).toEqual({ rebuilt: 7, superseded: 0 });+ expect(direct.clock.t - 40).toBeLessThan(250);+ const resident = costed(engine, 40);+ expect(await runResidentProjectionInvocation(resident.engine, localHostId(), [], resident.clock.now)).toEqual({ rebuilt: 7, superseded: 0 });+ expect(await pending(engine)).toBe(26);+ }+}, 120_000);++test('a claimable write drops the resident invocation to two pages; a blocked or excluded write does not', async () => {+ for (const engine of engines) {+ await backlog(engine, 30);+ const f = await requestFixture(engine);+ const head = await f.admit('head');+ const invoke = (excluded: string[]) => { const timed = costed(engine, 20); return runResidentProjectionInvocation(timed.engine, localHostId(), excluded, timed.clock.now); };+ expect(await hasClaimableWrite(engine, localHostId())).toBe(true);+ expect((await invoke([])).rebuilt).toBe(2);+ const root = `db:${head.source_incarnation}`;+ expect(await hasClaimableWrite(engine, localHostId(), [root])).toBe(false);+ expect((await invoke([root])).rebuilt).toBe(13);+ expect((await claimNextWrite(engine, localHostId()))?.id).toBe(head.id);+ await f.admit('behind-running-head');+ expect(await hasClaimableWrite(engine, localHostId())).toBe(false);+ expect((await invoke([])).rebuilt).toBe(13);+ expect(await pending(engine)).toBe(2);+ }+}, 120_000);++test('a 1,000-page backlog drains in the invocation count the injected per-page cost predicts', async () => {+ for (const engine of engines) {+ await backlog(engine, 1000);+ const { engine: timed, clock } = costed(engine, 10);+ let invocations = 0;+ for (;;) {+ const startedAt = clock.t;+ const result = await runResidentProjectionInvocation(timed, localHostId(), [], clock.now);+ if (result.rebuilt + result.superseded === 0) break;+ invocations++;+ expect(result.rebuilt).toBe(25);+ expect(clock.t - 10 - startedAt).toBeLessThan(250);+ }+ expect(invocations).toBe(40);+ expect(await pending(engine)).toBe(0);+ }+}, 300_000);++test('a drain run tries a failing page once, keeps rebuilding the rest, and reports it with its reason', async () => {+ for (const engine of engines) {+ const sourceId = await backlog(engine, 3);+ await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId });+ const result = await drainProjections(engine);+ expect(result).toMatchObject({ rebuilt: 3, superseded: 0, remaining: 1, limited: false });+ expect(result.failed).toHaveLength(1);+ expect(result.failed[0]).toMatchObject({ source_id: sourceId, slug: 'broken-code' });+ expect(result.failed[0].reason).toContain('recorded source path');+ expect(await engine.executeRaw("SELECT reason FROM page_projection_jobs WHERE slug='broken-code'")).toEqual([{ reason: 'rebuild_failed' }]);+ }+}, 120_000);++test('the resident selector waits 30 seconds before retrying a failed page; the drain command does not', async () => {+ for (const engine of engines) {+ const sourceId = await backlog(engine, 0);+ await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId });+ await engine.executeRaw("UPDATE page_projection_jobs SET reason='rebuild_failed',updated_at=now()-interval '10 seconds'");+ const stamp = async () => (await engine.executeRaw<{ at: string }>('SELECT updated_at::text AS at FROM page_projection_jobs'))[0].at;+ const cooling = await stamp();+ expect(await runResidentProjectionInvocation(engine, localHostId(), [])).toEqual({ rebuilt: 0, superseded: 0 });+ expect(await stamp()).toBe(cooling);+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at=now()-interval '1 minute'");+ const due = await stamp();+ await runResidentProjectionInvocation(engine, localHostId(), []);+ expect(await stamp()).not.toBe(due);+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at=now()-interval '10 seconds'");+ expect((await drainProjections(engine)).failed.map(failure => failure.slug)).toEqual(['broken-code']);+ }+}, 120_000);++test('the run-start bound keeps microseconds: a row queued at the bound is tried, one queued 100 microseconds after it is not', async () => {+ for (const engine of engines) {+ await backlog(engine, 1);+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at='2026-01-01 00:00:00.000400+00'");+ expect(await rebuildPendingPageProjections(engine, 100, { notAfter: '2026-01-01 00:00:00.000300+00' })).toEqual({ rebuilt: 0, superseded: 0 });+ expect(await rebuildPendingPageProjections(engine, 100, { notAfter: '2026-01-01 00:00:00.000400+00' })).toEqual({ rebuilt: 1, superseded: 0 });+ }+}, 120_000);++test('a preparation error is one page failure, not a batch abort', async () => {+ for (const engine of engines) {+ await backlog(engine, 4);+ const transaction = engine.transaction.bind(engine);+ let calls = 0;+ const broken = new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>) => {+ if (calls++ === 0) return Promise.reject(new Error('simulated preparation failure'));+ return transaction(run);+ };+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;+ } });+ const failures: Array<{ slug: string; reason: string }> = [];+ expect(await rebuildPendingPageProjections(broken, 100, { onFailure: failure => failures.push(failure) })).toEqual({ rebuilt: 3, superseded: 0 });+ expect(failures).toEqual([expect.objectContaining({ slug: 'notes/n-0000', reason: 'simulated preparation failure' })]);+ expect(await engine.executeRaw('SELECT slug,reason FROM page_projection_jobs')).toEqual([{ slug: 'notes/n-0000', reason: 'rebuild_failed' }]);+ }+}, 120_000);++test('--limit caps the pages tried and the result records that the run stopped early', async () => {+ for (const engine of engines) {+ await backlog(engine, 12);+ expect(await drainProjections(engine, { limit: 5 })).toEqual({ rebuilt: 5, superseded: 0, failed: [], remaining: 7, limited: true });+ expect(await drainProjections(engine)).toEqual({ rebuilt: 7, superseded: 0, failed: [], remaining: 0, limited: false });+ }+}, 120_000);++test('doctor names the drain command when no PGLite resident holds the brain, and the resident when one does', async () => {+ for (const engine of engines) {+ const sourceId = await backlog(engine, 1);+ const local = await checkProjectionReadiness(engine, { sourceId });+ expect(local.status).toBe('warn');+ expect(local.message).toContain('Run `gbrain projections drain`');+ expect(local.message).not.toContain('Restart the upgraded resident');+ const resident = await checkProjectionReadiness(engine, { sourceId }, { resident: true });+ expect(resident.message).toContain('resident gbrain process that holds this PGLite brain is rebuilding');+ expect(resident.message).not.toContain('Run `gbrain projections drain`');+ await drainProjections(engine);+ expect((await checkProjectionReadiness(engine, { sourceId })).status).toBe('ok');+ }+}, 120_000);++/** Pauses the first page of `engine` until `release` resolves, at `point`. */+function paused(engine: BrainEngine, point: 'before_lock' | 'after_lock') {+ const reached = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const transaction = engine.transaction.bind(engine);+ let first = true;+ const proxy = new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return async <T>(run: (tx: BrainEngine) => Promise<T>) => {+ if (!first) return transaction(run);+ first = false;+ if (point === 'before_lock') { reached.resolve(); await release.promise; return transaction(run); }+ return transaction(tx => run(new Proxy(tx, { get(inner, prop) {+ if (prop === 'lockPageKeys') return async (keys: unknown) => { await (inner as any).lockPageKeys(keys); reached.resolve(); await release.promise; };+ const value = Reflect.get(inner, prop, inner); return typeof value === 'function' ? value.bind(inner) : value;+ } })));+ };+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;+ } });+ return { engine: proxy, reached: reached.promise, release: () => release.resolve() };+}++test('on Postgres the drain runs beside a resident owner and each page is rebuilt once in either order', async () => {+ for (const engine of engines.filter(candidate => candidate.kind === 'postgres')) {+ await backlog(engine, 3);+ const cli = paused(engine, 'before_lock');+ const drain = drainProjections(cli.engine);+ await cli.reached;+ expect(await runResidentProjectionInvocation(engine, localHostId(), [])).toEqual({ rebuilt: 3, superseded: 0 });+ cli.release();+ expect(await drain).toEqual({ rebuilt: 0, superseded: 3, failed: [], remaining: 0, limited: false });++ const sourceId = await backlog(engine, 1);+ const holder = paused(engine, 'after_lock');+ const first = drainProjections(holder.engine);+ await holder.reached;+ const resident = runResidentProjectionInvocation(engine, localHostId(), []);+ for (let attempt = 0; attempt < 200; attempt++) {+ const [waiting] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_locks WHERE NOT granted');+ if (waiting.n > 0) break;+ await Bun.sleep(25);+ }+ holder.release();+ const [cliRun, residentRun] = await Promise.all([first, resident]);+ expect(cliRun.failed).toEqual([]);+ expect({ rebuilt: cliRun.rebuilt + residentRun.rebuilt, superseded: cliRun.superseded + residentRun.superseded }).toEqual({ rebuilt: 1, superseded: 1 });+ const [page] = await engine.executeRaw<{ sealed: boolean }>("SELECT text_projection_revision=knowledge_revision AS sealed FROM pages WHERE slug='notes/n-0000' AND source_id=$1", [sourceId]);+ expect(page.sealed).toBe(true);+ }+}, 120_000);diff --git a/test/projections-drain-cli.serial.test.ts b/test/projections-drain-cli.serial.test.tsnew file mode 100644index 0000000000..357cb89ea3--- /dev/null+++ b/test/projections-drain-cli.serial.test.ts@@ -0,0 +1,113 @@+/**+ * #5401 / DX-O5: `gbrain projections drain` through the real CLI entrypoint.+ * Exit 0 when nothing tried failed, 1 when a page failed, 2 when it did not run+ * (bad usage, or `projection_owner_resident` because a resident holds the+ * PGLite brain — refused before any engine opens, including for a mounted+ * PGLite brain on a host configured for Postgres).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';+import { runCli } from './helpers/cli-spawn.ts';++const root = mkdtempSync(join(tmpdir(), 'gbrain-projections-cli-'));+const healthyHome = join(root, 'healthy');+const failingHome = join(root, 'failing');+const mountedHome = join(root, 'mounted');++function writeConfig(home: string, config: Record<string, unknown>) {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));+}++async function seedBrain(home: string, broken: boolean) {+ const database_path = join(home, '.gbrain', 'brain.pglite');+ writeConfig(home, { engine: 'pglite', database_path });+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path });+ try {+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('cli-example','cli-example')");+ for (const slug of ['notes/a', 'notes/b']) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example ${slug}.` }, { sourceId: 'cli-example' });+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='cli-example'");+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id='cli-example'+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision`);+ if (broken) await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId: 'cli-example' });+ } finally { await engine.disconnect(); }+}++beforeAll(async () => {+ await seedBrain(healthyHome, false);+ await seedBrain(failingHome, true);+ writeConfig(mountedHome, { engine: 'postgres', database_url: 'postgresql://[email protected]:1/unreachable' });+ writeFileSync(join(mountedHome, '.gbrain', 'mounts.json'), JSON.stringify({ version: 1, mounts: [+ { id: 'team-a', path: join(mountedHome, 'team-a'), engine: 'pglite', database_path: join(mountedHome, 'team-a.pglite'), enabled: true },+ ] }));+}, 240_000);+afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('gbrain projections drain', () => {+ test('help lists the command; bad usage exits 2 without running', async () => {+ expect((await runCli(['--help'], { home: healthyHome })).stdout).toContain('projections drain [--limit n]');+ const help = await runCli(['projections', '--help'], { home: healthyHome });+ expect(help.exitCode).toBe(0);+ expect(help.stdout).toContain('Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run');+ const unknown = await runCli(['projections', 'rebuild'], { home: healthyHome });+ expect(unknown.exitCode).toBe(2);+ expect(unknown.stderr).toContain('Error [invalid_params]');+ const limit = await runCli(['projections', 'drain', '--limit', '0', '--json'], { home: healthyHome });+ expect(limit.exitCode).toBe(2);+ expect(JSON.parse(limit.stdout)).toMatchObject({ error: 'invalid_params', suggestion: expect.stringContaining('gbrain projections drain --limit 1000') });+ }, 120_000);++ test('exit 0 drains the backlog and says it is empty', async () => {+ const human = await runCli(['projections', 'drain'], { home: healthyHome });+ expect(human.exitCode).toBe(0);+ expect(human.stdout).toContain('projections drain: 2 rebuilt, 0 superseded, 0 failed, 0 remaining. The projection backlog is empty.');+ const again = await runCli(['projections', 'drain', '--json'], { home: healthyHome });+ expect(again.exitCode).toBe(0);+ expect(JSON.parse(again.stdout)).toEqual({ rebuilt: 0, superseded: 0, failed: [], remaining: 0 });+ }, 120_000);++ test('exit 1 reports each failed page with its source, slug, reason and next action', async () => {+ const json = await runCli(['projections', 'drain', '--json'], { home: failingHome });+ expect(json.exitCode).toBe(1);+ const payload = JSON.parse(json.stdout);+ expect(payload).toMatchObject({ rebuilt: 2, superseded: 0, remaining: 1 });+ expect(payload.failed).toEqual([{ source_id: 'cli-example', slug: 'broken-code', reason: expect.stringContaining('recorded source path') }]);+ const human = await runCli(['projections', 'drain'], { home: failingHome });+ expect(human.exitCode).toBe(1);+ expect(human.stderr).toContain('failed: cli-example/broken-code: Code projection requires a recorded source path');+ expect(human.stderr).toContain('next: restore frontmatter.file or source_path on broken-code');+ expect(human.stdout).toContain('0 rebuilt, 0 superseded, 1 failed, 1 remaining. Failed pages stay queued');+ expect(human.stdout).not.toContain('backlog is empty');+ }, 120_000);++ test('exit 2 projection_owner_resident while a resident holds the PGLite brain, before any engine opens', async () => {+ const lock = await acquireLock(join(healthyHome, '.gbrain', 'brain.pglite'));+ try {+ const human = await runCli(['projections', 'drain'], { home: healthyHome, timeoutMs: 30_000 });+ expect(human.exitCode).toBe(2);+ 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');+ 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' });+ } finally { await releaseLock(lock); }+ }, 120_000);++ test('a mounted PGLite brain on a Postgres-configured host is refused for its own resident', async () => {+ const lock = await acquireLock(join(mountedHome, 'team-a.pglite'));+ try {+ 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`);+ } finally { await releaseLock(lock); }+ }, 120_000);+});