Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(wave5-d): keep touched modules within their size ceilings
garrytane0dcf1e0679a
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 141a5c2a1e..2c9fd7967b 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 5503266a3a..1d05c52ee0 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -46,4 +46,4 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered).diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex 88c0ecaf81..9cf5196516 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/cli-force-exit.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`.+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`.- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrix + clamp arithmetic + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 871f745869..7a0cbf48e4 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -126,6 +126,7 @@ test/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSynctest/e2e/migration-flow.test.ts (file-level) 4 readFileSynctest/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSynctest/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync+test/embed-concurrency-pool-clamp.test.ts #5183 embed concurrency never exceeds the Postgres pool 4 readFileSynctest/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helpertest/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helpertest/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync@@ -204,11 +205,12 @@ test/migrate.test.ts resolveSessionTimeouts — env var overrides 5 source-surfatest/migrate.test.ts v117 — context_volunteer_events_table 5 readFileSync,source-surface-helpertest/migration-resume.test.ts Bug 3 — orchestrator no longer writes the ledger directly 6 bun-filetest/migrations-v0_11_0.test.ts AGENTS.md marker injection 6 readFileSync+test/migrations-v0_11_0.test.ts GBRAIN_HOME resolution (#5549) 2 readFileSynctest/migrations-v0_11_0.test.ts cron manifest rewrite — gbrain builtins only 8 readFileSynctest/migrations-v0_14_0.test.ts Bug 5 + Bug 8 — v0_14_0 module shape 3 bun-filetest/migrations-v0_14_0.test.ts Bug 5 — Phase B host-work entry dedup 2 readFileSynctest/migrations-v0_14_0.test.ts Bug 8 — max_stalled default bumped in schema files 3 bun-file-test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 9 readFileSync+test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 10 readFileSynctest/model-pricing.test.ts DRIFT GUARD — derived views stay equal to canonical (re-hardcode trip-wire) 4 readFileSynctest/model-pricing.test.ts no heavy import (cycle guard) 1 readFileSynctest/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (#3973) 1 doctor-source-helper@@ -317,6 +319,7 @@ test/template-repo-generator.test.ts generateTemplateTree 0 readFileSynctest/template-repo-generator.test.ts renderTemplateReadme 5 readFileSynctest/think-embed-question-wiring.serial.test.ts #3734 — CRAG think escalation wires embedQuestion (source pin) 1 readFileSynctest/think-embed-question-wiring.serial.test.ts #3734 — synthesize verb wires embedQuestion into runThink 1 readFileSync+test/think-save-source.test.ts #5426 think --save persists into the think source 5 readFileSynctest/timing-safe.test.ts extraction contract 1 source-surface-helpertest/title-fuzzy-index.test.ts findByTitleFuzzy indexed threshold 2 source-surface-helpertest/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSyncdiff --git a/src/cli.ts b/src/cli.tsindex 75acba6596..3f33cf9170 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -4,7 +4,7 @@ import { affectsRecall } from './core/types.ts';import { deliveryVersionSkewWarning } from './core/search/evidence-delivery.ts';import { installSigchldHandler } from './core/zombie-reap.ts';installSigchldHandler();-import { installSignalHandlers as installCleanupSignalHandlers } from './core/process-cleanup.ts';+import { installCleanupSignalHandlers } from './core/serve-invocation.ts';import { readFileSync, existsSync, unlinkSync, fstatSync } from 'fs';import { spawn } from 'child_process';@@ -34,7 +34,7 @@ import { operations, OperationError } from './core/operations.ts';import { resolveSourceIdEngineFree } from './core/source-resolver.ts';import { formatVolunteeredPage } from './core/context/volunteer.ts';import type { Operation, OperationContext } from './core/operations.ts';-import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery, isHttpServeInvocation } from './core/cli-force-exit.ts';+import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';import { runCliPreflight } from './core/cli-preflight.ts';@@ -3108,7 +3108,7 @@ if (import.meta.main) {// SIGTERM→exit(143) handler into any process that merely IMPORTS this module// (bun test runners died mid-suite when a test emitted a synthetic SIGTERM).// Spawned/compiled CLI processes are entrypoints, so they still install.- installCleanupSignalHandlers({ keepServingOnLogEpipe: isHttpServeInvocation() });+ installCleanupSignalHandlers();// #4383: CLI_ONLY payloads (console.log / bare process.stdout.write) get// delivery-exact serialized writes; `serve` keeps native streaming stdout.if (shouldForceExitAfterMain()) installStdoutPipeDelivery();diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 388010b242..9b901535cb 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -57,11 +57,29 @@ import {autopilotLaunchdLabel,autopilotWrapperOwner,resolveAutopilotJob,- DEFAULT_AUTOPILOT_LAUNCHD_LABEL,DEFAULT_AUTOPILOT_SYSTEMD_UNIT,type AutopilotJob,} from '../core/autopilot-paths.ts';-import { errorFor } from '../core/errors.ts';+import {+ BOOTSTRAP_MARKER,+ brainCommand,+ cronLineBelongsToBrain,+ crontabIndicatesAutopilotInstall,+ autopilotJobStatus,+ detectOpenClaw,+ legacyStartScriptPath,+ plistPath,+ plistWrapperPath,+ readIfExists,+ refuseForeignJob,+ replaceLegacySharedJob,+ scriptWrapperPath,+ shellQuote,+ stripBootstrapLines,+ systemdUnitPath,+ unitWrapperPath,+} from './autopilot/jobs.ts';+export { cronLineBelongsToBrain, crontabIndicatesAutopilotInstall, plistWrapperPath, scriptWrapperPath, unitWrapperPath };export { autopilotLockPath, autopilotDisabledMarkerPath, autopilotPausedMarkerPath, autopilotLaunchdLabel };export { relativeSourceLocalPathSkipWarning as relativeLocalPathSkipWarning };@@ -621,86 +639,6 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// --- Install/Uninstall ----function plistPath(label: string): string {- return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${label}.plist`);-}--function systemdUnitPath(unit: string = DEFAULT_AUTOPILOT_SYSTEMD_UNIT): string {- return join(process.env.HOME || '', '.config', 'systemd', 'user', unit);-}--/** The pre-#5195 shared start script, which every brain used to overwrite. */-function legacyStartScriptPath(): string {- return join(process.env.HOME || '', '.gbrain', 'start-autopilot.sh');-}--const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;-const unshellQuote = (s: string) => s.replace(/'\\''/g, "'");--/** The wrapper a launchd plist runs (its first ProgramArguments entry). */-export function plistWrapperPath(plist: string): string | null {- const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(plist);- if (!m) return null;- return m[1].replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');-}--/** The wrapper a systemd unit runs. */-export function unitWrapperPath(unit: string): string | null {- return /^ExecStart=(.+)$/m.exec(unit)?.[1].trim() || null;-}--/** The autopilot wrapper a crontab line or start script names, if any. */-export function scriptWrapperPath(text: string): string | null {- const quoted = /'((?:[^']|'\\'')*autopilot-run\.sh)'/.exec(text);- if (quoted) return unshellQuote(quoted[1]);- return /(\S*autopilot-run\.sh)/.exec(text)?.[1] ?? null;-}--/**- * #5195: does this crontab line belong to this brain's job? A marked line- * (`# gbrain-autopilot:<suffix>`) belongs to the brain with that suffix. An- * unmarked line predates per-brain names: it belongs to the brain whose- * wrapper it names, and to the default brain when it names none.- */-export function cronLineBelongsToBrain(line: string, job: AutopilotJob): boolean {- if (!crontabIndicatesAutopilotInstall(line)) return false;- const marker = /#\s*gbrain-autopilot:([A-Za-z0-9]+)\s*$/.exec(line);- if (marker) return job.suffix !== null && marker[1] === job.suffix;- const wrapper = scriptWrapperPath(line);- if (!wrapper) return job.kind === 'default';- return autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';-}--/** `GBRAIN_HOME=<parent> gbrain autopilot <verb>` for the brain whose home is `brainHome`. */-function brainCommand(brainHome: string, verb: string): string {- const parent = dirname(brainHome);- const defaultHome = join(process.env.HOME || '', '.gbrain');- return resolvePath(brainHome) === resolvePath(defaultHome)- ? `gbrain autopilot ${verb}`- : `GBRAIN_HOME=${shellQuote(parent)} gbrain autopilot ${verb}`;-}--/**- * ENG-O11: before replacing a job, make sure its wrapper names this brain. A- * job whose wrapper belongs to another live brain is that brain's supervision;- * replacing it would silently stop it (the #5195 failure).- */-function refuseForeignJob(jobName: string, wrapperPath: string | null, job: AutopilotJob): void {- const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);- if (owner.owner !== 'other') return;- throw errorFor({- class: 'AutopilotJobOwnedByOtherBrain',- code: 'autopilot_job_owned_by_other_brain',- message: `The autopilot job ${jobName} runs the brain at ${owner.home}, not this brain at ${job.homeDir}.`,- hint: `Give that brain its own job first: ${brainCommand(owner.home, '--install')}; then re-run: ${brainCommand(job.homeDir, '--install')}`,- docs_url: 'docs/guides/live-sync.md#several-brains-on-one-host',- });-}--function readIfExists(path: string): string | null {- try { return readFileSync(path, 'utf-8'); } catch { return null; }-}-export type InstallTarget = 'macos' | 'linux-systemd' | 'ephemeral-container' | 'linux-cron';/**@@ -735,21 +673,6 @@ export function detectInstallTarget(): InstallTarget {return 'linux-cron';}-function detectOpenClaw(): { detected: boolean; bootstrapCandidates: string[] } {- const home = process.env.HOME || '';- const candidates = [- process.env.OPENCLAW_HOME ? join(process.env.OPENCLAW_HOME, 'hooks', 'bootstrap', 'ensure-services.sh') : '',- join(process.cwd(), 'hooks', 'bootstrap', 'ensure-services.sh'),- join(home, '.claude', 'hooks', 'bootstrap', 'ensure-services.sh'),- ].filter(Boolean) as string[];- const existing = candidates.filter(p => existsSync(p));- const signal = !!process.env.OPENCLAW_HOME- || existsSync(join(process.cwd(), 'openclaw.json'))- || existsSync(join(home, 'openclaw.json'))- || existing.length > 0;- return { detected: signal, bootstrapCandidates: existing };-}-/** systemd unit name. The launchd label lives in `autopilotLaunchdLabel()`* (core/autopilot-paths.ts) so installer, uninstaller, status, and the* wrapper's self-disable can never name different jobs. */@@ -1399,77 +1322,6 @@ export function runAutopilotStatus(args: string[]): void {showStatus(args.includes('--json'), Number.isFinite(rawInterval) && rawInterval > 0 ? rawInterval : 300);}-const BOOTSTRAP_MARKER = '# gbrain:autopilot v0.11.0';--/**- * Remove the bootstrap lines that launch `scriptPath` (the marker line and the- * `bash <script>` line after it) from every OpenClaw bootstrap candidate.- * Another brain's injected lines name its own script and are left alone.- */-function stripBootstrapLines(scriptPath: string): number {- let removed = 0;- try {- const { bootstrapCandidates } = detectOpenClaw();- for (const candidate of bootstrapCandidates) {- try {- const content = readFileSync(candidate, 'utf-8');- if (!content.includes(`${BOOTSTRAP_MARKER}\nbash ${scriptPath}`)) continue;- const lines = content.split('\n');- const cleaned: string[] = [];- for (let i = 0; i < lines.length; i++) {- if (lines[i].includes(BOOTSTRAP_MARKER) && lines[i + 1] === `bash ${scriptPath}`) {- // Skip this marker line AND the next line (the bash start-script call).- i++;- continue;- }- cleaned.push(lines[i]);- }- // Backup before edit- const stamp = new Date().toISOString().replace(/[:.]/g, '-');- writeFileSync(`${candidate}.bak.${stamp}`, content);- writeFileSync(candidate, cleaned.join('\n'));- console.log(`Removed bootstrap marker from: ${candidate}`);- removed++;- } catch (e) {- console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);- }- }- } catch { /* OpenClaw detection best-effort */ }- return removed;-}--/**- * #5195: a non-default brain installed by an older gbrain ran under the shared- * job name. Installing it again on the same target removes that shared job —- * only when its wrapper names this brain — before the brain's own job is- * written, and says so. Crontab lines are handled by installCrontab.- */-function replaceLegacySharedJob(job: AutopilotJob, target: InstallTarget): void {- if (job.kind === 'default') return;- const own = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';- if (target === 'macos') {- const legacyLabel = autopilotLaunchdLabel(null);- const path = plistPath(legacyLabel);- if (legacyLabel === job.launchdLabel || !own(plistWrapperPath(readIfExists(path) ?? ''))) return;- execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });- unlinkSync(path);- console.log(`Replaced the shared launchd job ${legacyLabel}, which ran this brain, with ${job.launchdLabel}.`);- } else if (target === 'linux-systemd') {- const path = systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT);- if (!own(unitWrapperPath(readIfExists(path) ?? ''))) return;- execSync(`systemctl --user disable --now ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });- unlinkSync(path);- console.log(`Replaced the shared systemd unit ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT}, which ran this brain, with ${job.systemdUnit}.`);- } else if (target === 'ephemeral-container') {- const path = legacyStartScriptPath();- if (path === job.startScriptPath || !own(scriptWrapperPath(readIfExists(path) ?? ''))) return;- unlinkSync(path);- stripBootstrapLines(path);- console.log(`Replaced the shared start script ${path}, which ran this brain, with ${job.startScriptPath}.`);- console.log(` Update any bootstrap line that runs \`bash ${path}\` to run \`bash ${job.startScriptPath}\`.`);- }-}-export function uninstallDaemon() {// #5195: only this brain's job is removed — its own named job (checked to// run this brain's wrapper before removal), plus, for a non-default brain,@@ -1686,83 +1538,6 @@ export function classifyAutopilotStatus(input: {};}-interface InstalledJob {- target: InstallTarget;- /** launchd label, systemd unit, start-script path, or the crontab marker. */- name: string;- wrapperPath: string | null;- /** A pre-#5195 shared-name job that runs this non-default brain. */- legacy: boolean;-}--/**- * Which supervisor, if any, currently holds THIS brain's autopilot job (#5195).- *- * Checks every target `installDaemon` can produce. The prior version grepped- * crontab ONLY on non-darwin, so systemd-user and ephemeral-container installs- * read as "not installed" — cosmetic while status always exited 0, but a hard- * false failure once the exit code became load-bearing. A shared job whose- * wrapper runs another live brain is reported separately, never as this- * brain's install.- */-function detectInstalledJob(job: AutopilotJob): { installed: InstalledJob | null; foreign: { name: string; home: string } | null } {- let foreign: { name: string; home: string } | null = null;- const assigned = job.kind !== 'unassigned';- const consider = (target: InstallTarget, name: string, text: string | null, wrapperOf: (t: string) => string | null, legacy: boolean): InstalledJob | null => {- if (text === null) return null;- const wrapperPath = wrapperOf(text);- const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);- if (legacy) return owner.owner === 'own' ? { target, name, wrapperPath, legacy } : null;- if (owner.owner === 'other') {- foreign ??= { name, home: owner.home };- return null;- }- return { target, name, wrapperPath, legacy };- };- const candidates: Array<() => InstalledJob | null> = [];- if (process.platform === 'darwin') {- if (assigned) candidates.push(() => consider('macos', job.launchdLabel, readIfExists(plistPath(job.launchdLabel)), plistWrapperPath, false));- if (job.kind !== 'default' && autopilotLaunchdLabel(null) !== job.launchdLabel) {- candidates.push(() => consider('macos', autopilotLaunchdLabel(null), readIfExists(plistPath(autopilotLaunchdLabel(null))), plistWrapperPath, true));- }- }- if (assigned) candidates.push(() => consider('linux-systemd', job.systemdUnit, readIfExists(systemdUnitPath(job.systemdUnit)), unitWrapperPath, false));- if (job.kind !== 'default') candidates.push(() => consider('linux-systemd', DEFAULT_AUTOPILOT_SYSTEMD_UNIT, readIfExists(systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT)), unitWrapperPath, true));- if (assigned) candidates.push(() => consider('ephemeral-container', job.startScriptPath, readIfExists(job.startScriptPath), scriptWrapperPath, false));- if (job.kind !== 'default') candidates.push(() => consider('ephemeral-container', legacyStartScriptPath(), readIfExists(legacyStartScriptPath()), scriptWrapperPath, true));- candidates.push(() => {- try {- const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });- if (!crontabIndicatesAutopilotInstall(crontab)) return null;- const line = crontab.split('\n').find(l => cronLineBelongsToBrain(l, job));- if (!line) return null;- const legacy = job.cronMarker !== null && !line.includes(job.cronMarker);- return { target: 'linux-cron', name: job.cronMarker ?? 'crontab entry', wrapperPath: scriptWrapperPath(line), legacy };- } catch { return null; /* no crontab */ }- });- for (const candidate of candidates) {- const installed = candidate();- if (installed) return { installed, foreign };- }- return { installed: null, foreign };-}--/**- * Does this crontab contain an autopilot INSTALL line? The installed line- * invokes the generated wrapper (autopilot-run.sh); older installs called- * `gbrain autopilot` directly — match either. But the docs also recommend- * cron-ing `gbrain autopilot --status` as a health monitor, and counting THAT- * line as an install makes a monitor-only machine report installed/never_run- * with exit 1 forever. Comments never count. Pure and exported for tests.- */-export function crontabIndicatesAutopilotInstall(crontab: string): boolean {- return crontab.split('\n').some((line) => {- if (line.trimStart().startsWith('#')) return false;- if (line.includes('autopilot-run.sh')) return true;- return line.includes('gbrain autopilot') && !line.includes('--status');- });-}-function showStatus(json: boolean, intervalSeconds: number) {// gbrainHomePath, not raw HOME: the daemon writes its lock through// gbrainHomePath() (#1226), so a GBRAIN_HOME install had status reading one@@ -1790,28 +1565,8 @@ function showStatus(json: boolean, intervalSeconds: number) {heartbeatAgeSeconds = Math.max(0, Math.floor((Date.now() - mtimeMs) / 1000));} catch { /* never ran, or already cleaned up */ }- const { installed, foreign } = detectInstalledJob(job);- const installTarget = installed?.target ?? null;- const wrapperMissing = installed?.wrapperPath ? !existsSync(installed.wrapperPath) : false;- const needsReinstall = installed?.legacy- ? 'legacy_shared_job'- : wrapperMissing ? 'wrapper_missing' : null;- const jobReport = {- kind: job.kind,- suffix: job.suffix,- launchd_label: job.kind === 'unassigned' ? null : job.launchdLabel,- systemd_unit: job.kind === 'unassigned' ? null : job.systemdUnit,- start_script: job.kind === 'unassigned' ? null : job.startScriptPath,- cron_marker: job.cronMarker,- install_id_path: job.installIdPath,- wrapper_path: job.wrapperPath,- log_path: job.logPath,- installed_definition: installed- ? { target: installed.target, name: installed.name, wrapper_path: installed.wrapperPath, wrapper_exists: !wrapperMissing, legacy_shared_name: installed.legacy }- : null,- needs_reinstall: needsReinstall,- shared_job_of_other_brain: foreign,- };+ const jobStatus = autopilotJobStatus(job);+ const installTarget = jobStatus.installTarget;const report = classifyAutopilotStatus({installed: installTarget !== null,installTarget,@@ -1824,7 +1579,7 @@ function showStatus(json: boolean, intervalSeconds: number) {const processing = readAutopilotProcessingStatus();if (json) {- console.log(JSON.stringify({ ...report, ...processing, job: jobReport }));+ console.log(JSON.stringify({ ...report, ...processing, job: jobStatus.report }));} else {switch (report.state) {case 'not_installed':@@ -1862,17 +1617,7 @@ function showStatus(json: boolean, intervalSeconds: number) {console.log(`Stage: ${processing.processing_stage}${processing.retry_at ? `; next retry ${processing.retry_at}` : ''}`);if (processing.processing_state === 'configuration_blocked') console.log('Repair the worker and selected child installation, then explicitly restart autopilot.');}- const jobName = installed?.name ?? (job.kind === 'unassigned' ? null : `${job.launchdLabel} (launchd) / ${job.systemdUnit} (systemd)`);- if (jobName) console.log(`Job: ${jobName}${job.suffix ? ` (suffix ${job.suffix})` : ''}`);- if (job.installIdPath) console.log(`Install id: ${job.installIdPath}`);- console.log(`Wrapper: ${installed?.wrapperPath ?? job.wrapperPath}`);- console.log(`Log: ${job.logPath}`);- if (needsReinstall === 'legacy_shared_job') {- console.log(` This brain runs under the shared job ${installed!.name} from an older gbrain. Give it its own job: ${brainCommand(job.homeDir, '--install')}`);- } else if (needsReinstall === 'wrapper_missing') {- console.log(` The job runs ${installed!.wrapperPath}, which no longer exists (the brain moved?). Reinstall: ${brainCommand(job.homeDir, '--install')}`);- }- if (foreign) console.log(` ${foreign.name} runs the brain at ${foreign.home}, not this one.`);+ for (const line of jobStatus.lines) console.log(line);if (lastLine) console.log(`Last log: ${lastLine}`);}diff --git a/src/commands/autopilot/jobs.ts b/src/commands/autopilot/jobs.tsnew file mode 100644index 0000000000..de15c16c84--- /dev/null+++ b/src/commands/autopilot/jobs.ts@@ -0,0 +1,303 @@+/**+ * #5195: one brain's autopilot job definitions on every install target.+ * Reads and replaces the launchd plist, systemd unit, ephemeral start script and+ * crontab lines that belong to a brain, judged by the job name it resolves+ * (`resolveAutopilotJob`) and by the wrapper path each definition runs. Split+ * out of src/commands/autopilot.ts, which installs, uninstalls and reports.+ */+import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs';+import { dirname, join, resolve as resolvePath } from 'path';+import { execSync } from 'child_process';+import {+ autopilotLaunchdLabel,+ autopilotWrapperOwner,+ DEFAULT_AUTOPILOT_SYSTEMD_UNIT,+ type AutopilotJob,+} from '../../core/autopilot-paths.ts';+import { errorFor } from '../../core/errors.ts';+import type { InstallTarget } from '../autopilot.ts';++export function plistPath(label: string): string {+ return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${label}.plist`);+}++export function systemdUnitPath(unit: string = DEFAULT_AUTOPILOT_SYSTEMD_UNIT): string {+ return join(process.env.HOME || '', '.config', 'systemd', 'user', unit);+}++/** The pre-#5195 shared start script, which every brain used to overwrite. */+export function legacyStartScriptPath(): string {+ return join(process.env.HOME || '', '.gbrain', 'start-autopilot.sh');+}++export const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+export const unshellQuote = (s: string) => s.replace(/'\\''/g, "'");++/** The wrapper a launchd plist runs (its first ProgramArguments entry). */+export function plistWrapperPath(plist: string): string | null {+ const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(plist);+ if (!m) return null;+ return m[1].replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');+}++/** The wrapper a systemd unit runs. */+export function unitWrapperPath(unit: string): string | null {+ return /^ExecStart=(.+)$/m.exec(unit)?.[1].trim() || null;+}++/** The autopilot wrapper a crontab line or start script names, if any. */+export function scriptWrapperPath(text: string): string | null {+ const quoted = /'((?:[^']|'\\'')*autopilot-run\.sh)'/.exec(text);+ if (quoted) return unshellQuote(quoted[1]);+ return /(\S*autopilot-run\.sh)/.exec(text)?.[1] ?? null;+}++/**+ * #5195: does this crontab line belong to this brain's job? A marked line+ * (`# gbrain-autopilot:<suffix>`) belongs to the brain with that suffix. An+ * unmarked line predates per-brain names: it belongs to the brain whose+ * wrapper it names, and to the default brain when it names none.+ */+export function cronLineBelongsToBrain(line: string, job: AutopilotJob): boolean {+ if (!crontabIndicatesAutopilotInstall(line)) return false;+ const marker = /#\s*gbrain-autopilot:([A-Za-z0-9]+)\s*$/.exec(line);+ if (marker) return job.suffix !== null && marker[1] === job.suffix;+ const wrapper = scriptWrapperPath(line);+ if (!wrapper) return job.kind === 'default';+ return autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';+}++/** `GBRAIN_HOME=<parent> gbrain autopilot <verb>` for the brain whose home is `brainHome`. */+export function brainCommand(brainHome: string, verb: string): string {+ const parent = dirname(brainHome);+ const defaultHome = join(process.env.HOME || '', '.gbrain');+ return resolvePath(brainHome) === resolvePath(defaultHome)+ ? `gbrain autopilot ${verb}`+ : `GBRAIN_HOME=${shellQuote(parent)} gbrain autopilot ${verb}`;+}++/**+ * ENG-O11: before replacing a job, make sure its wrapper names this brain. A+ * job whose wrapper belongs to another live brain is that brain's supervision;+ * replacing it would silently stop it (the #5195 failure).+ */+export function refuseForeignJob(jobName: string, wrapperPath: string | null, job: AutopilotJob): void {+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);+ if (owner.owner !== 'other') return;+ throw errorFor({+ class: 'AutopilotJobOwnedByOtherBrain',+ code: 'autopilot_job_owned_by_other_brain',+ message: `The autopilot job ${jobName} runs the brain at ${owner.home}, not this brain at ${job.homeDir}.`,+ hint: `Give that brain its own job first: ${brainCommand(owner.home, '--install')}; then re-run: ${brainCommand(job.homeDir, '--install')}`,+ docs_url: 'docs/guides/live-sync.md#several-brains-on-one-host',+ });+}++export function readIfExists(path: string): string | null {+ try { return readFileSync(path, 'utf-8'); } catch { return null; }+}++export function detectOpenClaw(): { detected: boolean; bootstrapCandidates: string[] } {+ const home = process.env.HOME || '';+ const candidates = [+ process.env.OPENCLAW_HOME ? join(process.env.OPENCLAW_HOME, 'hooks', 'bootstrap', 'ensure-services.sh') : '',+ join(process.cwd(), 'hooks', 'bootstrap', 'ensure-services.sh'),+ join(home, '.claude', 'hooks', 'bootstrap', 'ensure-services.sh'),+ ].filter(Boolean) as string[];+ const existing = candidates.filter(p => existsSync(p));+ const signal = !!process.env.OPENCLAW_HOME+ || existsSync(join(process.cwd(), 'openclaw.json'))+ || existsSync(join(home, 'openclaw.json'))+ || existing.length > 0;+ return { detected: signal, bootstrapCandidates: existing };+}++export const BOOTSTRAP_MARKER = '# gbrain:autopilot v0.11.0';++/**+ * Remove the bootstrap lines that launch `scriptPath` (the marker line and the+ * `bash <script>` line after it) from every OpenClaw bootstrap candidate.+ * Another brain's injected lines name its own script and are left alone.+ */+export function stripBootstrapLines(scriptPath: string): number {+ let removed = 0;+ try {+ const { bootstrapCandidates } = detectOpenClaw();+ for (const candidate of bootstrapCandidates) {+ try {+ const content = readFileSync(candidate, 'utf-8');+ if (!content.includes(`${BOOTSTRAP_MARKER}\nbash ${scriptPath}`)) continue;+ const lines = content.split('\n');+ const cleaned: string[] = [];+ for (let i = 0; i < lines.length; i++) {+ if (lines[i].includes(BOOTSTRAP_MARKER) && lines[i + 1] === `bash ${scriptPath}`) {+ // Skip this marker line AND the next line (the bash start-script call).+ i++;+ continue;+ }+ cleaned.push(lines[i]);+ }+ // Backup before edit+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');+ writeFileSync(`${candidate}.bak.${stamp}`, content);+ writeFileSync(candidate, cleaned.join('\n'));+ console.log(`Removed bootstrap marker from: ${candidate}`);+ removed++;+ } catch (e) {+ console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);+ }+ }+ } catch { /* OpenClaw detection best-effort */ }+ return removed;+}++/**+ * #5195: a non-default brain installed by an older gbrain ran under the shared+ * job name. Installing it again on the same target removes that shared job —+ * only when its wrapper names this brain — before the brain's own job is+ * written, and says so. Crontab lines are handled by installCrontab.+ */+export function replaceLegacySharedJob(job: AutopilotJob, target: InstallTarget): void {+ if (job.kind === 'default') return;+ const own = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';+ if (target === 'macos') {+ const legacyLabel = autopilotLaunchdLabel(null);+ const path = plistPath(legacyLabel);+ if (legacyLabel === job.launchdLabel || !own(plistWrapperPath(readIfExists(path) ?? ''))) return;+ execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });+ unlinkSync(path);+ console.log(`Replaced the shared launchd job ${legacyLabel}, which ran this brain, with ${job.launchdLabel}.`);+ } else if (target === 'linux-systemd') {+ const path = systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT);+ if (!own(unitWrapperPath(readIfExists(path) ?? ''))) return;+ execSync(`systemctl --user disable --now ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });+ unlinkSync(path);+ console.log(`Replaced the shared systemd unit ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT}, which ran this brain, with ${job.systemdUnit}.`);+ } else if (target === 'ephemeral-container') {+ const path = legacyStartScriptPath();+ if (path === job.startScriptPath || !own(scriptWrapperPath(readIfExists(path) ?? ''))) return;+ unlinkSync(path);+ stripBootstrapLines(path);+ console.log(`Replaced the shared start script ${path}, which ran this brain, with ${job.startScriptPath}.`);+ console.log(` Update any bootstrap line that runs \`bash ${path}\` to run \`bash ${job.startScriptPath}\`.`);+ }+}++export interface InstalledJob {+ target: InstallTarget;+ /** launchd label, systemd unit, start-script path, or the crontab marker. */+ name: string;+ wrapperPath: string | null;+ /** A pre-#5195 shared-name job that runs this non-default brain. */+ legacy: boolean;+}++/**+ * Which supervisor, if any, currently holds THIS brain's autopilot job (#5195).+ *+ * Checks every target `installDaemon` can produce. The prior version grepped+ * crontab ONLY on non-darwin, so systemd-user and ephemeral-container installs+ * read as "not installed" — cosmetic while status always exited 0, but a hard+ * false failure once the exit code became load-bearing. A shared job whose+ * wrapper runs another live brain is reported separately, never as this+ * brain's install.+ */+export function detectInstalledJob(job: AutopilotJob): { installed: InstalledJob | null; foreign: { name: string; home: string } | null } {+ let foreign: { name: string; home: string } | null = null;+ const assigned = job.kind !== 'unassigned';+ const consider = (target: InstallTarget, name: string, text: string | null, wrapperOf: (t: string) => string | null, legacy: boolean): InstalledJob | null => {+ if (text === null) return null;+ const wrapperPath = wrapperOf(text);+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);+ if (legacy) return owner.owner === 'own' ? { target, name, wrapperPath, legacy } : null;+ if (owner.owner === 'other') {+ foreign ??= { name, home: owner.home };+ return null;+ }+ return { target, name, wrapperPath, legacy };+ };+ const candidates: Array<() => InstalledJob | null> = [];+ if (process.platform === 'darwin') {+ if (assigned) candidates.push(() => consider('macos', job.launchdLabel, readIfExists(plistPath(job.launchdLabel)), plistWrapperPath, false));+ if (job.kind !== 'default' && autopilotLaunchdLabel(null) !== job.launchdLabel) {+ candidates.push(() => consider('macos', autopilotLaunchdLabel(null), readIfExists(plistPath(autopilotLaunchdLabel(null))), plistWrapperPath, true));+ }+ }+ if (assigned) candidates.push(() => consider('linux-systemd', job.systemdUnit, readIfExists(systemdUnitPath(job.systemdUnit)), unitWrapperPath, false));+ if (job.kind !== 'default') candidates.push(() => consider('linux-systemd', DEFAULT_AUTOPILOT_SYSTEMD_UNIT, readIfExists(systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT)), unitWrapperPath, true));+ if (assigned) candidates.push(() => consider('ephemeral-container', job.startScriptPath, readIfExists(job.startScriptPath), scriptWrapperPath, false));+ if (job.kind !== 'default') candidates.push(() => consider('ephemeral-container', legacyStartScriptPath(), readIfExists(legacyStartScriptPath()), scriptWrapperPath, true));+ candidates.push(() => {+ try {+ const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });+ if (!crontabIndicatesAutopilotInstall(crontab)) return null;+ const line = crontab.split('\n').find(l => cronLineBelongsToBrain(l, job));+ if (!line) return null;+ const legacy = job.cronMarker !== null && !line.includes(job.cronMarker);+ return { target: 'linux-cron', name: job.cronMarker ?? 'crontab entry', wrapperPath: scriptWrapperPath(line), legacy };+ } catch { return null; /* no crontab */ }+ });+ for (const candidate of candidates) {+ const installed = candidate();+ if (installed) return { installed, foreign };+ }+ return { installed: null, foreign };+}++/**+ * Does this crontab contain an autopilot INSTALL line? The installed line+ * invokes the generated wrapper (autopilot-run.sh); older installs called+ * `gbrain autopilot` directly — match either. But the docs also recommend+ * cron-ing `gbrain autopilot --status` as a health monitor, and counting THAT+ * line as an install makes a monitor-only machine report installed/never_run+ * with exit 1 forever. Comments never count. Pure and exported for tests.+ */+export function crontabIndicatesAutopilotInstall(crontab: string): boolean {+ return crontab.split('\n').some((line) => {+ if (line.trimStart().startsWith('#')) return false;+ if (line.includes('autopilot-run.sh')) return true;+ return line.includes('gbrain autopilot') && !line.includes('--status');+ });+}+++/**+ * DX-O12: this brain's job for `autopilot --status`: the names it resolves to,+ * the definition actually installed (which may be a pre-#5195 shared-name job,+ * or one whose wrapper is gone because the brain moved), and the human lines.+ */+export function autopilotJobStatus(job: AutopilotJob): { installTarget: InstallTarget | null; report: Record<string, unknown>; lines: string[] } {+ const { installed, foreign } = detectInstalledJob(job);+ const wrapperMissing = installed?.wrapperPath ? !existsSync(installed.wrapperPath) : false;+ const needsReinstall = installed?.legacy ? 'legacy_shared_job' : wrapperMissing ? 'wrapper_missing' : null;+ const assigned = job.kind !== 'unassigned';+ const report = {+ kind: job.kind,+ suffix: job.suffix,+ launchd_label: assigned ? job.launchdLabel : null,+ systemd_unit: assigned ? job.systemdUnit : null,+ start_script: assigned ? job.startScriptPath : null,+ cron_marker: job.cronMarker,+ install_id_path: job.installIdPath,+ wrapper_path: job.wrapperPath,+ log_path: job.logPath,+ installed_definition: installed+ ? { target: installed.target, name: installed.name, wrapper_path: installed.wrapperPath, wrapper_exists: !wrapperMissing, legacy_shared_name: installed.legacy }+ : null,+ needs_reinstall: needsReinstall,+ shared_job_of_other_brain: foreign,+ };+ const lines: string[] = [];+ const jobName = installed?.name ?? (assigned ? `${job.launchdLabel} (launchd) / ${job.systemdUnit} (systemd)` : null);+ if (jobName) lines.push(`Job: ${jobName}${job.suffix ? ` (suffix ${job.suffix})` : ''}`);+ if (job.installIdPath) lines.push(`Install id: ${job.installIdPath}`);+ lines.push(`Wrapper: ${installed?.wrapperPath ?? job.wrapperPath}`);+ lines.push(`Log: ${job.logPath}`);+ if (needsReinstall === 'legacy_shared_job') {+ lines.push(` This brain runs under the shared job ${installed!.name} from an older gbrain. Give it its own job: ${brainCommand(job.homeDir, '--install')}`);+ } else if (needsReinstall === 'wrapper_missing') {+ lines.push(` The job runs ${installed!.wrapperPath}, which no longer exists (the brain moved?). Reinstall: ${brainCommand(job.homeDir, '--install')}`);+ }+ if (foreign) lines.push(` ${foreign.name} runs the brain at ${foreign.home}, not this one.`);+ return { installTarget: installed?.target ?? null, report, lines };+}diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 445af1f695..550b7d0647 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -36,7 +36,8 @@ import {import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';import { AITransientError } from '../core/ai/errors.ts';-import { resolvePoolSize } from '../core/db.ts';+import { resolveEmbedConcurrency } from '../core/embed-concurrency.ts';+export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } from '../core/embed-concurrency.ts';import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';import {@@ -1169,43 +1170,6 @@ function preserveCodeMetadata(loaded: any, base: ChunkInput): ChunkInput {return carryChunkMetadata(loaded, base);}-let warnedEmbedConcurrencyClamp = false;--/** Test seam: let the clamp warning print again. */-export function _resetEmbedConcurrencyClampWarningForTest(): void {- warnedEmbedConcurrencyClamp = false;-}--/**- * Parallel page-embedding workers: GBRAIN_EMBED_CONCURRENCY (default 20),- * lowered to a paced run's cap, and on Postgres never above the client pool- * (#5183). Each worker holds a connection across its read and upsert, so more- * workers than pool connections left the run waiting on itself: no progress,- * no error, 0% CPU. An explicit setting that gets lowered is reported once- * per process; the default is lowered silently.- */-export function resolveEmbedConcurrency(- engineKind: string,- paceMaxConcurrency?: number,- env: Record<string, string | undefined> = process.env,- poolSize: number = resolvePoolSize(),-): number {- const explicit = env.GBRAIN_EMBED_CONCURRENCY;- const parsed = parseInt(explicit || '20', 10);- const base = Number.isFinite(parsed) && parsed > 0 ? parsed : 20;- const paced = paceMaxConcurrency ? Math.min(base, paceMaxConcurrency) : base;- if (engineKind !== 'postgres' || paced <= poolSize) return paced;- const clamped = Math.max(1, poolSize);- if (explicit && !warnedEmbedConcurrencyClamp) {- warnedEmbedConcurrencyClamp = true;- process.stderr.write(- `[embed] GBRAIN_EMBED_CONCURRENCY=${explicit} is above the connection pool (${poolSize}); using ${clamped} workers. ` +- `Raise GBRAIN_POOL_SIZE or lower GBRAIN_EMBED_CONCURRENCY to match.\n`,- );- }- return clamped;-}-async function embedAll(engine: BrainEngine,staleOnly: boolean,diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.tsindex c20d57ea2f..d084b29835 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -320,3 +320,23 @@ export function createGlobalLlmHaltTracker(): GlobalLlmHaltTracker {note: () => lastNote,};}++/**+ * Embedding providers whose own documentation says a rejected request is not+ * billed. Only for these does a permanent request-shaped rejection (HTTP 400,+ * 413 or 422; never 401/403/429) release its invocation reservation instead of+ * keeping the maximum debit. Verified per provider:+ * - google: "If your request fails with a 400 or 500 error, you won't be+ * charged for the tokens used." (ai.google.dev/gemini-api/docs/billing,+ * "Am I charged for failed requests?", checked 2026-10-01)+ * OpenAI, Voyage and the other embedding recipes publish no such statement, so+ * their rejections keep the debit (token-limit rejections are handled above).+ */+const UNBILLED_REJECTION_PROVIDERS: ReadonlySet<string> = new Set(['google']);++export function isUnbilledEmbeddingRejection(recipeId: string, err: unknown): boolean {+ if (!UNBILLED_REJECTION_PROVIDERS.has(recipeId)) return false;+ const e = err as { statusCode?: unknown; status?: unknown } | null;+ const status = typeof e?.statusCode === 'number' ? e.statusCode : typeof e?.status === 'number' ? e.status : undefined;+ return status === 400 || status === 413 || status === 422;+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex f0c9f3b5fe..3f7f8db2c7 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -57,7 +57,7 @@ import { parseLlmJson } from '../llm-json.ts';import type { BrainEngine } from '../engine.ts';import { dimsProviderOptions } from './dims.ts';import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';-import { AIConfigError, AITransientError, isStructuredOutputRejection, normalizeAIError } from './errors.ts';+import { AIConfigError, AITransientError, isStructuredOutputRejection, isUnbilledEmbeddingRejection, normalizeAIError } from './errors.ts';import { isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';import { getProviderCapabilities } from './capabilities.ts';import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';@@ -1620,27 +1620,6 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A}}-/**- * Embedding providers whose own documentation says a rejected request is not- * billed. Only for these does a permanent request-shaped rejection (HTTP 400,- * 413 or 422; never 401/403/429) release its invocation reservation instead of- * keeping the maximum debit. Verified per provider:- * - google: "If your request fails with a 400 or 500 error, you won't be- * charged for the tokens used." (ai.google.dev/gemini-api/docs/billing,- * "Am I charged for failed requests?", checked 2026-10-01)- * OpenAI, Voyage and the other embedding recipes publish no such statement, so- * their rejections keep the debit (token-limit rejections are handled above).- */-const UNBILLED_REJECTION_PROVIDERS: ReadonlySet<string> = new Set(['google']);--/** @internal exported for tests; not part of the public gateway API. */-export function isUnbilledEmbeddingRejection(recipeId: string, err: unknown): boolean {- if (!UNBILLED_REJECTION_PROVIDERS.has(recipeId)) return false;- const e = err as { statusCode?: unknown; status?: unknown } | null;- const status = typeof e?.statusCode === 'number' ? e.statusCode : typeof e?.status === 'number' ? e.status : undefined;- return status === 400 || status === 413 || status === 422;-}-/*** Returns true if the error looks like a provider batch-token-limit error.*diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.tsindex efb7f11e55..ab991d5e8b 100644--- a/src/core/cli-force-exit.ts+++ b/src/core/cli-force-exit.ts@@ -85,17 +85,6 @@ export function shouldForceExitAfterMain(return !DAEMON_COMMANDS.has(command);}-/** #5079: is this `serve --http`, whose stdout/stderr are log streams only? */-export function isHttpServeInvocation(argv: string[] = process.argv.slice(2)): boolean {- let rest: string[];- try {- rest = parseGlobalFlags(argv).rest;- } catch {- rest = argv;- }- return rest[0] === 'serve' && rest.includes('--http');-}-/** Floor for the computed backstop deadline (the historical hard deadline). */export const TEARDOWN_DEADLINE_FLOOR_MS = 10_000;/** Allowance for the facts sink's awaited abort() (shutdown of an in-flight job). */diff --git a/src/core/embed-concurrency.ts b/src/core/embed-concurrency.tsnew file mode 100644index 0000000000..9daff449cc--- /dev/null+++ b/src/core/embed-concurrency.ts@@ -0,0 +1,38 @@+import { resolvePoolSize } from './db.ts';++let warnedEmbedConcurrencyClamp = false;++/** Test seam: let the clamp warning print again. */+export function _resetEmbedConcurrencyClampWarningForTest(): void {+ warnedEmbedConcurrencyClamp = false;+}++/**+ * Parallel page-embedding workers: GBRAIN_EMBED_CONCURRENCY (default 20),+ * lowered to a paced run's cap, and on Postgres never above the client pool+ * (#5183). Each worker holds a connection across its read and upsert, so more+ * workers than pool connections left the run waiting on itself: no progress,+ * no error, 0% CPU. An explicit setting that gets lowered is reported once+ * per process; the default is lowered silently.+ */+export function resolveEmbedConcurrency(+ engineKind: string,+ paceMaxConcurrency?: number,+ env: Record<string, string | undefined> = process.env,+ poolSize: number = resolvePoolSize(),+): number {+ const explicit = env.GBRAIN_EMBED_CONCURRENCY;+ const parsed = parseInt(explicit || '20', 10);+ const base = Number.isFinite(parsed) && parsed > 0 ? parsed : 20;+ const paced = paceMaxConcurrency ? Math.min(base, paceMaxConcurrency) : base;+ if (engineKind !== 'postgres' || paced <= poolSize) return paced;+ const clamped = Math.max(1, poolSize);+ if (explicit && !warnedEmbedConcurrencyClamp) {+ warnedEmbedConcurrencyClamp = true;+ process.stderr.write(+ `[embed] GBRAIN_EMBED_CONCURRENCY=${explicit} is above the connection pool (${poolSize}); using ${clamped} workers. ` ++ `Raise GBRAIN_POOL_SIZE or lower GBRAIN_EMBED_CONCURRENCY to match.\n`,+ );+ }+ return clamped;+}diff --git a/src/core/serve-invocation.ts b/src/core/serve-invocation.tsnew file mode 100644index 0000000000..f22757a923--- /dev/null+++ b/src/core/serve-invocation.ts@@ -0,0 +1,25 @@+/**+ * #5079: is this process `serve --http`, whose stdout/stderr are log streams+ * only (the MCP transport is the HTTP socket)? cli.ts installs the cleanup+ * handlers through installCleanupSignalHandlers below, before main(). Kept+ * out of cli-force-exit.ts, which most commands import: the CLI flag-registry+ * generator harvests flag literals from imported modules, so the literal here+ * would widen their accepted flags.+ */+import { parseGlobalFlags } from './cli-options.ts';+import { installSignalHandlers } from './process-cleanup.ts';++export function isHttpServeInvocation(argv: string[] = process.argv.slice(2)): boolean {+ let rest: string[];+ try {+ rest = parseGlobalFlags(argv).rest;+ } catch {+ rest = argv;+ }+ return rest[0] === 'serve' && rest.includes('--http');+}++/** cli.ts entrypoint: the process-cleanup handlers, log-pipe tolerant for `serve --http` only. */+export function installCleanupSignalHandlers(argv: string[] = process.argv.slice(2)): void {+ installSignalHandlers({ keepServingOnLogEpipe: isHttpServeInvocation(argv) });+}diff --git a/test/embedding-rejection-refund.serial.test.ts b/test/embedding-rejection-refund.serial.test.tsindex 5a1a562415..b28b47db86 100644--- a/test/embedding-rejection-refund.serial.test.ts+++ b/test/embedding-rejection-refund.serial.test.ts@@ -14,7 +14,8 @@*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway, embed, resetGateway, __setEmbedTransportForTests, isUnbilledEmbeddingRejection } from '../src/core/ai/gateway.ts';+import { configureGateway, embed, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { isUnbilledEmbeddingRejection } from '../src/core/ai/errors.ts';import { planEmbeddingMigration, readMigrationState, runSchemaTransition } from '../src/core/embedding-migration.ts';import { authorizeMigrationBudget } from '../src/core/embedding-migration-budget.ts';import { withAIInvocationGuard, type AIInvocation } from '../src/core/ai/invocation-guard.ts';diff --git a/test/serve-http-log-epipe.test.ts b/test/serve-http-log-epipe.test.tsindex e5bda5a631..03ecd99a8f 100644--- a/test/serve-http-log-epipe.test.ts+++ b/test/serve-http-log-epipe.test.ts@@ -6,8 +6,9 @@* now drops the write and keeps serving; stdio `serve` and every other* command still exit, since there a broken stdout means the reader left.*- * The broken pipe is real: a child installs the handlers, keeps logging on a- * timer, and the parent destroys the child's stdout/stderr pipes.+ * The broken pipe is real: a child installs the handlers through the same+ * entrypoint cli.ts uses, keeps logging on a timer, and the parent destroys+ * the child's stdout/stderr pipes.*/import { describe, test, expect } from 'bun:test';@@ -16,19 +17,19 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fsimport { join, resolve } from 'path';import { tmpdir } from 'os';-import { isHttpServeInvocation } from '../src/core/cli-force-exit.ts';+import { isHttpServeInvocation } from '../src/core/serve-invocation.ts';-const CLEANUP = resolve(import.meta.dir, '..', 'src', 'core', 'process-cleanup.ts');+const ENTRY = resolve(import.meta.dir, '..', 'src', 'core', 'serve-invocation.ts');-async function logThroughClosedPipe(keepServing: boolean): Promise<{ exit: number | string | null; ticksAfterClose: number }> {+async function logThroughClosedPipe(argv: string[]): Promise<{ exit: number | string | null; ticksAfterClose: number }> {const dir = mkdtempSync(join(tmpdir(), 'gbrain-5079-'));try {const marker = join(dir, 'ticks.log');const script = join(dir, 'child.ts');writeFileSync(script, `-const { installSignalHandlers } = await import(${JSON.stringify(CLEANUP)});+const { installCleanupSignalHandlers } = await import(${JSON.stringify(ENTRY)});const { appendFileSync } = await import('fs');-installSignalHandlers({ keepServingOnLogEpipe: ${keepServing} });+installCleanupSignalHandlers(${JSON.stringify(argv)});let n = 0;setInterval(() => {n++;@@ -55,15 +56,14 @@ setInterval(() => {}describe('#5079 serve --http survives a closed log pipe', () => {- test('with the serve --http setting the process keeps running and logging', async () => {- const r = await logThroughClosedPipe(true);+ test('serve --http keeps running and logging', async () => {+ const r = await logThroughClosedPipe(['serve', '--http', '--port', '3131']);expect(r.exit).toBe('alive');expect(r.ticksAfterClose).toBeGreaterThan(5);}, 30_000);- test('every other command (stdio serve included) still exits on a broken pipe', async () => {- const r = await logThroughClosedPipe(false);- expect(r.exit).not.toBe('alive');+ test('stdio serve and other commands still exit on a broken pipe', async () => {+ for (const argv of [['serve'], ['sync']]) expect((await logThroughClosedPipe(argv)).exit).not.toBe('alive');}, 30_000);test('only `serve --http` gets the setting', () => {