Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Free unattended upkeep: gbrain maintain --unattended, --status, --purge preview, and a doctor check
garrytanba1e34ea9e95
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 927b2836bc..537ba714e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++### A keyless brain keeps itself tidy, and doctor says when upkeep last ran++**`gbrain maintain --unattended` runs the free upkeep a brain needs, and is safe to run from a scheduler.** It runs the same steps as `gbrain maintain --safe` (link and timeline extraction, stale-page checks, the free repair lanes) plus a new bookkeeping cleanup step. It never deletes a page and never starts a paid model call, with one exception you can switch off: on a brain with an embedding key, it embeds pages that are missing embeddings, capped at $1 a day per brain (`maintenance.embed_daily_usd`, 0 turns it off). It works the same on a brain with no git repository and no API keys. A run that has nothing to do, or that finds the brain busy, degraded, behind on migrations or already looked after by `gbrain autopilot`, exits 0 and says why. A step that fails three runs in a row is retried once a week instead of every run, and doctor names it.++- `gbrain maintain --status` shows when upkeep last ran, what each step did, what failed, and when the next run is due.+- A new doctor check, `unattended_maintenance`, reports the same thing. It warns when upkeep hasn't run for 48 hours or a step keeps failing, and its fix is `gbrain maintain --unattended`. A brain where `maintenance.auto` is `false`, or where autopilot runs upkeep, reads as ok.+- `gbrain maintain --purge` previews which soft-deleted pages are past their 72-hour window. `--yes --expect <hash>` purges exactly the previewed set, and refuses with `preview_changed` when the set moved since the preview. Upkeep never purges pages on its own.++### Smaller changes++- The old bookkeeping cleanup inside the cycle's `purge` phase is now its own phase, `bookkeeping_gc`, with the same retentions. It never touches a page, so upkeep can run it while `purge` stays manual. `purge`'s summary now counts only pages, sources and orphaned clone folders.+- `gbrain autopilot --install` on a PGLite brain or a brain with no repository now refuses with a structured error (`autopilot_pglite_daemon`, `autopilot_no_repo`) that points at `gbrain maintain --status`, instead of a plain message.+- doctor's `cycle_freshness` fix no longer asks for spend consent on a brain with no chat or embedding key, since nothing it runs there costs money.+- The cycle's skip message for a phase that needs a filesystem no longer claims the reason is a Postgres or remote engine.++### Itemized changes++- `src/core/maintenance/run.ts` (new): the `--safe` step list (moved from `src/commands/maintain.ts`, which re-exports it), `unattendedPlan`, and `runUnattendedMaintenance`. The run record is `maintenance.last_run` in the database config, so repo-less brains have one. Brain-wide steps run once per run, then one item per source.+- `src/core/maintenance/status.ts` (new): `readUpkeepStatus`, the one view behind `--status` and doctor.+- `src/commands/doctor/checks/unattended-maintenance.ts` (new): the `unattended_maintenance` check.+- `src/core/cycle/bookkeeping-gc.ts` (new) and `src/core/cycle/phase-table.ts`: `bookkeeping_gc`, and a `tier` (`free`, `paid`, `deletes`, `filesystem`) on every phase, which the upkeep step list is tested against.+- `src/core/cycle.ts`: `CycleOpts.stamp` (`full`, `source_only`, `none`) so a partial run can't claim a full cycle, and `deferFactEmbedding` so fact extraction stays free on a keyed brain.+- `src/commands/autopilot-refusals.ts` (new) and `src/core/error-registry.ts`: new codes `autopilot_no_repo`, `autopilot_pglite_daemon`, `cycle_already_running`, `engine_degraded`, `maintenance_disabled` and `maintenance_owned_by_autopilot`.+- Tests: `test/maintenance-unattended.test.ts` (PGLite and Postgres) and `test/e2e/maintain-unattended-keyless-pglite.test.ts`.+## [0.60.699.0] - 2026-11-12### The Ubicloud gate VMs run a current gitdiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 7d9526be4d..d5a6e5dfe6 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -31,8 +31,8 @@ from its last line; never raise the cap.| [Commands (2/6, continued)](key-files/commands-2-continued.md) | More `doctor/checks/*`, `dream-retriage.ts` to `embed.ts`; [tiers and budgets](key-files/doctor-budgets.md) || [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `extract.ts` || [Commands (3/6, continued)](key-files/commands-3-continued.md) | `src/commands/extract-timeline-db.ts` through `frontmatter-install-hook.ts` |-| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `pages-status.ts` |-| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `persistence-admin.ts` to `reindex-search-vector.ts`, `init-mode-picker.ts`, `core/embedding-migration-cli.ts` |+| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `pages-unsearchable.ts` |+| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `pages-status.ts` to `reindex-search-vector.ts`, `init-mode-picker.ts`, `core/embedding-migration-cli.ts` || [Commands (5/6)](key-files/commands-5.md) | `repair.ts` to `skillpack.ts`; [continued](key-files/commands-5-continued.md) || [Commands (6/6)](key-files/commands-6.md) | `sync.ts` to `whoknows.ts` || [Core Ai](key-files/core-ai.md) | `src/core/ai/` gateway, embedding, dims, errors, fallbacks |diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex b3ef3ebc8b..0b978e70d6 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -20,6 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/autopilot-retry-global.ts` — `gbrain autopilot --retry-global [--phase <name>] [--json]` (GBRA-130 A-10): clears `retry_at` on the backed-off phase streaks in `autopilot.global_maintenance.progress` (one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a running `autopilot-global-maintenance` job, whose next progress save can restore the back-off. Test: `test/pathological/a10-global-maintenance-stamp.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 from `automaticSyncPull` (`src/core/persistence/automatic-sync-policy.ts`): a parsed `remote_url` on an unmanaged, unbound source, so local-only and managed 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; it also adds `global_maintenance`, the daemon's latest stall verdict (`readGlobalMaintenanceVerdict` in `src/core/minions/global-maintenance-stall.ts`, null when absent or older than a day), and a non-ok verdict turns exit 0 into 1 (`autopilotStatusExitCode(state, stalled)`); 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. The queued drain's `window` and `timeout_ms` are co-stamped by `resolveAutopilotAutoDrainBounds` (`autopilot-timeout.ts`): the deadline is at least the window plus twice the gateway's `AI_CHAT_TIMEOUT_MS` plus 60 s, because the drain hard-stops at its job deadline (#5809) and checks the window only between items; the window is clamped (to at least 1 s) so that deadline fits the full-cycle anchor (1140 s at the default chat timeout), and a longer interval-derived deadline still wins. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`, `test/autopilot-auto-drain-dispatch.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`. `--install` without `--repo` uses `sync.repo_path`, else the default source's `local_path` (`src/commands/autopilot/install-repo.ts`), and refuses when neither is set; pinned by `test/autopilot-install-repo-fallback-6755.test.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker).+- `src/commands/autopilot-refusals.ts` — GBRA-438: `autopilot --install`'s PGLite and no-repo refusals as `autopilot_pglite_daemon` / `autopilot_no_repo` errors whose fix points at `gbrain maintain --status`.Size ceiling: `scripts/module-size-limits.tsv`. 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, --retry-global; 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`; `readTickHealth` (`autopilot-health.ts`, #7236): one bounded read per tick), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through `autopilotTargetedSteps` in `autopilot-remediation-policy.ts`, which drops manual-only steps) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker). #7239: `readSyncRefusalHolds` holds a source's freshness sync after a refused sync job for the failure cooldown of its refusal count (`freshness_sync_refused`).@@ -47,6 +48,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (the user's approval for `--install`: `installConsent` asks through `requireConsent`, effects `credentials` + `persistent_install`, via the `isTTY`/`promptYesNo` seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`. D2 (`json: 'document'`): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line `database_error` envelope leading with the report keys (`reason` = diagnosis reason, fix = the tier's next step: `--yes` for auto, `--yes --apply-rewrites` with consent `credentials` for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (`unknown_flag`/`invalid_params` exit 2, `requires_local_engine`, `config_error`, `lock_busy`, `not_found`, `no_brain`). Healthy success shape: `test/e2e/cli-json-commands-postgres.test.ts`.--- `src/commands/feedback.ts` — `gbrain feedback status [--json]` (settings, answers recorded, ratings by signal, learned weights, most and least trusted pages with a next step, a one-client-dominance warning, this process's dropped events and stage errors) and `gbrain feedback reset [--source ID] [--page SLUG]` (learned weights back to neutral). Table record `feedback` (post-connect, thin client refused). The doctor check `retrieval_feedback_health` (`src/commands/doctor/checks/retrieval-feedback.ts`, meta category) reports the same counts and warns when one client made over 80% of ratings in 7 days, or when at least `UNRATED_ANSWERS_WARN` (50) answers were recorded with no rating (a host that hides tool result text never shows the answer id; fix `gbrain feedback status --json`).-diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex a1648d1dfe..e2047550a3 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -42,3 +42,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/purge-parks.ts` — `purge_parked_pages` (#6741 C): names parked purges with their last error (only this version's parks, `isParked`); fix `gbrain pages purge-deleted --retry-parked --yes` (preview `--dry-run --json`), consent destructive, ask_user.- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Non-user facts are skipped (#7270). Tests: `test/doctor-unlinked-facts.test.ts`, `test/relink-attribution-7270.test.ts`.+- `src/commands/doctor/checks/unattended-maintenance.ts` — `unattended_maintenance` (GBRA-438): `readUpkeepStatus` as a check; off and autopilot-owned are ok, a brain under 48h with no run is info, a run older than 48h or a step failing 3 runs in a row warns with `gbrain maintain --unattended` (`consent: []` unless an embedding key and a non-zero cap make it paid).diff --git a/docs/architecture/key-files/commands-3-continued.md b/docs/architecture/key-files/commands-3-continued.mdindex bd0493e996..4fa0343112 100644--- a/docs/architecture/key-files/commands-3-continued.md+++ b/docs/architecture/key-files/commands-3-continued.md@@ -13,6 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.+- `src/commands/feedback.ts` — `gbrain feedback status [--json]` (settings, answers recorded, ratings by signal, learned weights, most and least trusted pages with a next step, a one-client-dominance warning, this process's dropped events and stage errors) and `gbrain feedback reset [--source ID] [--page SLUG]` (learned weights back to neutral). Table record `feedback` (post-connect, thin client refused). The doctor check `retrieval_feedback_health` (`src/commands/doctor/checks/retrieval-feedback.ts`, meta category) reports the same counts and warns when one client made over 80% of ratings in 7 days, or when at least `UNRATED_ANSWERS_WARN` (50) answers were recorded with no rating (a host that hides tool result text never shows the answer id; fix `gbrain feedback status --json`).- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises carry a `_friction-protocol.md` callout so agents know when to log friction.- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script carries `# gbrain-hook-version: N` (`FRONTMATTER_HOOK_VERSION`; no marker = version 1, which validated working-tree bytes), lists staged paths with `-z | tr '\0' '\n'`, collects them in a heredoc-fed `while IFS= read -r` loop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONE `gbrain frontmatter validate --staged -- <paths>`, which checks the staged blobs under the strict producer rule and names failures as staged content. `inspectFrontmatterHook(localPath, sourceId?)` (read-only) returns the installed gbrain hook's version, `current`, and the `install-hook --force` refresh argv for doctor and post-upgrade. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then — one resolving to `.githooks` counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore them). Every git spawn passes `env: process.env` (Bun's default child env is a startup snapshot), so `GIT_CONFIG_*` overrides reach the child. A `core.hooksPath` of `/dev/null` in the clone's own (`--local`) config (a URL source a remote caller added: hooks off on purpose; a global or system value does not count; that one read runs with `gitChildEnv()` minus `GIT_CONFIG_GLOBAL`/`SYSTEM`/`NOSYSTEM`, so an inherited `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` cannot redirect it) returns `skipped_hooks_off` before anything is written, `--force` included, `hooksPathBlocker` names it without wiring advice, and `inspectFrontmatterHook` returns null so doctor never proposes a refresh install-hook would skip. Any other blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 24c2083db5..651f8f17d9 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -3,6 +3,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-4.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/commands/pages-status.ts` — `gbrain pages status <slug...> [--source <id>] [--json]` (#7179, read-only, CLI only): one `PageStatus` per slug (at most 200) in the `sources resolve-path` state vocabulary (`searchable`, `pending_embedding`, `chunkless`, `keyword_only`, `quarantined`, `empty`, `missing`, `page_deleted`) with `searchable` true/'keyword'/false, the page's chunks and `unembedded` (no vector in the active column), `embedding_hold` (a held or capped budget row that applies per `budgetRowAppliesFilter`), `hold` (the Git sync hold on its file from `readGitHold`, keyed by the source-root path under the source's slug mode), `source_path`, `in_synced_commit` (the file is in `sources.last_commit`; null without a Git checkout here) and `why` + `fix`; top level `last_commit`, `head`, `at_head`, `embeddings_enabled`. The state is the worst classifier row from `listEmbeddingStateRows` narrowed by `slugs` (quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks read `pending_embedding`, not keyword_only, and its fix is `heldApproveAction` (ask_user, preview first, never a spend). A sync hold's `gitHoldFix` wins over every other fix; otherwise `embeddingStateFix`, none for `searchable`, `missing`, `page_deleted` or pending on a brain keyless by choice. Strict arguments (`invalid_params`, exit 2); a page that is not searchable exits 0. Test: `test/pages-status-7179.test.ts`.- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration,transfer-administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. `transfer-administration.ts` owns `transfer prepare|accept|cancel`: `cancel <source> --expected-epoch <n>` (intent `writer_transfer_cancel`, `--dry-run` previews) runs `cancelWriterTransfer` in `ownership.ts` on the owner host under the coordination lock and `FOR UPDATE`, requires `draining` at that epoch, returns the worktree to `active` and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses `writer_transfer_conflict`. Prepare stamps `prepared_at`. Test: `test/pathological/c5-writer-transfer-cancel.test.ts` (both engines).- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending` unless the receipt carries `diagnostic.owner`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`. #6255: a pending receipt's envelope carries the receipt fix, and `poll_command` plus the `Poll:` line are that same argv.- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`. `--legacy-lock` routes to `src/commands/pglite-repair-legacy-lock.ts` (`runLegacyLockRepair`): `--dry-run` prints `inspectLegacyLock` (`src/core/pglite-legacy-lock.ts`) with `apply_argv`, risk and user_message; apply takes `acquireKernelLockOnly` (5 s; busy → `pglite_busy` reason `timeout`), re-inspects under it, refuses `legacy_lock_removal_refused` (`live_holder` / `network_filesystem` / `filesystem_unverified`, fix = the preview), asks `consentGate` (`destructive`, plan hash bound to the legacy lock; a changed lock refuses `preview_changed`), inspects again after consent (refusal or a changed plan hash refuses; `consentEnv` / `probe` are test seams), then applies and prints the receipt. Pinned by `test/pathological/c3-pglite-legacy-lock.test.ts`.@@ -34,3 +35,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration-cli.ts` — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by `commands/migrate-embeddings.ts`). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.- `test/migrate-embeddings-recovery-cli.serial.test.ts` — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static `EMBEDDING_MIGRATION_RECOVERY` is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by `test/migrate-embeddings-op-contract.serial.test.ts`. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.+- `src/core/maintenance/run.ts` + `src/core/maintenance/status.ts` — GBRA-438 free unattended upkeep. `unattendedPlan` is the `--safe` list plus `bookkeeping_gc`, split into one global item (brain-wide phases, once per window under `gbrain-cycle`) and one item per source; cycles run with `stamp: 'none'` and `deferFactEmbedding` on a keyed brain. `runUnattendedMaintenance` never throws: preflight skips (`maintenance_disabled`, `engine_degraded`, `migrations_pending`, `maintenance_owned_by_autopilot` when `autopilot.last_global_at` is under 48h old, `write_capacity_backpressure`, `cycle_already_running`) exit 0; a failed step records its code (exit 1 for `maintain`) and three same-code failures back the step off to once a week. The embedding step runs under `maintenance.embed_daily_usd` (default $1 per UTC day, 0 = off; spend in `maintenance.embed_spend`). The record is `maintenance.last_run` (database config, so repo-less brains have one). `readUpkeepStatus` is the one view behind `--status` and doctor. Tests: `test/maintenance-unattended.test.ts` (both engines).diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 33bf2a013b..0ae7d0bb7b 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (`fileMatchesSnapshot`, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixable `managed-write-pending` issue with `code: 'managed_write_pending'`, a `reason` (the coordinator refusal's detail, `held_file`, `canonical_file_missing`, `revision_changed`, `not_indexed`), the refusal's own rendered `fix` (never a sync) and the guide link; the run continues (`LintResult.write_path` / `fix_pending` / `pending_issues`, first 50; #5180, `test/managed-lint.test.ts` on both engines). A file the scan listed that is gone by its scan read (ENOENT only; other read errors still fail the run) is reported instead of aborting: a managed `--fix` run asks the coordinator (pending `canonical_file_missing`), otherwise a non-fixable `file-removed-during-scan` issue with code `file_removed_during_scan` and a `gbrain lint <target>` fix; the CLI prints each issue's `Fix:` command and `Docs:` link (`test/lint-file-removed-during-scan.test.ts`). `llm-preamble` matches only a leading run at a body start (file top, after leading frontmatter, or after a whole-page ```markdown wrapper), and repair removes only that run, so a later line that begins like a preamble is never flagged or deleted. A filesystem fix write refused with EACCES/EPERM/EROFS leaves the file unchanged and becomes a non-fixable `fix-not-writable` issue (`code: 'fix_not_writable'`, the errno as `reason`, a user `fix` naming the permission change or `--exclude`) counted in `fix_pending`; the run continues (`test/lint-preamble-anchor.test.ts`). `placeholder-date` and `empty-section` read code-masked text (`stripCodeBlocks`, offset-preserving): a placeholder or a `## ` line inside a fence or inline code is code, an unclosed fence masks to the end of the file, and `empty-section` reads each section's body from the original text, so a section holding only a code block is not empty (`test/lint-3958.test.ts`). #5433: `missing-created` fires only when none of `created`, `event_date`, `date`, `published`, `captured_at`, `ingested_at` parses (`parseDateLoose` on the parsed frontmatter, never a regex; a block YAML could not read is already `frontmatter-yaml-parse`) and is never fixable: `fixContent` no longer promotes a capture timestamp into `created` (ingest time is not creation time, and the cycle's `fix: true` lint phase rewrote every native page), so a page `serializePageToMarkdown` emits stays byte-identical across repeated `--fix` runs; `promoteCreatedFromCapture` stays exported, deprecated, for explicit callers.-- `src/commands/maintain.ts` — `gbrain maintain [--safe] [--dry-run] [--json]`: stale extraction, then one source-scoped `runCycle` per source doctor's `cycle_freshness` names, limited to `MAINTAIN_SAFE_PHASES` (free and never hard-deleting: no `purge`, no paid phase); `maintainSafePhases` also holds back `extract_facts` when an embedding provider is available or the decide conflict slot is on and the repair lanes when an embedding provider is available or `fences.repair.llm` has a model (GST-2246). A source whose cycle throws an item-scoped error is a `blocked` action with `details.code` and `fix` (`gbrain dream --source <id>`) and later sources still cycle (ItemRun site `maintain.cycle_sources`); run-scoped errors and `item_failures_systemic` stop maintain; any blocked action sets exit 1. Tests: `test/maintain.test.ts`, `test/pathological/a41-maintain-sources.test.ts`.+- `src/commands/maintain.ts` — `gbrain maintain [--safe] [--dry-run] [--json]`, `--unattended [--runner <name>]` (one free upkeep run through `src/core/maintenance/run.ts`), `--status` (the upkeep view doctor's `unattended_maintenance` reads) and `--purge` (page-purge preview; `--yes --expect <hash>` applies exactly the previewed set, `purgePreviewHash`). `--safe`: stale extraction, then one source-scoped `runCycle` per source doctor's `cycle_freshness` names, limited to `MAINTAIN_SAFE_PHASES` (the step list lives in `src/core/maintenance/run.ts` and is re-exported here) (free and never hard-deleting: no `purge`, no paid phase); `maintainSafePhases` also holds back `extract_facts` when an embedding provider is available or the decide conflict slot is on and the repair lanes when an embedding provider is available or `fences.repair.llm` has a model (GST-2246). A source whose cycle throws an item-scoped error is a `blocked` action with `details.code` and `fix` (`gbrain dream --source <id>`) and later sources still cycle (ItemRun site `maintain.cycle_sources`); run-scoped errors and `item_failures_systemic` stop maintain; any blocked action sets exit 1. Tests: `test/maintain.test.ts`, `test/maintenance-unattended.test.ts`, `test/e2e/maintain-unattended-keyless-pglite.test.ts`, `test/pathological/a41-maintain-sources.test.ts`.- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.- `src/commands/migrate-engine.ts` — Legacy engine copier (`gbrain migrate --to pglite`, and PGLite → Postgres when `migrate.graduation` is `false`). A PGLite → Postgres move routes to `src/commands/migrate-graduation.ts` (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286: `copyPageToTarget` forwards the full page row (`page_kind`, `source_path`, effective date and its source, `import_filename`, `source_kind`/`source_uri`/`ingested_via`, `ingested_at` restored in the timestamp UPDATE), the frontmatter aliases (`setPageAliases`) and each chunk's code metadata (`carryChunkMetadata`). A page sealed on the source is queued `engine_migration`; one the source had not sealed is queued `engine_migration_source_unsealed` and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, `runMigrateEngine` runs `drainProjections` (moved to `src/core/page-state/projections.ts`; `commands/projections.ts` re-exports it) on the target for the `engine_migration` and `rebuild_failed` reasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned by `test/migrate-full-row-projections.serial.test.ts`, `test/e2e/migrate-full-row-projections-postgres.test.ts` and a D2 case in `test/e2e/migrate-engine-pglite-to-postgres.test.ts`. Open-loop and loop-suppression rows the target refuses (`copyMigrationSimpleTable`, per-row `ItemRun` site `migrate_engine.loop_rows`) are printed with their id and reason, block the config flip and set exit 1; a run-scoped failure stops the copy (`test/pathological/a31-migrate-loop-rows.serial.test.ts`). Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.@@ -39,4 +39,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. `pages status <slug...>` (#7179) lives in `pages-status.ts`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values; adds `semantic_unsearchable` (+keyword_only) and `awaiting_sync` (held files) (#7193). Test: `test/pages-unsearchable.test.ts`.-- `src/commands/pages-status.ts` — `gbrain pages status <slug...> [--source <id>] [--json]` (#7179, read-only, CLI only): one `PageStatus` per slug (at most 200) in the `sources resolve-path` state vocabulary (`searchable`, `pending_embedding`, `chunkless`, `keyword_only`, `quarantined`, `empty`, `missing`, `page_deleted`) with `searchable` true/'keyword'/false, the page's chunks and `unembedded` (no vector in the active column), `embedding_hold` (a held or capped budget row that applies per `budgetRowAppliesFilter`), `hold` (the Git sync hold on its file from `readGitHold`, keyed by the source-root path under the source's slug mode), `source_path`, `in_synced_commit` (the file is in `sources.last_commit`; null without a Git checkout here) and `why` + `fix`; top level `last_commit`, `head`, `at_head`, `embeddings_enabled`. The state is the worst classifier row from `listEmbeddingStateRows` narrowed by `slugs` (quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks read `pending_embedding`, not keyword_only, and its fix is `heldApproveAction` (ask_user, preview first, never a spend). A sync hold's `gitHoldFix` wins over every other fix; otherwise `embeddingStateFix`, none for `searchable`, `missing`, `page_deleted` or pending on a brain keyless by choice. Strict arguments (`invalid_params`, exit 2); a page that is not searchable exits 0. Test: `test/pages-status-7179.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex c3e8d0e632..6677b382c1 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -59,4 +59,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/content-repair.ts` — the `content_repair` maintenance phase (#6377): `runContentRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, kinds?, registry?, now? })` runs the content-repair lane (`src/core/repair/content-lane.ts`) minus `fences`, which `fence_repair` just ran (`contentRepairPhaseKinds()`; with `CONTENT_REPAIR_KINDS` holding only `fences` the phase runs nothing and reports `skipped` / `no_kinds`), through the shared trusted `repairRunner` over every active source: an apply, or a preview on a dry run. Gated on `fences.repair.enabled` (one switch for the whole lane; the summary names `gbrain config set fences.repair.enabled true` and `gbrain repair content`). Deadline min(`CONTENT_REPAIR_PHASE_BUDGET_MS` = 120 s, a third of the maintenance job's remaining time); past it the lane's kind stops `time_budget` (status ok, the next run resumes). Details: `kinds`, `candidates`, `repaired`, `held_by_reason` (each kind's `remaining`, else its per-item outcome reasons), `by_kind` (mode, counts by outcome, spend, oldest hold, stop), `llm_usd`, `oldest_hold_at` / `oldest_hold_age_hours`, `time_budget_ms`, `stopped_reason`; the summary counts holds that wait for a person (`merge_recommended`, `content_repair_needs_human`) and points at `gbrain sync status`. Any stop other than the time budget reports `warn` with the kind's fix; an internal error reports `warn` with its code only unless the cycle is aborted. Brain-global, right after `fence_repair` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-content-repair.test.ts`.- `src/core/cycle/unindexed-files.ts` — the `unindexed_files` maintenance phase (#6865, global, right after `content_repair` through the `REPAIR_LANE_PHASES` dispatch helper): on a managed brain, `runUnindexedFilesPhase(engine, { dryRun, signal?, deadlineAtMs?, now? })` runs one detector pass (`persistence/unindexed-files.ts`) per managed Git source this host owns, least recently scanned first (#7149: no stored result first, then the oldest, so one large source cannot starve the others), under one deadline of min(5 min, a third of the maintenance job's remaining time), each source also stopping at its own budget (`unindexedScanBudgetMs`: 60 s per started 100k live pages); a source the budget stops continues from its stored cursor next run. A real run stores each result and schedules the found files for a re-screen on the next sync (`requestGitHoldRetry`, at most 5,000 per run); a dry run reports without writing. Company-brain sources and sources this host does not own are skipped with a reason; an error on one source is `warn` and the others still run, and `details.complete` is true only when no source stopped at its budget or errored (#8887). Details are counts by source and code, never a path; it never runs on the per-sync path. Classified `no_coordinated_write` (`phase-table.ts`). Tests: `test/unindexed-files.test.ts`, `test/unindexed-files-convergence-7149.test.ts`, `test/managed-phase-matrix.test.ts`.-- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.+- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase. Each entry also carries a `tier` (`free | paid | deletes | filesystem`, GBRA-438) that unattended upkeep's step list is checked against.+- `src/core/cycle/bookkeeping-gc.ts` — the `bookkeeping_gc` phase (GBRA-438), split out of `purge` with the same functions and retentions; it never touches a page.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8d6a62a3d7..18f679f5bd 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -348,6 +348,22 @@ Override: reason `transient`: retryable, exit 11, retryable.|---|---|---|---|---|---|---|| The autopilot job is bound to a different brain. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### autopilot_no_repo++<a id="autopilot_no_repo"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain autopilot --install found no absolute repo directory (sync.repo_path and the default source's local_path are unset or relative), so it installed nothing. | The autopilot daemon syncs a git checkout. A repo-less brain needs no daemon: free upkeep (gbrain maintain --unattended) keeps it maintained. | Pass --repo <absolute-directory> for a brain kept in git, or check free upkeep with gbrain maintain --status. | agent | `repeat the read that failed` | 1 | no |++### autopilot_pglite_daemon++<a id="autopilot_pglite_daemon"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain autopilot --install refused on a PGLite brain: a daemon would hold the single-writer lock all day and block every other gbrain process. | PGLite has one writer. gbrain serve owns the lock and runs the resident sweep; free upkeep runs through gbrain maintain --unattended. | Run gbrain serve, check upkeep with gbrain maintain --status, or re-run with --force for a dedicated-brain daemon. | agent | `repeat the read that failed` | 1 | no |+### backup_dump_failed<a id="backup_dump_failed"></a>@@ -1258,6 +1274,14 @@ More: [docs/guides/repair.md#coverage-gap](../../docs/guides/repair.md#coverage-More: [docs/guides/repair.md#managed-sync-orphans](../../docs/guides/repair.md#managed-sync-orphans)+### cycle_already_running++<a id="cycle_already_running"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Another maintenance cycle holds the brain cycle lock, so this run skipped instead of waiting. | Cycles serialize on the gbrain-cycle lease; the holder releases it when it finishes (or its TTL lapses after a crash). | Wait for the other cycle; unattended upkeep retries on its next turn (gbrain maintain --status shows the last skip). | agent | `repeat the read that failed` | 1 | yes |+### cycle_failed<a id="cycle_failed"></a>@@ -1584,6 +1608,14 @@ More: [docs/guides/enforced-member.md#refused](../../docs/guides/enforced-memberMore: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)+### engine_degraded++<a id="engine_degraded"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The brain database was unreachable (the engine is in degraded mode), so background work such as unattended upkeep skipped this run. | A degraded engine answers from its last state and reconnects on its own; writing maintenance results then would be lost or refused. | Run gbrain doctor --json and report the connection problem it names. | agent | `gbrain doctor --json` | 1 | no |+### engine_embedding_mismatch<a id="engine_embedding_mismatch"></a>@@ -2936,6 +2968,14 @@ More: [docs/guides/open-loops.md#two-detectors](../../docs/guides/open-loops.md#More: [docs/guides/write-refusals.md#maintenance_backpressure](../../docs/guides/write-refusals.md#maintenance_backpressure)+### maintenance_disabled++<a id="maintenance_disabled"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Free unattended upkeep is off on this brain (maintenance.auto is false), so nothing ran. | The person turned upkeep off; doctor reads it as off, not stale. | Turn it back on with gbrain config set maintenance.auto true. | agent | `repeat the read that failed` | 0 | no |+### maintenance_lock_busy<a id="maintenance_lock_busy"></a>@@ -2946,6 +2986,14 @@ More: [docs/guides/write-refusals.md#maintenance_backpressure](../../docs/guidesMore: [docs/guides/cron-schedule.md#dream-beside-autopilot](../../docs/guides/cron-schedule.md#dream-beside-autopilot)+### maintenance_owned_by_autopilot++<a id="maintenance_owned_by_autopilot"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing. | One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database. | Nothing to do; gbrain autopilot --status shows the daemon. | agent | `repeat the read that failed` | 0 | no |+### managed_failure_unsettled<a id="managed_failure_unsettled"></a>diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex dd2ea888de..b61e808291 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -498,6 +498,7 @@ src/core/interaction.ts process_env 3 W6: settings plane out of the coresrc/core/last-retrieved.ts module_collection 2 W6: per-engine state, or mark as a constant tablesrc/core/link-extraction.ts process_env 2 W6: settings plane out of the coresrc/core/link-validity.ts module_collection 1 W6: per-engine state, or mark as a constant table+src/core/maintenance/run.ts fs_import 1 GBRA-438: unattended upkeep checks that a source checkout still exists before running filesystem phases there (a vanished checkout runs the database-only phases instead of failing each run); moves with the W7 filesystem boundarysrc/core/markdown-chunks.ts process_env 1 W6: settings plane out of the coresrc/core/markdown.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/mcp-client.ts module_collection 1 W6: per-engine state, or mark as a constant tablediff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 8753729ace..0384008d84 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -29,7 +29,7 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wavsrc/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane mergesrc/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)-src/core/cycle.ts runCycleUnscoped 1277 #6696 (A5): the body of runCycle, renamed when runCycle became its background-origin wrapper (9 lines shorter); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts); +7 C4: standing_questions phase dispatch block (logic in questions/phase.ts)+src/core/cycle.ts runCycleUnscoped 1290 #6696 (A5): the body of runCycle, renamed when runCycle became its background-origin wrapper (9 lines shorter); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts); +7 C4: standing_questions phase dispatch block (logic in questions/phase.ts); +13 GBRA-438: bookkeeping_gc phase dispatch block (logic in cycle/bookkeeping-gc.ts) and the CycleOpts.stamp switch on the freshness stamp blocksrc/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallbacksrc/core/cycle/extract-facts.ts runExtractFacts 382 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts; +1 #5575 I2 (L1a-taint): the run result sums the write-gate tally each page reconcile returns; +1 merge v0.60.249.0: Wave B PR 1 segmented-page skip (+4, absorbed before) and master growth compose at 382src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b1efc2ba87..49992fe91b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -37,7 +37,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1997 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt names; +1 GBRA-377 PR B: the GBRAIN_HOOK_LANE=skill-resolver dispatch line (logic in core/skills/resolver/hook-lane.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 2027 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +2 GBRA-377 PR B: loadConfig reads a config.json of file-plane settings alone (skills.resolver) as no brain, plus its comment; +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts); re-summed at the #8797 merge (2026 measured); +1 GST-2250: the sources.auto_reconcile.source. KNOWN_CONFIG_KEY_PREFIXES row (prefix rows are data and cannot move)+src/core/config.ts 2029 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +2 GBRA-377 PR B: loadConfig reads a config.json of file-plane settings alone (skills.resolver) as no brain, plus its comment; +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts); re-summed at the #8797 merge (2026 measured); +1 GST-2250: the sources.auto_reconcile.source. KNOWN_CONFIG_KEY_PREFIXES row (prefix rows are data and cannot move); +2 GBRA-438: the maintenance.auto and maintenance.embed_daily_usd KNOWN_CONFIG_KEYS entry and its commentsrc/core/persistence/sync-run.ts 1710 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals); +10 GBRA-133: freezeEntry takes a timer turn between its synchronous Git reads and re-checks the run there (loopYield lives in sync-yield.ts; the turns sit between reads of freezeEntry locals)src/core/persistence/worktree-refresh.ts 1554 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside itsrc/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)@@ -49,6 +49,6 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1761 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3+src/core/behavior-change-notice.ts 1767 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +6 GBRA-438 PR 1: the wave comment and five rows (unattended_maintenance_doctor, bookkeeping_gc_phase, autopilot_refusals_structured, cycle_skip_text, cycle_freshness_keyless_consent; since TBD until the merge slot; rows are data and cannot move)src/core/git/commit-push.ts 1658 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/src/commands/autopilot-refusals.ts b/src/commands/autopilot-refusals.tsnew file mode 100644index 0000000000..fda40f27d7--- /dev/null+++ b/src/commands/autopilot-refusals.ts@@ -0,0 +1,28 @@+/**+ * GBRA-438: the two `gbrain autopilot --install` refusals through the agent+ * error contract (code, why, fix); PGLite and repo-less brains are pointed at+ * free upkeep (`gbrain maintain --status`) instead of a daemon.+ */+import { opError } from '../core/ops/contract.ts';++const UPKEEP_STATUS_FIX = {+ argv: ['gbrain', 'maintain', '--status'], consent: [], actor: 'agent' as const, requires_exclusive: false,+ why: 'Shows when free upkeep last ran and what it left for you; on a brain with no autopilot, gbrain maintain --unattended runs that upkeep (no model calls, no page purge).',+};++/** GBRA-438: the PGLite daemon refusal through the agent error contract (code, why, fix). */+export function autopilotPgliteRefusal(message: string) {+ return opError('autopilot_pglite_daemon', message.split('\n')[0]!,+ 'Run gbrain serve instead (it owns the lock and runs the resident sweep), check free upkeep with gbrain maintain --status, or re-run with --force for a dedicated-brain daemon.',+ { why: 'A PGLite brain has one writer; a daemon holding it all day would block every other gbrain process.', fix: UPKEEP_STATUS_FIX });+}++/** GBRA-438: the no-repo refusal through the agent error contract; a repo-less brain is served by free upkeep instead. */+export function autopilotNoRepoRefusal(engineKind: string) {+ return opError('autopilot_no_repo', 'No repo path: sync.repo_path and the default source local_path are unset or relative.',+ 'Pass --repo <absolute-directory> for a brain kept in git; a repo-less brain needs no autopilot: gbrain maintain --status shows its free upkeep.',+ { why: 'The autopilot daemon syncs a git checkout, so it needs an absolute repo directory.', fix: engineKind === 'pglite' ? UPKEEP_STATUS_FIX+ : { argv: ['gbrain', 'autopilot', '--install', '--repo', '<dir>'], consent: ['persistent_install'], actor: 'user', ask_user: true, requires_exclusive: false,+ inputs: [{ name: 'dir', how: 'The absolute path of the brain repo, from the user.' }], why: 'Installs the autopilot daemon for the named checkout.' } });+}+diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 47e9fc67bd..e1ba485c1d 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -19,6 +19,8 @@import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, unlinkSync, chmodSync, statSync } from 'fs';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { exitCliError } from '../cli/cli-error.ts';+import { autopilotNoRepoRefusal, autopilotPgliteRefusal } from './autopilot-refusals.ts';import { readGlobalMaintenanceVerdict } from '../core/minions/global-maintenance-stall.ts';import { readDaemonStaleAfter } from '../core/autopilot-heartbeat.ts';import { detectExecutionEnvironment } from '../core/execution-env.ts';@@ -902,15 +904,9 @@ async function installDaemon(engine: BrainEngine, args: string[]) {// sweep, embed) then fails to connect. Refuse with guidance; --force for// operators who genuinely want a daemon-owned brain.const guardMsg = pgliteDaemonGuardMessage(engine.kind, args.includes('--force'));- if (guardMsg) {- console.error(guardMsg);- process.exit(1);- }+ if (guardMsg) exitCliError(autopilotPgliteRefusal(guardMsg), 'autopilot');const rawRepoPath = parseArg(args, '--repo') || await installRepoFallback(engine);- if (!rawRepoPath) {- console.error('No repo path: sync.repo_path and the default source local_path are unset or relative. Use --repo <absolute-directory>.');- process.exit(1);- }+ if (!rawRepoPath) exitCliError(autopilotNoRepoRefusal(engine.kind), 'autopilot');// #3696: the daemon runs with an arbitrary cwd (launchd: `/`), so a// relative `--repo .` baked into the wrapper script resolves to a phantom// path at daemon runtime. Resolve NOW, against the installer's cwd.diff --git a/src/commands/doctor/checks/consolidation-cycle.ts b/src/commands/doctor/checks/consolidation-cycle.tsindex c04c3a0663..fbfeb1a9e4 100644--- a/src/commands/doctor/checks/consolidation-cycle.ts+++ b/src/commands/doctor/checks/consolidation-cycle.ts@@ -9,6 +9,7 @@ import { resolveHoursEnv } from '../../../core/env-number.ts';import type { Check } from '../../doctor.ts';import type { Action } from '../../../core/agent-output.ts';import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { isAvailable } from '../../../core/ai/gateway.ts';/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */const _resolveSyncFreshnessHours = resolveHoursEnv;@@ -238,7 +239,7 @@ export async function checkCycleFreshness(}}- const fix = firstStale ? cycleFix(firstStale) : undefined;+ const fix = firstStale ? cycleFix(firstStale, isAvailable('chat') || isAvailable('embedding')) : undefined;if (hasFailures) {return {name: 'cycle_freshness',@@ -287,8 +288,11 @@ async function youngOrEmptySources(engine: BrainEngine, ids: string[], now: numbreturn out;}-function cycleFix(sourceId: string): Action {- return agentFix(['gbrain', 'dream', '--source', sourceId], `Runs one full maintenance cycle for source '${sourceId}' (sync, extract, consolidate). Phases that call a chat model spend provider credits when keys are configured; \`gbrain autopilot --install\` keeps every source cycled.`, 'cycle_freshness',- { consent: ['paid'], requires_exclusive: true });+/** GBRA-438: a keyless brain has no paid phase to run, so the fix asks no paid consent there. */+function cycleFix(sourceId: string, paid: boolean): Action {+ return agentFix(['gbrain', 'dream', '--source', sourceId], paid+ ? `Runs one full maintenance cycle for source '${sourceId}' (sync, extract, consolidate). Phases that call a chat model spend provider credits when keys are configured; \`gbrain autopilot --install\` keeps every source cycled.`+ : `Runs one full maintenance cycle for source '${sourceId}' (sync, extract, consolidate). No model key is configured, so no phase spends anything.`, 'cycle_freshness',+ { consent: paid ? ['paid'] : [], requires_exclusive: true });}diff --git a/src/commands/doctor/checks/unattended-maintenance.ts b/src/commands/doctor/checks/unattended-maintenance.tsnew file mode 100644index 0000000000..814810b330--- /dev/null+++ b/src/commands/doctor/checks/unattended-maintenance.ts@@ -0,0 +1,46 @@+/**+ * unattended_maintenance doctor check (GBRA-438): reads `maintenance.last_run`+ * (or autopilot's freshness when an autopilot owns upkeep) through the same+ * view as `gbrain maintain --status`. Off and autopilot-owned read as ok; a+ * brain younger than 48 hours with no run is information; a run older than+ * 48 hours, or a step failing three runs in a row, warns with the command+ * that runs free upkeep now.+ */+import type { Check } from '../../doctor.ts';+import { checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { readUpkeepStatus, type UpkeepStatus } from '../../../core/maintenance/status.ts';++const name = 'unattended_maintenance';++function details(s: UpkeepStatus): Record<string, unknown> {+ return {+ state: s.state, runner: s.runner, last_run: s.last_run, steps: s.steps.length, next_due_at: s.next_due_at,+ pending_purge_count: s.pending_purge_count, paid_phases_opt_in: s.paid_phases_opt_in,+ embed_spend_today_usd: s.embed_spend_today_usd, embed_daily_cap_usd: s.embed_daily_cap_usd,+ ...(s.failing ? { failing: s.failing } : {}),+ };+}++export async function checkUnattendedMaintenance(engine: Parameters<typeof readUpkeepStatus>[0], opts: { nowMs?: number } = {}): Promise<Check> {+ try {+ const s = await readUpkeepStatus(engine, opts.nowMs);+ if (s.state === 'never') return infoCheck(name, s.message, 'not_applicable', undefined, details(s));+ if (s.state === 'overdue' || s.state === 'failing') return { name, status: 'warn', message: s.message, details: details(s), ...(s.fix ? { fix: s.fix } : {}) };+ return { name, status: 'ok', message: s.message, details: details(s) };+ } catch (error) {+ return checkError(name, 'read the unattended upkeep record', error);+ }+}++async function runUnattendedMaintenance(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push(await checkUnattendedMaintenance(connectedEngine(ctx)));+ return checks;+}++export const unattendedMaintenanceEntry: DoctorEntry = {+ name: 'unattended_maintenance',+ emits: ['unattended_maintenance'],+ run: runUnattendedMaintenance,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex caa61be819..b366c47d0b 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -90,6 +90,7 @@ import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/quimport { imageEmbeddingCoverageEntry } from './checks/image-embedding-coverage.ts';import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';import { globalMaintenanceStalledEntry } from './checks/global-maintenance-stalled.ts';+import { unattendedMaintenanceEntry } from './checks/unattended-maintenance.ts';import { embedBackfillStalledEntry } from './checks/embed-backfill-stalled.ts';import { contentDriftSweepEntry } from './checks/content-drift-sweep.ts';import { connectorAccountMismatchEntry } from './checks/connector-account-mismatch.ts';@@ -274,6 +275,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [queueHealthEntry,globalMaintenanceTimeoutsEntry,globalMaintenanceStalledEntry,+ unattendedMaintenanceEntry,embedBackfillStalledEntry,contentDriftSweepEntry,connectorAccountMismatchEntry,diff --git a/src/commands/maintain.ts b/src/commands/maintain.tsindex 6d7203164c..4a088ae62d 100644--- a/src/commands/maintain.ts+++ b/src/commands/maintain.ts@@ -13,18 +13,15 @@import { existsSync } from 'fs';import { isAbsolute } from 'path';-import { isAvailable } from '../core/ai/gateway.ts';-import { fenceRepairLlmEnabled } from '../core/fence-repair/config.ts';-import { resolveFenceRepairModel } from '../core/fence-repair/model.ts';-import { resolveContentRepairModel } from '../core/content-repair/llm.ts';-import { loadConfigSnapshot } from '../core/config-snapshot.ts';-import { readDecideConfig } from '../core/ai/decide/config.ts';-import { hasTypesafeKey } from '../core/ai/decide/index.ts';+import { createHash } from 'crypto';import type { BrainEngine } from '../core/engine.ts';import type { BrainHealth } from '../core/types.ts';import { buildChecks, computeDoctorReport, type DoctorReport, type Check } from './doctor.ts';import { extractStaleFromDB } from './extract.ts';-import { resolveCyclePhases, runCycle, type CycleReport, type CyclePhase } from '../core/cycle.ts';+import { runCycle, type CycleReport } from '../core/cycle.ts';+import { maintainSafePhases, readSafePhaseProviders, isValidRunnerName, runUnattendedMaintenance, type UpkeepOutcome } from '../core/maintenance/run.ts';+import { readUpkeepStatus } from '../core/maintenance/status.ts';+import { cliRenderContext, noticeBlock, renderAction, renderNotice, type Action } from '../core/agent-output.ts';import { ItemRun } from '../core/item-failure.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -42,6 +39,19 @@ export interface MaintainOptions {safe: boolean;dryRun: boolean;help: boolean;+ unattended: boolean;+ runner: string;+ status: boolean;+ purge: boolean;+ yes: boolean;+ expect: string | null;+}++function flagValue(args: string[], flag: string): string | null {+ const i = args.indexOf(flag);+ if (i >= 0) return args[i + 1] ?? '';+ const eq = args.find((a) => a.startsWith(flag + '='));+ return eq ? eq.slice(flag.length + 1) : null;}export interface MaintainReport {@@ -64,6 +74,12 @@ export function parseMaintainArgs(args: string[]): MaintainOptions {safe,dryRun: args.includes('--dry-run') || !safe,help: args.includes('--help') || args.includes('-h'),+ unattended: args.includes('--unattended'),+ runner: flagValue(args, '--runner') ?? 'cli',+ status: args.includes('--status'),+ purge: args.includes('--purge'),+ yes: args.includes('--yes'),+ expect: flagValue(args, '--expect'),};}@@ -80,44 +96,8 @@ export function extractCycleFreshnessSourceIds(checks: Check[]): string[] {return [...ids].sort();}-/**- * The cycle phases `--safe` may run: free, and never hard-deleting. The page- * purge and every phase that calls a model stay with `gbrain dream` and- * `gbrain pages purge-deleted`.- */-export const MAINTAIN_SAFE_PHASES: readonly CyclePhase[] = [- 'lint', 'backlinks', 'sync', 'fence_repair', 'content_repair', 'unindexed_files',- 'extract', 'extract_facts', 'resolve_symbol_edges', 'recompute_emotional_weight',- 'consolidate', 'orphans', 'schema-suggest',-];--/** Which providers a safe phase would call on this brain; those phases are held back. */-export interface SafePhaseProviders {- embedding: boolean;- decideConflict: boolean;- fenceRepairModel: boolean;- contentRepairModel: boolean;-}--export function maintainSafePhases(sourceId: string, providers: SafePhaseProviders): { phases: CyclePhase[]; held: CyclePhase[] } {- const held: CyclePhase[] = [];- if (providers.embedding || providers.decideConflict) held.push('extract_facts');- if (providers.fenceRepairModel || providers.embedding) held.push('fence_repair');- if (providers.contentRepairModel || providers.embedding) held.push('content_repair');- const phases = resolveCyclePhases(undefined, sourceId)- .filter((phase) => MAINTAIN_SAFE_PHASES.includes(phase) && !held.includes(phase));- return { phases, held };-}--async function readSafePhaseProviders(engine: BrainEngine): Promise<SafePhaseProviders> {- const repairLlm = await fenceRepairLlmEnabled(engine);- return {- embedding: isAvailable('embedding'),- decideConflict: readDecideConfig(await loadConfigSnapshot(engine), { typesafeKey: hasTypesafeKey() }).slots.conflict.mode !== 'off',- fenceRepairModel: repairLlm && (await resolveFenceRepairModel(engine)) !== null,- contentRepairModel: repairLlm && (await resolveContentRepairModel(engine)) !== null,- };-}+// The step list --safe shares with unattended upkeep lives in the runner core.+export { MAINTAIN_SAFE_PHASES, maintainSafePhases, type SafePhaseProviders } from '../core/maintenance/run.ts';async function buildDoctorReport(engine: BrainEngine): Promise<DoctorReport> {const checks = await buildChecks(engine, ['--json', '--scope=brain']);@@ -241,13 +221,24 @@ export async function runMaintain(engine: BrainEngine, args: string[]): Promise<const opts = parseMaintainArgs(args);if (opts.help) {console.log(`Usage: gbrain maintain [--safe] [--dry-run] [--json]+ gbrain maintain --unattended [--runner <name>] [--json]+ gbrain maintain --status [--json]+ gbrain maintain --purge [--yes --expect <hash>] [--json]Conservative self-healing maintenance.Modes:- --dry-run Preview safe actions without writes. Default when --safe is absent.- --safe Apply safe actions: stale extraction and source cycle freshness.- --json Emit a structured before/action/after report.+ --dry-run Preview safe actions without writes. Default when --safe is absent.+ --safe Apply safe actions: stale extraction and source cycle freshness.+ --unattended Run free upkeep once when it is due: links, timeline, facts index,+ bookkeeping GC and, with an embedding key, the embedding backlog+ within maintenance.embed_daily_usd (default $1 a day; 0 = off).+ Never purges a page or calls a chat model. Records+ maintenance.last_run; --runner names the caller (default cli).+ --status Show the last upkeep run, the next due time and what waits for you.+ --purge Preview the page purge (soft-deleted pages past purge.retention_hours);+ apply it with --yes --expect <hash> from the preview.+ --json Emit a structured report.Not auto-applied:source-file frontmatter fixes, schema-pack upgrades, atom-pack changes,@@ -257,6 +248,9 @@ Not auto-applied:`);return;}+ if (opts.unattended) return void await runUnattendedCli(engine, opts);+ if (opts.status) return void await runStatusCli(engine, opts);+ if (opts.purge) return void await runPurgeCli(engine, opts);const beforeHealth = await engine.getHealth();const beforeDoctor = await buildDoctorReport(engine);@@ -302,3 +296,83 @@ function printMaintainReport(report: MaintainReport): void {console.log('Run `gbrain maintain --safe` to apply safe actions.');}}++function printNotice(code: string, why: string, fix: Action | undefined): void {+ process.stderr.write(noticeBlock(renderNotice({ code, kind: 'info', why, ...(fix ? { fix } : {}) }, cliRenderContext())) + '\n');+}++async function runUnattendedCli(engine: BrainEngine, opts: MaintainOptions): Promise<UpkeepOutcome | void> {+ if (!isValidRunnerName(opts.runner)) {+ console.error(`--runner must be a short lowercase name (letters, digits, - or _), got "${opts.runner}".`);+ setCliExitVerdict(2);+ return;+ }+ const outcome = await runUnattendedMaintenance(engine, { runner: opts.runner });+ if (outcome.exit) setCliExitVerdict(outcome.exit);+ if (opts.json) {+ console.log(JSON.stringify({ ...outcome, ...(outcome.fix ? { fix: renderAction(outcome.fix, cliRenderContext()) } : {}) }, null, 2));+ return outcome;+ }+ console.log(outcome.message);+ for (const step of outcome.record?.steps ?? []) {+ if (outcome.status !== 'ran') break;+ console.log(` ${step.status}: ${step.name} (${step.scope})${step.code ? ` ${step.code}` : step.reason ? ` ${step.reason}` : ''}`);+ }+ if (outcome.status === 'skipped' && outcome.code) printNotice(outcome.code, outcome.message, outcome.fix);+ return outcome;+}++async function runStatusCli(engine: BrainEngine, opts: MaintainOptions): Promise<void> {+ const status = await readUpkeepStatus(engine);+ const { fix, ...rest } = status;+ if (opts.json) {+ console.log(JSON.stringify({ ...rest, ...(fix ? { fix: renderAction(fix, cliRenderContext()) } : {}) }, null, 2));+ return;+ }+ console.log(status.message);+ if (status.last_run) console.log(`Last run: ${status.last_run} (${status.runner}), next due: ${status.next_due_at}`);+ if (status.held.length) console.log(`Held back on this brain (they would call a provider): ${status.held.join(', ')}`);+ console.log(`Left for you (paid, opt-in; gbrain dream or an autopilot runs them): ${status.paid_phases_opt_in.join(', ')}`);+ if (fix) console.log(`Fix: ${fix.argv!.join(' ')}: ${fix.why}`);+}++/** Hash of exactly what a purge would remove, so --expect binds the apply to the preview the person saw. */+export function purgePreviewHash(retentionHours: number, pages: ReadonlyArray<{ source_id?: string; slug: string }>): string {+ const keys = pages.map((p) => `${p.source_id ?? 'default'}/${p.slug}`).sort();+ return createHash('sha256').update(JSON.stringify({ retentionHours, keys })).digest('hex').slice(0, 12);+}++async function runPurgeCli(engine: BrainEngine, opts: MaintainOptions): Promise<void> {+ const [{ selectPurgeCandidates, purgeDeletedPagesCoordinated }, { readPurgeRetentionHours }] = await Promise.all([+ import('../core/persistence/purge-deleted.ts'), import('../core/sync-reconcile.ts')]);+ const retention = await readPurgeRetentionHours(engine);+ const selection = await selectPurgeCandidates(engine, retention, { automatic: true });+ const pages: Array<{ source_id?: string; slug: string }> = selection.managed+ ? selection.candidates.map((c) => ({ source_id: c.source_id, slug: c.slug }))+ : selection.slugs.map((slug) => ({ slug }));+ const hash = purgePreviewHash(retention, pages);+ const apply = ['gbrain', 'maintain', '--purge', '--yes', '--expect', hash];+ if (!opts.yes) {+ const preview = { mode: 'preview', retention_hours: retention, count: pages.length, pages: pages.slice(0, 50), blocked: selection.blocked.length, hash,+ ...(pages.length ? { apply: renderAction({ argv: apply, consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ why: `Permanently deletes the ${pages.length} page(s) listed (soft-deleted more than ${retention}h ago); gbrain restore cannot bring them back.` }, cliRenderContext()) } : {}) };+ if (opts.json) { console.log(JSON.stringify(preview, null, 2)); return; }+ console.log(`${pages.length} soft-deleted page(s) are past the ${retention}h recovery window.`);+ for (const p of pages.slice(0, 50)) console.log(` ${p.source_id ?? 'default'}/${p.slug}`);+ if (pages.length > 50) console.log(` ...and ${pages.length - 50} more`);+ if (pages.length) console.log(`Nothing was deleted. To purge exactly these, run: ${apply.join(' ')}`);+ return;+ }+ if (opts.expect !== hash) {+ const why = opts.expect ? `The purge set changed since the preview (expected ${opts.expect}, now ${hash}); nothing was deleted.` : 'A purge needs --expect <hash> from the preview; nothing was deleted.';+ setCliExitVerdict(3);+ const fix: Action = { argv: ['gbrain', 'maintain', '--purge'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the current purge set and its hash; it deletes nothing.' };+ if (opts.json) console.log(JSON.stringify({ mode: 'refused', code: 'preview_changed', why, hash, fix: renderAction(fix, cliRenderContext()) }, null, 2));+ else console.error(`${why} Preview again: gbrain maintain --purge`);+ return;+ }+ const result = await purgeDeletedPagesCoordinated(engine, retention, { automatic: true });+ if (result.error) setCliExitVerdict(1);+ if (opts.json) { console.log(JSON.stringify({ mode: 'applied', purged: result.count, slugs: result.slugs, blocked: result.blocked, deferred: result.deferred, ...(result.error ? { error: result.error } : {}) }, null, 2)); return; }+ console.log(`Purged ${result.count} page(s).${result.blocked.length ? ` ${result.blocked.length} blocked; see --json.` : ''}`);+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 590ab065e6..7b2c56094a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1563,6 +1563,12 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.693.0', id: 'member_save_withdrawn_scope_gst2346', text: 'A remote `remember` onto a member\'s own page (`memory/members/<id>`) is refused `fact_withdrawn` only when that member could read what was withdrawn: a fact on its own page, its own copy withdrawn by the brain host, or for the brain owner a fact it reads. A claim withdrawn by the brain host or the owner that the member never read no longer refuses its save: the fact saves as the member\'s own active row with the same reply as a new claim. A schema migration makes the database insert guards mark a row on a member page only by that page\'s own withdrawals; a withdrawal still expires matching rows on member pages when it is made, and strikes them in the page\'s file, so an import of a member page\'s file no longer marks a row withdrawn by a withdrawal of another subject. The same holds for each item of a `remember` batch (`items`), a replay with the same `request_id`, a `replaces` and the write receipt (`get_write_request`). Trusted local saves keep the check they had.' },{ since: '0.60.694.0', id: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },{ since: '0.60.694.0', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ // GBRA-438 PR 1: free unattended upkeep (core/maintenance/run.ts); since TBD until the merge slot, rows are data and cannot move.+ { since: 'TBD', id: 'unattended_maintenance_doctor_gbra438', text: '`gbrain doctor` has a new check, `unattended_maintenance`, which reads the free-upkeep record `maintenance.last_run`: it warns (and so can lower doctor status from healthy) when no upkeep run is recorded on a brain older than 48 hours, when the last run is older than 48 hours, or when one step failed three runs in a row; the fix is `gbrain maintain --unattended`. Upkeep turned off (`maintenance.auto false`) or owned by an autopilot reads ok. New commands: `gbrain maintain --unattended`, `--status` and `--purge` (preview, then `--yes --expect <hash>`).' },+ { since: 'TBD', id: 'bookkeeping_gc_phase_gbra438', text: 'The dream cycle has a new phase, `bookkeeping_gc`, after `purge`: it now does the retention GC that `purge` used to do (op checkpoints, brainstorm checkpoints, batch-retry audit files, volunteer events, decision receipts, applied captures, retrieval feedback), with the same retentions. `gbrain dream --json` reports those counts under `bookkeeping_gc` instead of `purge`, whose details keep only sources, pages and orphan clones; `--phase purge` no longer runs the GC.' },+ { since: 'TBD', id: 'autopilot_refusals_structured_gbra438', text: '`gbrain autopilot --install` refusals (a PGLite brain without --force, no repo path) now go through the agent error contract: codes `autopilot_pglite_daemon` and `autopilot_no_repo`, a why, a fix and `--json` output, instead of a bare line on stderr; PGLite and repo-less users are pointed to `gbrain maintain --status`.' },+ { since: 'TBD', id: 'cycle_skip_text_gbra438', text: 'A dream cycle phase skipped for want of a checkout no longer says (postgres/remote engine), which was wrong on PGLite: the summary is now: requires a local brain directory; this brain has no on-disk checkout; pass --dir <path> to run filesystem phases. The reason code `no_brain_dir` is unchanged.' },+ { since: 'TBD', id: 'cycle_freshness_keyless_consent_gbra438', text: 'On a brain with no chat or embedding key, the `cycle_freshness` doctor fix (`gbrain dream --source <id>`) now asks no paid consent (`consent: []`, so `next: run`), because no phase it runs can spend.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cca0fb7231..d35240491f 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -21,7 +21,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],- 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],+ 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--unattended', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -78,14 +78,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--dir', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--unattended', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scan-secrets', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--older-than', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--runner', '--safe', '--scan-secrets', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unattended', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex 433cda32ca..20d875b2a0 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1797,6 +1797,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['embed.backfill_cooldown_min','embed.backfill_max_usd_per_source_24h','embed.backfill_max_usd',+ // GBRA-438: free unattended upkeep on/off and its daily embedding cap (core/maintenance/run.ts).+ 'maintenance.auto', 'maintenance.embed_daily_usd',// Brain-level default source. Read by source-resolver.ts tier 5// (`engine.getConfig('sources.default')`) and written by// `gbrain sources default <id>`. Listed here so `gbrain config set`diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex e3d6d56f30..f891b8936b 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -94,6 +94,8 @@ export type CyclePhase =// Lane D — runs queued facts-absorb jobs on PGLite (no job worker there); bounded per run and per day.| 'facts_drain'| 'embed' | 'orphans' | 'purge'+ // GBRA-438: bookkeeping GC split out of purge (retention-bound rows and files, never a page).+ | 'bookkeeping_gc'// v0.39 T12: schema-suggest passive trigger (D3 + D4 plan-eng-review).// Wraps runSuggest() — same library the CLI verb + EIIRP call.| 'schema-suggest'@@ -227,6 +229,9 @@ export const ALL_PHASES: CyclePhase[] = [// the 72h recovery window. Runs last so the rest of the cycle sees the// recoverable set; the purge then drops what's expired.'purge',+ // GBRA-438: the bookkeeping GC that used to ride inside purge, as its own+ // step so unattended upkeep can run it without the page purge.+ 'bookkeeping_gc',];/**@@ -379,6 +384,7 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['skillopt','embed','purge',+ 'bookkeeping_gc',]);export type PhaseStatus = 'ok' | 'warn' | 'fail' | 'skipped';@@ -633,6 +639,20 @@ export interface CycleOpts {deadlineAtMs?: number | null;/** Internal: minion job id that owns any phase-created private dream-inline queues. */privateQueueOwnerJobId?: number | null;+ /**+ * GBRA-438: which freshness stamps a successful source-scoped cycle writes.+ * `full` (the default, unchanged behaviour) writes `last_source_cycle_at`+ * and `last_full_cycle_at`; `source_only` writes the first; `none` writes+ * neither, so free unattended upkeep never reads as a cycle to doctor's+ * `cycle_freshness` or the autopilot fan-out gate.+ */+ stamp?: 'full' | 'source_only' | 'none';+ /**+ * GBRA-438: extract_facts writes new fact rows without calling the+ * embedding provider; their vectors wait for the stale-fact embed drain+ * (`gbrain embed --stale --facts`, or unattended upkeep's capped step).+ */+ deferFactEmbedding?: boolean;}// ─── Lock primitives ───────────────────────────────────────────────@@ -1507,6 +1527,7 @@ async function runPhaseExtractFacts(dryRun: boolean,changedSlugs?: string[],signal?: AbortSignal,+ deferEmbedding?: boolean,): Promise<PhaseResult> {try {const { runExtractFacts } = await import('./cycle/extract-facts.ts');@@ -1517,6 +1538,7 @@ async function runPhaseExtractFacts(sourceId,brainDir: brainDir ?? undefined,signal,+ ...(deferEmbedding ? { deferEmbedding } : {}),});// v0.35.5: phantom-redirect counters bubble up alongside the existing@@ -1777,54 +1799,6 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas// #5405: coordinated on managed brains; #7130: `automatic` keeps managed sync tombstones with no live twin.const purgedPages = await purgeDeletedPagesCoordinated(engine, retentionHours, { automatic: true });const purgedClones = await purgeOrphanClones(retentionHours);- // v0.36+ folded scope item +C: GC stale op_checkpoints rows.- // 7-day TTL is deliberately generous; any reasonable long-running op- // finishes inside that window. Cheap (few KB per row).- let purgedCheckpoints = 0;- try {- const { purgeStaleCheckpoints } = await import('./op-checkpoint.ts');- purgedCheckpoints = await purgeStaleCheckpoints(engine, 7);- } catch {- // Non-fatal: op_checkpoints table may not exist yet on pre-v67 brains.- }- // v0.37.x — TX3 / A5: GC stale brainstorm checkpoints (filesystem-side).- // 7-day mtime window mirrors op_checkpoints. Wrapped in try/catch- // because the brainstorm dir may not exist on a brain that's never- // run a brainstorm.- let purgedBrainstormCheckpoints = 0;- try {- const { gcStaleCheckpoints } = await import('./brainstorm/checkpoint.ts');- purgedBrainstormCheckpoints = gcStaleCheckpoints(7);- } catch {- // Non-fatal.- }- // v0.41.18.0 codex H-8 — actual 30-day pruning of batch-retry audit JSONL.- // The pre-v0.41.18 plan promised this "by convention"; this is the real- // implementation. Never throws — best-effort GC.- let purgedBatchRetryAuditFiles = 0;- try {- const { pruneOldBatchRetryAuditFiles } = await import('./audit/batch-retry-audit.ts');- purgedBatchRetryAuditFiles = pruneOldBatchRetryAuditFiles(30).removed;- } catch {- // Non-fatal.- }- // v0.43 (#2095) — 90-day GC of the volunteered-context feedback log.- // Conversation-adjacent telemetry must never grow unbounded. Best-effort:- // purgeStaleVolunteerEvents returns 0 on pre-v117 brains (no table).- let purgedVolunteerEvents = 0;- try {- const { purgeStaleVolunteerEvents } = await import('./context/volunteer-events.ts');- purgedVolunteerEvents = await purgeStaleVolunteerEvents(engine);- } catch {- // Non-fatal.- }- // System One: decision receipts past decide.receipts.retention_days (reported only when rows were pruned).- let purgedDecisionReceipts = 0;- try { purgedDecisionReceipts = await (await import('./ai/decide/store.ts')).pruneReceiptsForCycle(engine); } catch { /* pre-v179 brain */ }- // GST-1856: applied-capture records past 90 days (ingestion/applied-captures.ts; 0 on a brain before v296).- const purgedAppliedCaptures = await (await import('./ingestion/applied-captures.ts')).purgeStaleAppliedCaptures(engine);- let purgedFeedback = { events: 0, weights: 0 };- try { purgedFeedback = await (await import('./feedback/store.ts')).pruneRetrievalFeedback(engine, (await (await import('./feedback/settings.ts')).loadFeedbackSettings(engine)).eventRetentionDays); } catch { /* pre-v207 brain */ }return {phase: 'purge',status: purgePhaseStatus(purgedPages), error: purgedPages.error, // #6741: a writer in recovery or a parked page warns@@ -1833,10 +1807,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas`purged ${purgedSources.length} source(s)` +(purgeResult.blocked.length > 0 ? ` (${purgeResult.blocked.length} blocked, see details)` : '') +`, ${purgedPages.count} page(s)${purgePhaseNote(purgedPages)}, ` +- `${purgedClones.count} orphan clone temp dir(s), ${purgedCheckpoints} stale op_checkpoint(s), ` +- `${purgedBrainstormCheckpoints} stale brainstorm checkpoint(s), ` +- `${purgedBatchRetryAuditFiles} stale batch-retry audit file(s), ` +- `and ${purgedVolunteerEvents} stale volunteer event(s)`,+ `and ${purgedClones.count} orphan clone temp dir(s)`,details: {purged_sources_count: purgedSources.length,purged_sources_blocked: purgeResult.blocked,@@ -1845,13 +1816,6 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phaspurged_orphan_clone_names: purgedClones.names,purged_sources: purgedSources,purged_page_slugs: purgedPages.slugs,- purged_checkpoints_count: purgedCheckpoints,- purged_brainstorm_checkpoints_count: purgedBrainstormCheckpoints,- purged_batch_retry_audit_files_count: purgedBatchRetryAuditFiles,- purged_volunteer_events_count: purgedVolunteerEvents,- ...(purgedDecisionReceipts > 0 ? { purged_decision_receipts_count: purgedDecisionReceipts } : {}),- ...(purgedAppliedCaptures > 0 ? { purged_applied_captures_count: purgedAppliedCaptures } : {}),- ...(purgedFeedback.events + purgedFeedback.weights > 0 ? { purged_retrieval_feedback_events_count: purgedFeedback.events, purged_retrieval_weights_count: purgedFeedback.weights } : {}),},};} catch (e) {@@ -1983,8 +1947,8 @@ async function runCycleUnscoped(phase,status: 'skipped',duration_ms: 0,- summary: 'requires a local brain directory; this brain has no on-disk checkout '- + '(postgres/remote engine); pass --dir <path> to run filesystem phases',+ summary: 'requires a local brain directory; this brain has no on-disk checkout; '+ + 'pass --dir <path> to run filesystem phases',details: { reason: 'no_brain_dir' },});@@ -2448,7 +2412,7 @@ async function runCycleUnscoped(const syncRanButFailed = syncAttempted && syncPagesAffected === undefined;const xfSlugs = syncRanButFailed ? [] : (sourceWindow?.slugs ?? syncPagesAffected);const { result, duration_ms } = await timePhase(() =>- runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal), 'extract_facts');+ runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal, opts.deferFactEmbedding), 'extract_facts');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -3088,6 +3052,21 @@ async function runCycleUnscoped(}await safeYield(opts.yieldBetweenPhases);}++ if (phases.includes('bookkeeping_gc')) {+ checkAborted(cycleSignal);+ if (!engine) {+ phaseResults.push({ phase: 'bookkeeping_gc', status: 'skipped', duration_ms: 0, summary: 'no database connected', details: { reason: 'no_database' } });+ } else {+ progress.start('cycle.bookkeeping_gc');+ const { result, duration_ms } = await timePhase(() => import('./cycle/bookkeeping-gc.ts').then(m => m.runPhaseBookkeepingGc(engine, dryRun))+ .catch((e): PhaseResult => ({ phase: 'bookkeeping_gc', status: 'fail', duration_ms: 0, summary: 'bookkeeping GC failed', details: {}, error: makeErrorFromException(e) })), 'bookkeeping_gc');+ result.duration_ms = duration_ms;+ phaseResults.push(result);+ progress.finish();+ }+ await safeYield(opts.yieldBetweenPhases);+ }} catch (e) {// W0 (Tier-1 #1): a lock steal aborts the run at the next boundary/raced// await. Completed phases' DB writes are durable (persisted-and-resumable@@ -3175,7 +3154,7 @@ async function runCycleUnscoped(// timestamp post-failure is still higher than missing a successful write, so// the stamp itself is unchanged — only the reporting is.let stampWriteFailed: { source_id: string; error: string } | undefined;- if (opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {+ if ((opts.stamp ?? 'full') !== 'none' && opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {try {const nowIso = new Date().toISOString();// #2194 fix #3 (the cycle split): `last_source_cycle_at` is the NEW gate@@ -3187,7 +3166,7 @@ async function runCycleUnscoped(// flagged in the rejected skip-based design.await engine.updateSourceConfig(opts.sourceId, {last_source_cycle_at: nowIso,- last_full_cycle_at: nowIso,+ ...(opts.stamp === 'source_only' ? {} : { last_full_cycle_at: nowIso }),...sourceCycleWindowStamp(phaseResults, sourceWindow),});} catch (e) {diff --git a/src/core/cycle/bookkeeping-gc.ts b/src/core/cycle/bookkeeping-gc.tsnew file mode 100644index 0000000000..6bb52b4c36--- /dev/null+++ b/src/core/cycle/bookkeeping-gc.ts@@ -0,0 +1,80 @@+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';++/**+ * GBRA-438 — bookkeeping GC, split out of purge with the same functions and+ * retentions: op_checkpoints and brainstorm checkpoints (7 days), batch-retry+ * audit files (30 days), volunteer events (90 days), decision receipts,+ * applied captures and retrieval feedback (their own retention settings). It+ * never deletes a page, so unattended upkeep may run it (decision C1).+ */+export async function runPhaseBookkeepingGc(engine: BrainEngine, dryRun: boolean): Promise<PhaseResult> {+ if (dryRun) {+ return { phase: 'bookkeeping_gc', status: 'ok', duration_ms: 0, summary: 'dry-run: skipped bookkeeping GC', details: { dry_run: true } };+ }+ // v0.36+ folded scope item +C: GC stale op_checkpoints rows.+ // 7-day TTL is deliberately generous; any reasonable long-running op+ // finishes inside that window. Cheap (few KB per row).+ let purgedCheckpoints = 0;+ try {+ const { purgeStaleCheckpoints } = await import('../op-checkpoint.ts');+ purgedCheckpoints = await purgeStaleCheckpoints(engine, 7);+ } catch {+ // Non-fatal: op_checkpoints table may not exist yet on pre-v67 brains.+ }+ // v0.37.x — TX3 / A5: GC stale brainstorm checkpoints (filesystem-side).+ // 7-day mtime window mirrors op_checkpoints. Wrapped in try/catch+ // because the brainstorm dir may not exist on a brain that's never+ // run a brainstorm.+ let purgedBrainstormCheckpoints = 0;+ try {+ const { gcStaleCheckpoints } = await import('../brainstorm/checkpoint.ts');+ purgedBrainstormCheckpoints = gcStaleCheckpoints(7);+ } catch {+ // Non-fatal.+ }+ // v0.41.18.0 codex H-8 — actual 30-day pruning of batch-retry audit JSONL.+ // The pre-v0.41.18 plan promised this "by convention"; this is the real+ // implementation. Never throws — best-effort GC.+ let purgedBatchRetryAuditFiles = 0;+ try {+ const { pruneOldBatchRetryAuditFiles } = await import('../audit/batch-retry-audit.ts');+ purgedBatchRetryAuditFiles = pruneOldBatchRetryAuditFiles(30).removed;+ } catch {+ // Non-fatal.+ }+ // v0.43 (#2095) — 90-day GC of the volunteered-context feedback log.+ // Conversation-adjacent telemetry must never grow unbounded. Best-effort:+ // purgeStaleVolunteerEvents returns 0 on pre-v117 brains (no table).+ let purgedVolunteerEvents = 0;+ try {+ const { purgeStaleVolunteerEvents } = await import('../context/volunteer-events.ts');+ purgedVolunteerEvents = await purgeStaleVolunteerEvents(engine);+ } catch {+ // Non-fatal.+ }+ // System One: decision receipts past decide.receipts.retention_days (reported only when rows were pruned).+ let purgedDecisionReceipts = 0;+ try { purgedDecisionReceipts = await (await import('../ai/decide/store.ts')).pruneReceiptsForCycle(engine); } catch { /* pre-v179 brain */ }+ // GST-1856: applied-capture records past 90 days (ingestion/applied-captures.ts; 0 on a brain before v296).+ const purgedAppliedCaptures = await (await import('../ingestion/applied-captures.ts')).purgeStaleAppliedCaptures(engine);+ let purgedFeedback = { events: 0, weights: 0 };+ try { purgedFeedback = await (await import('../feedback/store.ts')).pruneRetrievalFeedback(engine, (await (await import('../feedback/settings.ts')).loadFeedbackSettings(engine)).eventRetentionDays); } catch { /* pre-v207 brain */ }+ return {+ phase: 'bookkeeping_gc',+ status: 'ok',+ duration_ms: 0,+ summary:+ `${purgedCheckpoints} stale op_checkpoint(s), ${purgedBrainstormCheckpoints} stale brainstorm checkpoint(s), ` ++ `${purgedBatchRetryAuditFiles} stale batch-retry audit file(s) and ${purgedVolunteerEvents} stale volunteer event(s)`,+ details: {+ purged_checkpoints_count: purgedCheckpoints,+ purged_brainstorm_checkpoints_count: purgedBrainstormCheckpoints,+ purged_batch_retry_audit_files_count: purgedBatchRetryAuditFiles,+ purged_volunteer_events_count: purgedVolunteerEvents,+ ...(purgedDecisionReceipts > 0 ? { purged_decision_receipts_count: purgedDecisionReceipts } : {}),+ ...(purgedAppliedCaptures > 0 ? { purged_applied_captures_count: purgedAppliedCaptures } : {}),+ ...(purgedFeedback.events + purgedFeedback.weights > 0 ? { purged_retrieval_feedback_events_count: purgedFeedback.events, purged_retrieval_weights_count: purgedFeedback.weights } : {}),+ },+ };+}diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex b43b217945..06ecb38153 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -723,6 +723,8 @@ export interface ExtractFactsOpts {* (src/core/facts/reconcile-watermark.ts). The dream cycle sets it.*/drain?: FactsReconcileDrainOpts;+ /** GBRA-438: write new rows without calling the embedding provider; the stale-fact embed drain adds their vectors later. */+ deferEmbedding?: boolean;}export interface ExtractFactsResult {@@ -1038,7 +1040,7 @@ export async function runExtractFacts(// consolidate's cosine clustering and find_trajectory's drift_score see// them. Rows updated in place keep their vectors: the claim text is// unchanged. Falls open without an embedding provider, with a warning.- if (toInsert.length > 0) {+ if (toInsert.length > 0 && !opts.deferEmbedding) {if (isAvailable('embedding')) {try {const texts = toInsert.map(e => e.fact);diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex ecc527dcac..fefd17c0cd 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -38,6 +38,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {embed: 'global',orphans: 'global',purge: 'global',+ bookkeeping_gc: 'global','schema-suggest': 'source',extract_atoms: 'source',synthesize_concepts: 'global',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex c2cbd9b914..678d644faf 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -9,6 +9,8 @@* - `managed_skip`: deliberately skipped on managed brains, with the reason* the cycle report shows.*+ * Each entry also carries its `tier` (PhaseTier below).+ ** `test/managed-phase-matrix.test.ts` fails for a phase missing here and runs* each classified phase once on a managed PGLite and Postgres brain.*/@@ -17,40 +19,50 @@ import type { CyclePhase } from '../cycle.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';export type ManagedPhaseClass = 'writes' | 'no_coordinated_write' | 'managed_skip';-export interface ManagedPhaseEntry { class: ManagedPhaseClass; reason: string }+/**+ * What running the phase costs or risks, before this brain's settings and keys+ * narrow it (src/core/maintenance/run.ts computes the per-run step list):+ * - free: no model call by design, and nothing it removes is a page.+ * - paid: calls a chat or embedding model.+ * - deletes: hard-deletes rows or files.+ * - filesystem: needs a git checkout.+ */+export type PhaseTier = 'free' | 'paid' | 'deletes' | 'filesystem';+export interface ManagedPhaseEntry { tier: PhaseTier; class: ManagedPhaseClass; reason: string }export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>> = {- lint: { class: 'writes', reason: 'Lint repairs publish through the maintenance coordinator, one page per repair; a file with no indexed page is reported and left for the next cycle.' },- backlinks: { class: 'no_coordinated_write', reason: 'Audit-only: counts missing back-links and never writes files.' },- sync: { class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },- fence_repair: { class: 'writes', reason: 'Fence repairs publish through managed_file_repair (managed sources), a revision-bound put_page (database-only pages) or the legacy confined write, one coordinated write per repaired file or page.' },- content_repair: { class: 'writes', reason: 'The other content-repair lane kinds publish through the same coordinated file-repair path as fence_repair, one write per repaired file; with no kind beyond fences registered the phase writes nothing.' },- unindexed_files: { class: 'no_coordinated_write', reason: 'Finds committed files with no page and no hold and schedules each for a re-screen on the next sync (an op_checkpoints row); the sync, not this phase, imports or holds them.' },- synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },- extract: { class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },- extract_facts: { class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },- extract_atoms: { class: 'writes', reason: 'Atom pages publish through the maintenance coordinator.' },- resolve_symbol_edges: { class: 'no_coordinated_write', reason: 'Resolves code-edge metadata on chunks, a derived projection outside the canonical tables.' },- patterns: { class: 'writes', reason: 'Pattern pages publish through the maintenance coordinator.' },- synthesize_concepts: { class: 'writes', reason: 'Concept pages publish through publishMaintenancePage: private first, provenance, then promotion.' },- recompute_emotional_weight: { class: 'no_coordinated_write', reason: 'Writes the derived emotional_weight column, which the canonical writer guard does not cover.' },- consolidate: { class: 'writes', reason: 'Consolidated takes, facts and pages commit through the maintenance coordinator.' },- propose_takes: { class: 'no_coordinated_write', reason: 'Writes the take_proposals review queue; managed brains skip the legacy receipt page.' },- grade_takes: { class: 'no_coordinated_write', reason: 'The cycle runs it with auto-resolve off, so it only caches verdicts in take_grade_cache; opt-in auto-applied resolutions go through the coordinated takes_resolve mutation.' },- calibration_profile: { class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },- edge_contradictions: { class: 'writes', reason: 'Applied closures append a timeline line through the coordinated add_timeline_entry mutation; proposals live in the link_edge_proposals side table.' },- claim_conflicts: { class: 'no_coordinated_write', reason: 'writes the decide_proposals review queue only' },- drift: { class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },- standing_questions: { class: 'writes', reason: 'Question pages publish through coordinated put_page mutations; answers and evidence pointers live in the pinned_questions side tables.' },- chronicle: { class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },- facts_drain: { class: 'writes', reason: 'Queued facts-absorb jobs publish facts through the same coordinated write path as the job worker.' },- conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },- enrich_thin: { class: 'writes', reason: 'Enriched pages publish through the maintenance coordinator.' },- skillopt: { class: 'no_coordinated_write', reason: 'Writes skill files and proposals outside the brain database.' },- embed: { class: 'no_coordinated_write', reason: 'Embeddings are a physical projection the canonical writer guard does not cover.' },- orphans: { class: 'no_coordinated_write', reason: 'Read-only orphan report.' },- 'schema-suggest': { class: 'no_coordinated_write', reason: 'Writes schema suggestions outside the canonical tables.' },- purge: { class: 'writes', reason: 'Expired tombstones are purged one by one through coordinated delete_page purges.' },+ lint: { tier: 'filesystem', class: 'writes', reason: 'Lint repairs publish through the maintenance coordinator, one page per repair; a file with no indexed page is reported and left for the next cycle.' },+ backlinks: { tier: 'filesystem', class: 'no_coordinated_write', reason: 'Audit-only: counts missing back-links and never writes files.' },+ sync: { tier: 'filesystem', class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },+ fence_repair: { tier: 'free', class: 'writes', reason: 'Fence repairs publish through managed_file_repair (managed sources), a revision-bound put_page (database-only pages) or the legacy confined write, one coordinated write per repaired file or page.' },+ content_repair: { tier: 'free', class: 'writes', reason: 'The other content-repair lane kinds publish through the same coordinated file-repair path as fence_repair, one write per repaired file; with no kind beyond fences registered the phase writes nothing.' },+ unindexed_files: { tier: 'filesystem', class: 'no_coordinated_write', reason: 'Finds committed files with no page and no hold and schedules each for a re-screen on the next sync (an op_checkpoints row); the sync, not this phase, imports or holds them.' },+ synthesize: { tier: 'filesystem', class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },+ extract: { tier: 'free', class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },+ extract_facts: { tier: 'free', class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },+ extract_atoms: { tier: 'paid', class: 'writes', reason: 'Atom pages publish through the maintenance coordinator.' },+ resolve_symbol_edges: { tier: 'free', class: 'no_coordinated_write', reason: 'Resolves code-edge metadata on chunks, a derived projection outside the canonical tables.' },+ patterns: { tier: 'filesystem', class: 'writes', reason: 'Pattern pages publish through the maintenance coordinator.' },+ synthesize_concepts: { tier: 'paid', class: 'writes', reason: 'Concept pages publish through publishMaintenancePage: private first, provenance, then promotion.' },+ recompute_emotional_weight: { tier: 'free', class: 'no_coordinated_write', reason: 'Writes the derived emotional_weight column, which the canonical writer guard does not cover.' },+ consolidate: { tier: 'free', class: 'writes', reason: 'Consolidated takes, facts and pages commit through the maintenance coordinator.' },+ propose_takes: { tier: 'paid', class: 'no_coordinated_write', reason: 'Writes the take_proposals review queue; managed brains skip the legacy receipt page.' },+ grade_takes: { tier: 'paid', class: 'no_coordinated_write', reason: 'The cycle runs it with auto-resolve off, so it only caches verdicts in take_grade_cache; opt-in auto-applied resolutions go through the coordinated takes_resolve mutation.' },+ calibration_profile: { tier: 'paid', class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },+ edge_contradictions: { tier: 'paid', class: 'writes', reason: 'Applied closures append a timeline line through the coordinated add_timeline_entry mutation; proposals live in the link_edge_proposals side table.' },+ claim_conflicts: { tier: 'free', class: 'no_coordinated_write', reason: 'writes the decide_proposals review queue only' },+ drift: { tier: 'paid', class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },+ standing_questions: { tier: 'paid', class: 'writes', reason: 'Question pages publish through coordinated put_page mutations; answers and evidence pointers live in the pinned_questions side tables.' },+ chronicle: { tier: 'paid', class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },+ facts_drain: { tier: 'paid', class: 'writes', reason: 'Queued facts-absorb jobs publish facts through the same coordinated write path as the job worker.' },+ conversation_facts_backfill: { tier: 'paid', class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },+ enrich_thin: { tier: 'paid', class: 'writes', reason: 'Enriched pages publish through the maintenance coordinator.' },+ skillopt: { tier: 'paid', class: 'no_coordinated_write', reason: 'Writes skill files and proposals outside the brain database.' },+ embed: { tier: 'paid', class: 'no_coordinated_write', reason: 'Embeddings are a physical projection the canonical writer guard does not cover.' },+ orphans: { tier: 'free', class: 'no_coordinated_write', reason: 'Read-only orphan report.' },+ 'schema-suggest': { tier: 'free', class: 'no_coordinated_write', reason: 'Writes schema suggestions outside the canonical tables.' },+ purge: { tier: 'deletes', class: 'writes', reason: 'Expired tombstones are purged one by one through coordinated delete_page purges.' },+ bookkeeping_gc: { tier: 'deletes', class: 'no_coordinated_write', reason: 'Deletes bookkeeping rows and files past their retention (op checkpoints, brainstorm checkpoints, batch-retry audit files, volunteer events, decision receipts, applied captures, retrieval feedback); it never touches a page.' },};export async function isManagedBrain(engine: BrainEngine): Promise<boolean> {diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 4013a71284..bf168094a7 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -439,6 +439,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['global_maintenance_timeouts',// GBRA-130 C-6: no completed brain-wide pass while jobs fail or a phase keeps blocking it.'global_maintenance_stalled',+ // GBRA-438: free unattended upkeep (maintenance.last_run) overdue or failing.+ 'unattended_maintenance','embed_backfill_stalled',// #7117: the content-drift sweep's latest batch failed.'content_drift_sweep',diff --git a/src/core/embed-cost-cap.ts b/src/core/embed-cost-cap.tsindex 36132e9385..b57bbe21c4 100644--- a/src/core/embed-cost-cap.ts+++ b/src/core/embed-cost-cap.ts@@ -17,6 +17,8 @@ export interface EmbedCostCap {readonly signal: AbortSignal;/** The cap's refusal once the run reached it; null while under it. */hit(): BudgetExhausted | null;+ /** Dollars the run has spent under the cap so far. */+ spent(): number;metered<T>(fn: () => Promise<T>): Promise<T>;}@@ -50,6 +52,7 @@ export function embedCostCap(capUsd: number | null | undefined, capSource: CapSohit: () => refusal ?? (controller.signal.aborted? new BudgetExhausted(`embed reached its $${capUsd.toFixed(2)} cost cap`, { reason: 'cost', spent: tracker.totalSpent, cap: capUsd }): null),+ spent: () => tracker.totalSpent,metered: fn => withBudgetTracker(tracker, fn),};}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5de3c80547..957e748c9d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -65,6 +65,12 @@ export const CODES = {absent_from_worktree: { class: 'caller', retryable: false, reasons: ['skip_worktree', 'deleted_locally'], summary: "Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced.", why: "Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run.", docs: 'docs/guides/write-refusals.md#absent_from_worktree', suggestion: 'Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold.' },access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },access_member_disabled: { class: 'host_only', actor: 'user', reasons: ['disabled', 'removed', 'missing', 'malformed'], summary: "The credential (access token, OAuth client or stdio binding) is bound to a member who is disabled, removed or missing, so it was refused at verification and nothing was read.", why: 'A credential bound to a member reads as that member. While the member cannot read, the credential is refused rather than silently treated as unbound.', docs: 'docs/guides/write-refusals.md#access_member_disabled', suggestion: 'Ask the brain operator to enable the member (gbrain access member enable <id>) or rebind the credential (gbrain auth rescope --token <name>|--client <id> --member <id>|none).' },+ autopilot_no_repo: { class: 'caller', summary: "gbrain autopilot --install found no absolute repo directory (sync.repo_path and the default source's local_path are unset or relative), so it installed nothing.", why: 'The autopilot daemon syncs a git checkout. A repo-less brain needs no daemon: free upkeep (gbrain maintain --unattended) keeps it maintained.', suggestion: 'Pass --repo <absolute-directory> for a brain kept in git, or check free upkeep with gbrain maintain --status.' },+ autopilot_pglite_daemon: { class: 'caller', summary: 'gbrain autopilot --install refused on a PGLite brain: a daemon would hold the single-writer lock all day and block every other gbrain process.', why: 'PGLite has one writer. gbrain serve owns the lock and runs the resident sweep; free upkeep runs through gbrain maintain --unattended.', suggestion: 'Run gbrain serve, check upkeep with gbrain maintain --status, or re-run with --force for a dedicated-brain daemon.' },+ cycle_already_running: { class: 'retryable', summary: 'Another maintenance cycle holds the brain cycle lock, so this run skipped instead of waiting.', why: 'Cycles serialize on the gbrain-cycle lease; the holder releases it when it finishes (or its TTL lapses after a crash).', suggestion: 'Wait for the other cycle; unattended upkeep retries on its next turn (gbrain maintain --status shows the last skip).' },+ engine_degraded: { class: 'unavailable', summary: 'The brain database was unreachable (the engine is in degraded mode), so background work such as unattended upkeep skipped this run.', why: 'A degraded engine answers from its last state and reconnects on its own; writing maintenance results then would be lost or refused.', suggestion: 'Run gbrain doctor --json and report the connection problem it names.' },+ maintenance_disabled: { class: 'caller', exit: 0, summary: 'Free unattended upkeep is off on this brain (maintenance.auto is false), so nothing ran.', why: 'The person turned upkeep off; doctor reads it as off, not stale.', suggestion: 'Turn it back on with gbrain config set maintenance.auto true.' },+ maintenance_owned_by_autopilot: { class: 'caller', exit: 0, summary: 'An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing.', why: 'One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database.', suggestion: 'Nothing to do; gbrain autopilot --status shows the daemon.' },on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },@@ -1060,4 +1066,8 @@ export const NOTICE_CODES = {reason_scan_failed: { kind: 'degraded', summary: 'A sync could not read change reasons from Git for its range (a Git error or a timeout): content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },reason_scan_capped: { kind: 'degraded', summary: 'A sync range held more than 10,000 commits, so its change reasons were not read: content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },reason_trailer_secret: { kind: 'safety', summary: 'A gbrain-reason trailer already in Git looks like a secret; the notice names the commit and path (never the value), no reason was stored, and the user should rotate the credential because Git history keeps it.' },+ cycle_already_running: { kind: 'info', summary: 'Unattended upkeep skipped this run because another maintenance cycle holds the brain cycle lock; it retries on its next turn.' },+ engine_degraded: { kind: 'degraded', summary: 'Unattended upkeep skipped this run because the brain database was unreachable (degraded engine).' },+ maintenance_disabled: { kind: 'info', summary: 'Unattended upkeep is off on this brain (maintenance.auto is false).' },+ maintenance_owned_by_autopilot: { kind: 'info', summary: 'An autopilot keeps this brain maintained, so free upkeep did nothing.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/maintenance/run.ts b/src/core/maintenance/run.tsnew file mode 100644index 0000000000..24018975ae--- /dev/null+++ b/src/core/maintenance/run.ts@@ -0,0 +1,434 @@+/**+ * Unattended upkeep (GBRA-438): the free, never-purging maintenance a brain+ * runs with nobody watching, and the runner core `gbrain maintain --safe`+ * shares its step list with.+ *+ * One run is a list of work items: one global item (the brain-wide free+ * phases, once per window, under the shared `gbrain-cycle` lease) and one+ * item per source (its source-scoped free phases, under that source's lease),+ * then the embedding catch-up step on a brain with an embedding key, under a+ * daily dollar cap (`maintenance.embed_daily_usd`, default $1, 0 turns it+ * off). Nothing here purges a page or calls a chat model; the page purge+ * stays preview-first (`gbrain maintain --purge`), and every other paid phase+ * stays with `gbrain dream` or an installed autopilot.+ *+ * Cycles run with `stamp: 'none'`, so upkeep never writes+ * `last_full_cycle_at` or `last_source_cycle_at`. Its own record is+ * `maintenance.last_run` in the database config, which is also the record on+ * a repo-less brain. The runner never throws to its caller: every skip and+ * failure comes back as an outcome with a code and a fix.+ */+import { existsSync } from 'fs';+import { isAbsolute } from 'path';+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { ALL_PHASES, LAST_GLOBAL_AT_KEY, PHASE_SCOPE, anyAbortSignal, resolveCyclePhases, runCycle, type CycleOpts, type CyclePhase, type CycleReport } from '../cycle.ts';+import { MANAGED_PHASE_TABLE } from '../cycle/phase-table.ts';+import { isAvailable } from '../ai/gateway.ts';+import { fenceRepairLlmEnabled } from '../fence-repair/config.ts';+import { resolveFenceRepairModel } from '../fence-repair/model.ts';+import { resolveContentRepairModel } from '../content-repair/llm.ts';+import { loadConfigSnapshot } from '../config-snapshot.ts';+import { readDecideConfig } from '../ai/decide/config.ts';+import { hasTypesafeKey } from '../ai/decide/index.ts';+import { isEngineDegraded } from '../degraded-marker.ts';+import { hasPendingMigrations } from '../migrate-pending.ts';++export const MAINTENANCE_LAST_RUN_KEY = 'maintenance.last_run';+export const MAINTENANCE_AUTO_KEY = 'maintenance.auto';+export const MAINTENANCE_EMBED_DAILY_USD_KEY = 'maintenance.embed_daily_usd';+/** Unattended embedding spend per UTC day: `{ day, usd }`. */+export const MAINTENANCE_EMBED_SPEND_KEY = 'maintenance.embed_spend';+export const DEFAULT_EMBED_DAILY_USD = 1;+/** A finished round is due again after this long. */+export const UPKEEP_INTERVAL_MS = 24 * 60 * 60 * 1000;+/** A step failing with the same code this many runs in a row backs off to once a week. */+export const UPKEEP_BACKOFF_FAILURES = 3;+export const UPKEEP_BACKOFF_MS = 7 * 24 * 60 * 60 * 1000;+/** An autopilot whose global pass is younger than this owns upkeep. */+export const AUTOPILOT_OWNS_WITHIN_MS = 48 * 60 * 60 * 1000;++/**+ * The cycle phases `--safe` may run: free, and never hard-deleting. The page+ * purge and every phase that calls a model stay with `gbrain dream` and+ * `gbrain pages purge-deleted`.+ */+export const MAINTAIN_SAFE_PHASES: readonly CyclePhase[] = [+ 'lint', 'backlinks', 'sync', 'fence_repair', 'content_repair', 'unindexed_files',+ 'extract', 'extract_facts', 'resolve_symbol_edges', 'recompute_emotional_weight',+ 'consolidate', 'orphans', 'schema-suggest',+];++/** Which providers a safe phase would call on this brain; those phases are held back. */+export interface SafePhaseProviders {+ embedding: boolean;+ decideConflict: boolean;+ fenceRepairModel: boolean;+ contentRepairModel: boolean;+}++export function maintainSafePhases(sourceId: string, providers: SafePhaseProviders): { phases: CyclePhase[]; held: CyclePhase[] } {+ const held: CyclePhase[] = [];+ if (providers.embedding || providers.decideConflict) held.push('extract_facts');+ if (providers.fenceRepairModel || providers.embedding) held.push('fence_repair');+ if (providers.contentRepairModel || providers.embedding) held.push('content_repair');+ const phases = resolveCyclePhases(undefined, sourceId)+ .filter((phase) => MAINTAIN_SAFE_PHASES.includes(phase) && !held.includes(phase));+ return { phases, held };+}++export async function readSafePhaseProviders(engine: BrainEngine): Promise<SafePhaseProviders> {+ const repairLlm = await fenceRepairLlmEnabled(engine);+ return {+ embedding: isAvailable('embedding'),+ decideConflict: readDecideConfig(await loadConfigSnapshot(engine), { typesafeKey: hasTypesafeKey() }).slots.conflict.mode !== 'off',+ fenceRepairModel: repairLlm && (await resolveFenceRepairModel(engine)) !== null,+ contentRepairModel: repairLlm && (await resolveContentRepairModel(engine)) !== null,+ };+}++export interface UpkeepPlan {+ /** Brain-wide phases, one item per run. */+ global: CyclePhase[];+ /** Source-scoped phases, one item per source. */+ source: CyclePhase[];+ /** Phases left out because they would call a provider on this brain. */+ held: CyclePhase[];+ /** An embedding key exists: extract_facts writes new rows without vectors and the capped embedding step adds them. */+ embedding: boolean;+}++/**+ * The unattended step list for this brain: the `--safe` phases plus the+ * bookkeeping GC (decision C1). extract_facts stays in on a keyed brain with+ * its embedding deferred; it is held only when the System One conflict slot+ * would call its provider. The repair lanes stay held whenever their LLM step+ * is on or an embedding key exists, because their publications embed.+ */+export function unattendedPlan(providers: SafePhaseProviders): UpkeepPlan {+ const held: CyclePhase[] = [];+ if (providers.decideConflict) held.push('extract_facts');+ if (providers.fenceRepairModel || providers.embedding) held.push('fence_repair');+ if (providers.contentRepairModel || providers.embedding) held.push('content_repair');+ const steps = ALL_PHASES.filter((phase) => (MAINTAIN_SAFE_PHASES.includes(phase) || phase === 'bookkeeping_gc') && !held.includes(phase));+ return {+ global: steps.filter((phase) => PHASE_SCOPE[phase] !== 'source'),+ source: steps.filter((phase) => PHASE_SCOPE[phase] === 'source'),+ held,+ embedding: providers.embedding,+ };+}++/** Paid-tier phases: what upkeep leaves for the person (`gbrain dream`, autopilot). */+export const PAID_PHASES: readonly CyclePhase[] = ALL_PHASES.filter((phase) => MANAGED_PHASE_TABLE[phase].tier === 'paid');++export type UpkeepStepStatus = 'ok' | 'warn' | 'fail' | 'skipped';+export interface UpkeepStep { name: string; scope: string; status: UpkeepStepStatus; code?: string; reason?: string }+export interface UpkeepFailure { step: string; scope: string; code: string; count: number; last_at: string }+export interface UpkeepRecord {+ at: string;+ runner: string;+ status: 'ok' | 'partial' | 'failed';+ steps: UpkeepStep[];+ held: CyclePhase[];+ /** Items already done in an unfinished round; null once the round finished. */+ cursor: { round_started_at: string; done: string[] } | null;+ next_due_at: string;+ consecutive_failures: UpkeepFailure[];+ embed?: { spent_today_usd: number; cap_usd: number };+ last_skip?: { at: string; code: string };+}++export interface UpkeepOutcome {+ status: 'ran' | 'skipped' | 'not_due';+ /** 0 for every skip; 1 when a step failed (`maintain` only; the serve never exits). */+ exit: 0 | 1;+ code?: string;+ message: string;+ fix?: Action;+ record?: UpkeepRecord;+}++export interface UpkeepOpts {+ runner: string;+ now?: () => Date;+ /** Wall-clock budget for the whole run; an unfinished round resumes on the next run. */+ budgetMs?: number;+ signal?: AbortSignal;+ /** Test seams. */+ providers?: SafePhaseProviders;+ capacityPaused?: (engine: BrainEngine) => Promise<{ command: string; config_key: string } | null>;+ cycle?: typeof runCycle;+}++const RUNNER_NAME = /^[a-z][a-z0-9_-]{0,31}$/;+export const isValidRunnerName = (name: string): boolean => RUNNER_NAME.test(name);++export async function readUpkeepRecord(engine: BrainEngine): Promise<UpkeepRecord | null> {+ const raw = await engine.getConfig(MAINTENANCE_LAST_RUN_KEY).catch(() => null);+ if (!raw) return null;+ try {+ const parsed = JSON.parse(raw) as UpkeepRecord;+ return parsed && typeof parsed.at === 'string' && Array.isArray(parsed.steps) ? parsed : null;+ } catch {+ return null;+ }+}++export async function upkeepEnabled(engine: BrainEngine): Promise<boolean> {+ const raw = (await engine.getConfig(MAINTENANCE_AUTO_KEY).catch(() => null))?.trim().toLowerCase();+ return !(raw === 'false' || raw === '0' || raw === 'off' || raw === 'no');+}++export async function readEmbedDailyCapUsd(engine: BrainEngine): Promise<number> {+ const raw = (await engine.getConfig(MAINTENANCE_EMBED_DAILY_USD_KEY).catch(() => null))?.trim();+ if (!raw) return DEFAULT_EMBED_DAILY_USD;+ const value = Number(raw);+ return Number.isFinite(value) && value >= 0 ? value : DEFAULT_EMBED_DAILY_USD;+}++const utcDay = (at: Date) => at.toISOString().slice(0, 10);++export async function readEmbedSpentToday(engine: BrainEngine, now: Date): Promise<number> {+ const raw = await engine.getConfig(MAINTENANCE_EMBED_SPEND_KEY).catch(() => null);+ if (!raw) return 0;+ try {+ const parsed = JSON.parse(raw) as { day?: string; usd?: number };+ return parsed.day === utcDay(now) && typeof parsed.usd === 'number' && Number.isFinite(parsed.usd) ? parsed.usd : 0;+ } catch {+ return 0;+ }+}++/** Whether an autopilot keeps this brain maintained: its brain-wide pass stamped recently (any host). */+export async function autopilotOwnsUpkeep(engine: BrainEngine, now: Date): Promise<string | null> {+ const raw = await engine.getConfig(LAST_GLOBAL_AT_KEY).catch(() => null);+ if (!raw) return null;+ const at = Date.parse(raw);+ return Number.isFinite(at) && now.getTime() - at < AUTOPILOT_OWNS_WITHIN_MS ? raw : null;+}++async function defaultCapacityPaused(engine: BrainEngine): Promise<{ command: string; config_key: string } | null> {+ const { cachedCapacitySnapshot } = await import('../persistence/capacity-snapshot.ts');+ const snapshot = await cachedCapacitySnapshot(engine as never).catch(() => null);+ const row = snapshot?.paused[0];+ return row ? { command: row.command, config_key: row.config_key } : null;+}++const STATUS_VERIFY = { argv: ['gbrain', 'maintain', '--status', '--json'] };++function skip(code: string, message: string, fix?: Action): UpkeepOutcome {+ return { status: 'skipped', exit: 0, code, message, ...(fix ? { fix } : {}) };+}++/** Why upkeep cannot run right now, or null. Checked in this order before any work. */+async function preflight(engine: BrainEngine, opts: UpkeepOpts, now: Date): Promise<UpkeepOutcome | null> {+ if (!await upkeepEnabled(engine)) {+ return skip('maintenance_disabled', 'Unattended upkeep is off (maintenance.auto is false); nothing ran.');+ }+ if (isEngineDegraded(engine)) {+ return skip('engine_degraded', 'The brain database is unreachable right now (degraded engine), so upkeep skipped this run.',+ { consent: [], actor: 'agent', requires_exclusive: false, why: 'Upkeep waits for the database to come back; doctor names the connection problem.', verify: { argv: ['gbrain', 'doctor', '--json'] } });+ }+ if (await hasPendingMigrations(engine)) {+ return skip('migrations_pending', 'Schema migrations are pending on this brain, so upkeep skipped this run.',+ { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Applies the pending schema migrations (the same ones every command applies on connect); upkeep runs on its next turn.', verify: STATUS_VERIFY });+ }+ const owner = await autopilotOwnsUpkeep(engine, now);+ if (owner) {+ return skip('maintenance_owned_by_autopilot', `An autopilot keeps this brain maintained (its last brain-wide pass ran at ${owner}), so free upkeep left it alone.`);+ }+ const paused = await (opts.capacityPaused ?? defaultCapacityPaused)(engine).catch(() => null);+ if (paused) {+ return skip('write_capacity_backpressure', `A cumulative write cap (${paused.config_key}) passed the background pause line, so upkeep skipped this run.`,+ { argv: paused.command.split(' '), consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Raises the write cap on the brain host; background producers, upkeep included, resume below the pause line.', verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] } });+ }+ return null;+}++interface WorkItem { key: string; sourceId?: string; phases: CyclePhase[] }++function phaseCode(phase: CycleReport['phases'][number]): string | undefined {+ return phase.code ?? phase.error?.code;+}++function stepsFrom(report: CycleReport, scope: string): UpkeepStep[] {+ return report.phases.map((phase) => {+ const code = phase.status === 'fail' ? phaseCode(phase) ?? 'phase_failed' : phase.status === 'skipped' ? undefined : phaseCode(phase);+ const reason = phase.status === 'skipped' ? String(phase.details?.reason ?? '') || undefined : undefined;+ return { name: phase.phase, scope, status: phase.status, ...(code ? { code } : {}), ...(reason ? { reason } : {}) };+ });+}++async function brainDirFor(engine: BrainEngine, sourceId: string, localPath: string | null | undefined): Promise<string | null> {+ if (!localPath || !isAbsolute(localPath) || !existsSync(localPath)) return null;+ const { syncContentDirectory } = await import('../sync-applicability.ts');+ return (await syncContentDirectory(engine, { sourceId }).catch(() => null)) ? null : localPath;+}++function backedOff(failures: UpkeepFailure[], step: string, scope: string, now: Date): boolean {+ const entry = failures.find((f) => f.step === step && f.scope === scope);+ return !!entry && entry.count >= UPKEEP_BACKOFF_FAILURES && now.getTime() - Date.parse(entry.last_at) < UPKEEP_BACKOFF_MS;+}++async function runEmbedStep(engine: BrainEngine, now: Date, signal: AbortSignal | undefined): Promise<{ step: UpkeepStep; embed: { spent_today_usd: number; cap_usd: number } }> {+ const cap = await readEmbedDailyCapUsd(engine);+ const spentBefore = await readEmbedSpentToday(engine, now);+ const embed = (spent: number) => ({ spent_today_usd: Math.round(spent * 1e6) / 1e6, cap_usd: cap });+ if (cap <= 0) return { step: { name: 'embed', scope: 'global', status: 'skipped', reason: 'embed_cap_off' }, embed: embed(spentBefore) };+ if (await engine.getConfig('embedding_disabled').catch(() => null) === 'true') {+ return { step: { name: 'embed', scope: 'global', status: 'skipped', reason: 'embedding_disabled' }, embed: embed(spentBefore) };+ }+ const remaining = cap - spentBefore;+ if (remaining <= 0) return { step: { name: 'embed', scope: 'global', status: 'skipped', reason: 'daily_cap_reached' }, embed: embed(spentBefore) };+ const [{ embedCostCap }, { loadPricingOverrides }, { runEmbedCore }, { embedStaleFacts }] = await Promise.all([+ import('../embed-cost-cap.ts'), import('../budget/budget-tracker.ts'), import('../../commands/embed.ts'), import('../embed-facts.ts')]);+ const costCap = embedCostCap(remaining, 'user', await loadPricingOverrides(engine).catch(() => undefined))!;+ const combined = anyAbortSignal(signal ? [costCap.signal, signal] : [costCap.signal]);+ let spent = 0;+ let status: UpkeepStepStatus = 'ok';+ let code: string | undefined;+ try {+ const result = await costCap.metered(() => runEmbedCore(engine, { stale: true, quiet: true, signal: combined.signal }));+ if (result.failures > 0 && !result.lock_skipped) status = 'warn';+ spent = costCap.spent();+ if (!costCap.hit() && !combined.signal.aborted) {+ for (const source of await engine.listAllSources()) {+ const left = remaining - spent;+ if (left <= 0 || combined.signal.aborted) break;+ try {+ const facts = await embedStaleFacts(engine, { sourceId: source.id, yes: true, maxCostUsd: left, signal: combined.signal });+ spent += facts.cost_usd;+ if (facts.failures > 0) status = 'warn';+ } catch (error) {+ status = 'warn';+ code ??= (error as { code?: string } | null)?.code ?? 'facts_embed_refused';+ }+ }+ }+ } catch (error) {+ spent = Math.max(spent, costCap.spent());+ if (!costCap.hit()) {+ status = 'fail';+ code = (error as { code?: string } | null)?.code ?? 'embed_failed';+ }+ } finally {+ combined.dispose();+ }+ const total = spentBefore + spent;+ await engine.setConfig(MAINTENANCE_EMBED_SPEND_KEY, JSON.stringify({ day: utcDay(now), usd: total }));+ const reason = costCap.hit() ? 'daily_cap_reached' : undefined;+ return { step: { name: 'embed', scope: 'global', status, ...(code ? { code } : {}), ...(reason ? { reason } : {}) }, embed: embed(total) };+}++/**+ * One unattended upkeep run. Never throws: a run that cannot start returns a+ * skip with its code and fix, a failed step is recorded with its own code and+ * the run moves on to the next item.+ */+export async function runUnattendedMaintenance(engine: BrainEngine, opts: UpkeepOpts): Promise<UpkeepOutcome> {+ const now = (opts.now ?? (() => new Date()))();+ try {+ const refused = await preflight(engine, opts, now);+ const prior = await readUpkeepRecord(engine);+ if (refused) {+ if (prior && refused.code) await engine.setConfig(MAINTENANCE_LAST_RUN_KEY, JSON.stringify({ ...prior, last_skip: { at: now.toISOString(), code: refused.code } }));+ return refused;+ }+ if (prior && !prior.cursor && Date.parse(prior.next_due_at) > now.getTime()) {+ return { status: 'not_due', exit: 0, message: `Upkeep already ran at ${prior.at}; next due at ${prior.next_due_at}.`, record: prior };+ }+ const plan = unattendedPlan(opts.providers ?? await readSafePhaseProviders(engine));+ const sources = (await engine.listAllSources()).sort((a, b) => a.id.localeCompare(b.id));+ const round = prior?.cursor ?? { round_started_at: now.toISOString(), done: [] as string[] };+ const failures = prior?.consecutive_failures ?? [];+ const items: WorkItem[] = [+ { key: 'global', phases: plan.global },+ ...sources.map((source) => ({ key: `source:${source.id}`, sourceId: source.id, phases: plan.source })),+ ].filter((item) => !round.done.includes(item.key));+ const deadline = opts.budgetMs !== undefined ? Date.now() + opts.budgetMs : Infinity;+ const steps: UpkeepStep[] = [];+ const done = [...round.done];+ let lockBusy = false;+ for (const item of items) {+ if (Date.now() >= deadline || opts.signal?.aborted) break;+ const scope = item.sourceId ?? 'global';+ const phases = item.phases.filter((phase) => !backedOff(failures, phase, scope, now));+ for (const phase of item.phases) if (!phases.includes(phase)) steps.push({ name: phase, scope, status: 'skipped', reason: 'backed_off' });+ const source = item.sourceId ? sources.find((s) => s.id === item.sourceId) : undefined;+ const brainDir = source ? await brainDirFor(engine, source.id, source.local_path) : null;+ const budget = Number.isFinite(deadline) ? AbortSignal.timeout(Math.max(1, deadline - Date.now())) : undefined;+ const signals = [opts.signal, budget].filter((s): s is AbortSignal => s !== undefined);+ const combined = signals.length ? anyAbortSignal(signals) : null;+ const cycleOpts: CycleOpts = {+ brainDir, pull: false, phases, stamp: 'none', deferFactEmbedding: plan.embedding,+ ...(item.sourceId ? { sourceId: item.sourceId } : { forceGlobalOrphans: true }),+ ...(combined ? { signal: combined.signal } : {}),+ };+ try {+ if (phases.length > 0) {+ const report = await (opts.cycle ?? runCycle)(engine, cycleOpts);+ if (report.status === 'skipped' && report.reason === 'cycle_already_running') { lockBusy = true; break; }+ steps.push(...stepsFrom(report, scope));+ if (report.reason === 'aborted' || report.reason === 'lock_stolen') break;+ }+ done.push(item.key);+ } catch (error) {+ if (combined?.signal.aborted) break;+ steps.push({ name: 'cycle', scope, status: 'fail', code: (error as { code?: string } | null)?.code ?? 'cycle_failed' });+ done.push(item.key);+ } finally {+ combined?.dispose();+ }+ }+ if (lockBusy && steps.length === 0) {+ const out = skip('cycle_already_running', 'Another maintenance cycle holds the brain\'s cycle lock, so upkeep skipped this run.',+ { argv: STATUS_VERIFY.argv, consent: [], actor: 'provider', requires_exclusive: false, why: 'The other cycle releases the lock when it finishes; upkeep runs again on its next turn.', verify: STATUS_VERIFY });+ if (prior) await engine.setConfig(MAINTENANCE_LAST_RUN_KEY, JSON.stringify({ ...prior, last_skip: { at: now.toISOString(), code: 'cycle_already_running' } }));+ return out;+ }+ const finished = items.every((item) => done.includes(item.key));+ let embed: UpkeepRecord['embed'];+ if (finished && plan.embedding && !opts.signal?.aborted) {+ const result = await runEmbedStep(engine, now, opts.signal);+ steps.push(result.step);+ embed = result.embed;+ }+ const failed = steps.filter((step) => step.status === 'fail');+ const nextFailures: UpkeepFailure[] = failures+ .filter((f) => !steps.some((s) => s.name === f.step && s.scope === f.scope && s.status !== 'fail' && s.reason !== 'backed_off'));+ for (const step of failed) {+ const entry = nextFailures.find((f) => f.step === step.name && f.scope === step.scope);+ if (entry && entry.code === step.code) { entry.count += 1; entry.last_at = now.toISOString(); }+ else if (entry) { entry.code = step.code!; entry.count = 1; entry.last_at = now.toISOString(); }+ else nextFailures.push({ step: step.name, scope: step.scope, code: step.code!, count: 1, last_at: now.toISOString() });+ }+ const record: UpkeepRecord = {+ at: now.toISOString(),+ runner: opts.runner,+ status: failed.length === 0 ? 'ok' : failed.length === steps.filter((s) => s.status !== 'skipped').length ? 'failed' : 'partial',+ steps,+ held: plan.held,+ cursor: finished ? null : { round_started_at: round.round_started_at, done },+ next_due_at: new Date(finished ? now.getTime() + UPKEEP_INTERVAL_MS : now.getTime()).toISOString(),+ consecutive_failures: nextFailures,+ ...(embed ? { embed } : {}),+ };+ await engine.setConfig(MAINTENANCE_LAST_RUN_KEY, JSON.stringify(record));+ const first = failed[0];+ return {+ status: 'ran',+ exit: first ? 1 : 0,+ ...(first?.code ? { code: first.code } : {}),+ message: first+ ? `Upkeep ran ${steps.length} step(s); ${failed.length} failed, first ${first.name} (${first.scope}) with ${first.code}.`+ : `Upkeep ran ${steps.length} step(s)${finished ? '' : '; the round continues on the next run'}.`,+ record,+ };+ } catch (error) {+ const code = (error as { code?: string } | null)?.code ?? 'maintenance_failed';+ return { status: 'ran', exit: 1, code, message: `Upkeep stopped: ${error instanceof Error ? error.message : String(error)}` };+ }+}diff --git a/src/core/maintenance/status.ts b/src/core/maintenance/status.tsnew file mode 100644index 0000000000..e79682065e--- /dev/null+++ b/src/core/maintenance/status.ts@@ -0,0 +1,107 @@+/**+ * What unattended upkeep looks like right now (GBRA-438): one view behind+ * `gbrain maintain --status` and the `unattended_maintenance` doctor check,+ * so the two can never disagree.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { isAvailable } from '../ai/gateway.ts';+import {+ PAID_PHASES, UPKEEP_BACKOFF_FAILURES, autopilotOwnsUpkeep, readEmbedDailyCapUsd, readEmbedSpentToday, readUpkeepRecord, upkeepEnabled,+ type UpkeepFailure, type UpkeepRecord,+} from './run.ts';++/** Past this age, an upkeep run (or a brain with none) reads as overdue. */+export const UPKEEP_OVERDUE_MS = 48 * 60 * 60 * 1000;++export type UpkeepState = 'ok' | 'never' | 'off' | 'autopilot' | 'overdue' | 'failing';++export interface UpkeepStatus {+ state: UpkeepState;+ message: string;+ runner: string | null;+ last_run: string | null;+ steps: UpkeepRecord['steps'];+ held: string[];+ next_due_at: string | null;+ failing: UpkeepFailure | null;+ pending_purge_count: number | null;+ paid_phases_opt_in: string[];+ embed_spend_today_usd: number | null;+ embed_daily_cap_usd: number | null;+ fix?: Action;+}++function ago(ms: number): string {+ const hours = Math.floor(ms / 3_600_000);+ if (hours >= 48) return `${Math.floor(hours / 24)}d`;+ if (hours >= 1) return `${hours}h`;+ return `${Math.max(0, Math.floor(ms / 60_000))}m`;+}++async function pendingPurgeCount(engine: BrainEngine): Promise<number | null> {+ try {+ const [{ selectPurgeCandidates }, { readPurgeRetentionHours }] = await Promise.all([import('../persistence/purge-deleted.ts'), import('../sync-reconcile.ts')]);+ return (await selectPurgeCandidates(engine, await readPurgeRetentionHours(engine), { automatic: true })).count;+ } catch {+ return null;+ }+}++async function brainAgeMs(engine: BrainEngine, now: number): Promise<number | null> {+ const [row] = await engine.executeRaw<{ oldest: string | Date | null }>('SELECT MIN(created_at) AS oldest FROM pages').catch(() => [{ oldest: null }]);+ const oldest = row?.oldest ? new Date(row.oldest).getTime() : NaN;+ return Number.isFinite(oldest) ? now - oldest : null;+}++/** The fix doctor and `--status` print when upkeep is overdue or failing. */+export function upkeepFix(paid: boolean): Action {+ return {+ argv: ['gbrain', 'maintain', '--unattended'], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,+ why: paid+ ? 'Runs free upkeep now (links, timeline, facts index, bookkeeping GC; never the page purge); with an embedding key it also embeds the backlog within maintenance.embed_daily_usd.'+ : 'Runs free upkeep now (links, timeline, facts index, bookkeeping GC); it calls no model and never purges a page.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'unattended_maintenance', '--json'] },+ };+}++export async function readUpkeepStatus(engine: BrainEngine, nowMs: number = Date.now()): Promise<UpkeepStatus> {+ const now = new Date(nowMs);+ const [record, enabled, owner, pending, cap, spent] = await Promise.all([+ readUpkeepRecord(engine), upkeepEnabled(engine), autopilotOwnsUpkeep(engine, now), pendingPurgeCount(engine),+ readEmbedDailyCapUsd(engine), readEmbedSpentToday(engine, now),+ ]);+ const keyed = isAvailable('embedding');+ const base = {+ runner: record?.runner ?? null, last_run: record?.at ?? null, steps: record?.steps ?? [], held: record?.held ?? [],+ next_due_at: record?.next_due_at ?? null, failing: null as UpkeepFailure | null, pending_purge_count: pending,+ paid_phases_opt_in: [...PAID_PHASES], embed_spend_today_usd: keyed ? spent : null, embed_daily_cap_usd: keyed ? cap : null,+ };+ const purgeNote = pending+ ? ` Nothing deletes on its own: ${pending} deleted page(s) wait for you (preview: gbrain maintain --purge).`+ : ' Nothing deletes on its own.';+ const spendNote = keyed ? ` Embedding catch-up: $${spent.toFixed(2)} of $${cap.toFixed(2)} today.` : '';+ if (!enabled) return { ...base, state: 'off', message: 'Free upkeep is off (maintenance.auto is false); turn it back on with gbrain config set maintenance.auto true.' };+ if (owner) return { ...base, state: 'autopilot', message: `An autopilot keeps this brain maintained (last brain-wide pass ${ago(nowMs - Date.parse(owner))} ago), so free upkeep stays out of its way.${purgeNote}` };+ const fix = upkeepFix(keyed && cap > 0);+ const failing = record?.consecutive_failures.find((f) => f.count >= UPKEEP_BACKOFF_FAILURES) ?? null;+ if (failing) {+ return { ...base, failing, fix, state: 'failing',+ message: `The last ${failing.count} upkeep runs failed at ${failing.step} (${failing.scope}) with ${failing.code}; that step now runs once a week until it succeeds.${spendNote}` };+ }+ if (!record) {+ const age = await brainAgeMs(engine, nowMs);+ if (age === null || age < UPKEEP_OVERDUE_MS) {+ return { ...base, state: 'never', message: `Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge).${purgeNote}` };+ }+ return { ...base, fix, state: 'overdue', message: `No free upkeep run is recorded on this brain, which is ${ago(age)} old.${purgeNote}` };+ }+ const age = nowMs - Date.parse(record.at);+ if (age > UPKEEP_OVERDUE_MS) {+ return { ...base, fix, state: 'overdue', message: `Free upkeep last ran ${ago(age)} ago (${record.runner}), past its 48h window.${purgeNote}${spendNote}` };+ }+ const ran = record.steps.filter((s) => s.status === 'ok' || s.status === 'warn').length;+ const due = Date.parse(record.next_due_at) - nowMs;+ return { ...base, state: 'ok',+ message: `Free upkeep ran ${ago(age)} ago (${record.runner}, ${ran} steps ok). ${record.cursor ? 'The round continues on the next run.' : due > 0 ? `Next due in ${ago(due)}.` : 'Due now.'}${purgeNote}${spendNote}` };+}diff --git a/test/autopilot-install-repo-fallback-6755.test.ts b/test/autopilot-install-repo-fallback-6755.test.tsindex 0fbc566541..0c74d30e74 100644--- a/test/autopilot-install-repo-fallback-6755.test.ts+++ b/test/autopilot-install-repo-fallback-6755.test.ts@@ -24,8 +24,10 @@ async function install(brain: { syncRepoPath?: string; defaultSourcePath?: strinconst log = console.log;const error = console.error;const exit = process.exit;+ const stderrWrite = process.stderr.write;console.log = () => {};console.error = (...p: unknown[]) => { stderr.push(p.map(String).join(' ')); };+ process.stderr.write = ((chunk: string | Uint8Array) => { stderr.push(String(chunk)); return true; }) as typeof process.stderr.write;process.exit = ((code?: number) => { exitCode = code ?? 0; throw new Error('process.exit'); }) as typeof process.exit;_resetCliExitVerdictForTests();try {@@ -40,6 +42,7 @@ async function install(brain: { syncRepoPath?: string; defaultSourcePath?: strin} finally {console.log = log;console.error = error;+ process.stderr.write = stderrWrite;process.exit = exit;}});diff --git a/test/autopilot-refusals-gbra438.test.ts b/test/autopilot-refusals-gbra438.test.tsnew file mode 100644index 0000000000..92327e6c91--- /dev/null+++ b/test/autopilot-refusals-gbra438.test.ts@@ -0,0 +1,38 @@+/**+ * GBRA-438: `gbrain autopilot --install` refusals on PGLite and repo-less brains.+ *+ * 1. Protects: both refusals carry a registered code, a why, and a fix that+ * points a PGLite or repo-less brain at free upkeep instead of a daemon.+ * 2. Fails when: a refusal loses its code, its fix asks for consent on the+ * free path, or the Postgres no-repo fix stops asking the user for the dir.+ * 3. Real seams: the refusal builders autopilot.ts passes to exitCliError.+ */+import { describe, expect, test } from 'bun:test';+import { autopilotNoRepoRefusal, autopilotPgliteRefusal } from '../src/commands/autopilot-refusals.ts';+import { CODES } from '../src/core/error-registry.ts';++describe('autopilot --install refusals (GBRA-438)', () => {+ test('PGLite daemon refusal points at free upkeep', () => {+ const e = autopilotPgliteRefusal('PGLite holds one writer.\nsecond line');+ expect(e.code).toBe('autopilot_pglite_daemon');+ expect(e.message).toBe('PGLite holds one writer.');+ expect(e.why).toBeTruthy();+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'maintain', '--status'], consent: [] });+ });++ test('repo-less PGLite brain is sent to free upkeep, not asked for a repo', () => {+ const e = autopilotNoRepoRefusal('pglite');+ expect(e.code).toBe('autopilot_no_repo');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'maintain', '--status'], consent: [] });+ });++ test('Postgres brain without a repo is asked for the directory', () => {+ const e = autopilotNoRepoRefusal('postgres');+ expect(e.code).toBe('autopilot_no_repo');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'autopilot', '--install', '--repo', '<dir>'], ask_user: true, consent: ['persistent_install'] });+ });++ test('both codes are registered', () => {+ expect(Object.keys(CODES)).toEqual(expect.arrayContaining(['autopilot_pglite_daemon', 'autopilot_no_repo']));+ });+});diff --git a/test/doctor-cycle-freshness.test.ts b/test/doctor-cycle-freshness.test.tsindex 54dd70de80..e1dd1ab432 100644--- a/test/doctor-cycle-freshness.test.ts+++ b/test/doctor-cycle-freshness.test.ts@@ -9,6 +9,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tesimport { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { checkCycleFreshness } from '../src/commands/doctor.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';let engine: PGLiteEngine;@@ -124,9 +125,14 @@ describe('doctor checkCycleFreshness', () => {test('E2: a never-cycled source with old pages still warns, with a dream fix that asks first', async () => {await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);await seed('old-vault');- const result = await checkCycleFreshness(engine, { nowMs: NOW });- expect(result.status).toBe('warn');- expect(result.fix).toMatchObject({ argv: ['gbrain', 'dream', '--source', 'old-vault'], consent: ['paid'], actor: 'agent' });+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });+ try {+ const result = await checkCycleFreshness(engine, { nowMs: NOW });+ expect(result.status).toBe('warn');+ expect(result.fix).toMatchObject({ argv: ['gbrain', 'dream', '--source', 'old-vault'], consent: ['paid'], actor: 'agent' });+ } finally {+ resetGateway();+ }});test('reporter case (#2540): one cycled vault + never-cycled siblings is warn, not permanent fail', async () => {diff --git a/test/e2e/maintain-unattended-keyless-pglite.test.ts b/test/e2e/maintain-unattended-keyless-pglite.test.tsnew file mode 100644index 0000000000..86dab6ea0a--- /dev/null+++ b/test/e2e/maintain-unattended-keyless-pglite.test.ts@@ -0,0 +1,60 @@+/**+ * GBRA-438 PR 1, done item 9: free upkeep on a fresh keyless, repo-less+ * PGLite brain, black-box through the real CLI. Import leaves links+ * unextracted (link_count 0); one \`gbrain maintain --unattended\` extracts+ * them, writes maintenance.last_run, and doctor's unattended_maintenance+ * shows the ok line. A second run is not due. \`maintain --status\` on a home+ * with no brain refuses no_brain with exit 1.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from '../helpers/cli-spawn.ts';++const KEYLESS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GEMINI_API_KEY: undefined, JEV_TYPESAFE_API_KEY: undefined };+const TIMEOUT_MS = 120_000;++describe('maintain --unattended on a fresh keyless repo-less PGLite brain', () => {+ let home: string;+ const gbrain = (args: string[], h = home) => runCli(args, { home: h, env: KEYLESS, timeoutMs: TIMEOUT_MS });++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-upkeep-e2e-'));+ const init = await gbrain(['init', '--pglite', '--no-embedding', '--non-interactive']);+ expect(init.exitCode).toBe(0);+ const notes = join(home, 'notes');+ mkdirSync(notes);+ writeFileSync(join(notes, 'alpha.md'), '---\ntitle: Alpha\ntype: concept\n---\n# Alpha\n\nAlpha relies on [[beta]].\n');+ writeFileSync(join(notes, 'beta.md'), '---\ntitle: Beta\ntype: concept\n---\n# Beta\n\nBeta.\n');+ expect((await gbrain(['import', notes, '--no-embed'])).exitCode).toBe(0);+ }, TIMEOUT_MS);++ afterAll(() => rmSync(home, { recursive: true, force: true }));++ test('extracts links, records the run, and doctor shows the ok line', async () => {+ expect(JSON.parse((await gbrain(['stats', '--json'])).stdout).link_count).toBe(0);+ const run = await gbrain(['maintain', '--unattended', '--json']);+ expect(run.exitCode).toBe(0);+ const outcome = JSON.parse(run.stdout);+ expect(outcome).toMatchObject({ status: 'ran', exit: 0, record: { runner: 'cli', status: 'ok', cursor: null } });+ expect(outcome.record.steps.map((s: { name: string }) => s.name)).not.toContain('purge');+ const links = JSON.parse((await gbrain(['backlinks', 'beta', '--json'])).stdout);+ expect(links.map((l: { from_slug: string }) => l.from_slug)).toEqual(['alpha']);+ const doctor = JSON.parse((await gbrain(['doctor', '--only', 'unattended_maintenance', '--json'])).stdout);+ const check = doctor.checks.find((c: { name: string }) => c.name === 'unattended_maintenance');+ expect(check).toMatchObject({ status: 'ok', details: { state: 'ok', runner: 'cli' } });+ expect(check.message).toMatch(/^Free upkeep ran \d+m ago \(cli, \d+ steps ok\)\. Next due in \d+h\. Nothing deletes on its own\./);+ const again = JSON.parse((await gbrain(['maintain', '--unattended', '--json'])).stdout);+ expect(again).toMatchObject({ status: 'not_due', exit: 0 });+ }, TIMEOUT_MS);++ test('--status on a home with no brain refuses no_brain with exit 1', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'gbrain-upkeep-empty-'));+ try {+ const out = await gbrain(['maintain', '--status', '--json'], empty);+ expect(out.exitCode).toBe(1);+ expect(out.stdout + out.stderr).toContain('no_brain');+ } finally { rmSync(empty, { recursive: true, force: true }); }+ }, TIMEOUT_MS);+});diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 3b272ef293..35187f8042 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -193,6 +193,7 @@" [OK] facts_health: facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —"," [OK] global_maintenance_timeouts: Brain-wide maintenance jobs are finishing within their deadline."," [OK] global_maintenance_stalled: Brain-wide maintenance has not run yet.",+ " [INFO] unattended_maintenance: Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own."," [OK] embed_backfill_stalled: No automatic embed-backfill is repeating the same failure."," [OK] content_drift_sweep: The content-drift sweep has not run yet; it runs inside embed --stale and the embed jobs."," [OK] connector_account_mismatch: No connector source is waiting for its account to be repinned.",@@ -289,7 +290,7 @@" [OK] oauth_client_scope_health: Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)"," [OK] autopilot_lock_scope: Lock path: <home>/.gbrain/autopilot.lock"," [OK] stale_locks: No stale locks (no rows with ttl_expires_at < NOW())",- " [OK] cycle_phase_scope: Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ " [OK] cycle_phase_scope: Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns]."," [INFO] embed_staleness: Not applicable: embeddings are disabled on this brain by choice, so chunks have no vectors by design (keyword search keeps working)."," [OK] entity_link_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale"," [OK] timeline_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 7b9a5d1f5d..51155ab54e 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -2376,6 +2376,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -4210,12 +4245,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -4249,7 +4285,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 1a48759622..0cc53d8f1c 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -2548,6 +2548,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -4641,12 +4676,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -4680,7 +4716,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},@@ -7671,6 +7707,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -9776,12 +9847,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -9815,7 +9887,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex ffab954553..e1a9f40cf5 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -2559,6 +2559,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -4651,12 +4686,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -4690,7 +4726,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},@@ -7690,6 +7726,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -9794,12 +9865,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -9833,7 +9905,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 33216de7b1..e493207b42 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2175,6 +2175,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -3788,12 +3823,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -3827,7 +3863,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 932946be75..4e476202b1 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2231,6 +2231,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -3832,12 +3867,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -3871,7 +3907,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 038abf31ee..2428285bd3 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -2242,6 +2242,41 @@"name": "global_maintenance_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "embed_daily_cap_usd": null,+ "embed_spend_today_usd": null,+ "last_run": null,+ "next_due_at": null,+ "paid_phases_opt_in": [+ "extract_atoms",+ "synthesize_concepts",+ "propose_takes",+ "grade_takes",+ "calibration_profile",+ "edge_contradictions",+ "drift",+ "standing_questions",+ "chronicle",+ "facts_drain",+ "conversation_facts_backfill",+ "enrich_thin",+ "skillopt",+ "embed"+ ],+ "pending_purge_count": 0,+ "runner": null,+ "state": "never",+ "steps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge). Nothing deletes on its own.",+ "name": "unattended_maintenance",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -3842,12 +3877,13 @@"category": "meta","details": {"counts": {- "global": 17,+ "global": 18,"mixed": 2,"source": 12},"phase_scope_map": {"backlinks": "source",+ "bookkeeping_gc": "global","calibration_profile": "global","chronicle": "global","claim_conflicts": "global",@@ -3881,7 +3917,7 @@}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 17 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 18 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, claim_conflicts, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge, bookkeeping_gc]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e159fdc11e..cb07e1f733 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -817,6 +817,10 @@"category": "ops","name": "global_maintenance_stalled"},+ {+ "category": "ops",+ "name": "unattended_maintenance"+ },{"category": "ops","name": "embed_backfill_stalled"diff --git a/test/maintenance-unattended.test.ts b/test/maintenance-unattended.test.tsnew file mode 100644index 0000000000..45076ad0b9--- /dev/null+++ b/test/maintenance-unattended.test.ts@@ -0,0 +1,335 @@+/**+ * GBRA-438 PR 1: free unattended upkeep (src/core/maintenance/run.ts), its+ * status view and doctor check, on a repo-less brain (the default keyless+ * install) and on Postgres when DATABASE_URL is set.+ *+ * 1. Protects: upkeep runs only the free phases and the bookkeeping GC, never+ * the page purge or a paid phase; it never writes a cycle freshness stamp;+ * brain-wide steps run once per window on a multi-source brain; every skip+ * comes back with its code, exit and fix; a keyed brain spends nothing past+ * maintenance.embed_daily_usd; doctor and --status read one record.+ * 2. Fails when: a purge or paid phase enters the unattended list, a stamp is+ * written, a global step repeats per source, a skip throws or exits 1, a+ * gateway call happens with the cap at 0, or a doctor state is misread.+ * 3. Real seams: runCycle on PGLite and Postgres, the gateway's embed+ * transport (a spy), the AI invocation observer, the CLI's runMaintain.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { ALL_PHASES, PHASE_SCOPE, runCycle, type CyclePhase } from '../src/core/cycle.ts';+import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';+import {+ MAINTAIN_SAFE_PHASES, MAINTENANCE_EMBED_SPEND_KEY, UPKEEP_INTERVAL_MS, readUpkeepRecord, runUnattendedMaintenance, unattendedPlan,+ type SafePhaseProviders,+} from '../src/core/maintenance/run.ts';+import { checkUnattendedMaintenance } from '../src/commands/doctor/checks/unattended-maintenance.ts';+import { checkCycleFreshness } from '../src/commands/doctor/checks/consolidation-cycle.ts';+import { runMaintain } from '../src/commands/maintain.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { observeAIInvocations } from '../src/core/ai/invocation-guard.ts';+import { tryAcquireDbLock } from '../src/core/db-lock.ts';+import { DEGRADED_STATE } from '../src/core/degraded-marker.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const KEYLESS: SafePhaseProviders = { embedding: false, decideConflict: false, fenceRepairModel: false, contentRepairModel: false };+const KEYED: SafePhaseProviders = { ...KEYLESS, embedding: true };+const HOUR = 60 * 60 * 1000;+const FENCE = (claim: string) => ['## Facts', '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ '| 1 | ' + claim + ' | fact | 1.0 | world | medium | 2017-01-01 | | chat | |', '<!--- gbrain:facts:end -->', ''].join('\n');++describe('the unattended step list', () => {+ test('free and filesystem phases only, plus the bookkeeping GC; never the purge or a paid phase', () => {+ for (const providers of [KEYLESS, KEYED, { ...KEYED, decideConflict: true, fenceRepairModel: true, contentRepairModel: true }]) {+ const plan = unattendedPlan(providers);+ const all = [...plan.global, ...plan.source];+ expect(all).toContain('bookkeeping_gc');+ expect(all).not.toContain('purge');+ for (const phase of all) expect(['free', 'filesystem', phase === 'bookkeeping_gc' ? 'deletes' : 'free']).toContain(MANAGED_PHASE_TABLE[phase].tier);+ expect(plan.global.every((phase) => PHASE_SCOPE[phase] !== 'source')).toBe(true);+ expect(plan.source.every((phase) => PHASE_SCOPE[phase] === 'source')).toBe(true);+ }+ });++ test('the --safe list is free or filesystem tier', () => {+ for (const phase of MAINTAIN_SAFE_PHASES) expect(['free', 'filesystem']).toContain(MANAGED_PHASE_TABLE[phase].tier);+ });++ test('a keyed brain keeps extract_facts with its embedding deferred; the System One slot holds it', () => {+ expect(unattendedPlan(KEYED)).toMatchObject({ embedding: true, held: ['fence_repair', 'content_repair'] });+ expect(unattendedPlan(KEYED).source).toContain('extract_facts');+ expect(unattendedPlan({ ...KEYLESS, decideConflict: true }).held).toContain('extract_facts');+ expect(unattendedPlan(KEYLESS)).toMatchObject({ embedding: false, held: [] });+ });+});++for (const kind of testBackends()) {+ describe(GBRA_TITLE(kind), () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let home: string;+ const calls: string[] = [];+ let stopObserving: () => void;++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-upkeep-'));+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ stopObserving = observeAIInvocations((event) => { calls.push(event.call.kind); });+ });++ afterAll(async () => {+ stopObserving();+ __setEmbedTransportForTests(null);+ resetGateway();+ await close();+ rmSync(home, { recursive: true, force: true });+ });++ beforeEach(async () => {+ calls.length = 0;+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'maintenance.%' OR key = 'autopilot.last_global_at'");+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb WHERE id = 'default'");+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op LIKE 'upkeep-%'");+ });++ /** A keyed brain at the schema's own vector width, with a spy for a transport. */+ async function keyed() {+ const [col] = await engine.executeRaw<{ dims: number }>("SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'");+ const dims = Number(col!.dims);+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-small');+ await engine.setConfig('embedding_dimensions', String(dims));+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => new Array(dims).fill(0.01)) })) as never);+ }++ const upkeep = (e: BrainEngine, opts: Parameters<typeof runUnattendedMaintenance>[1]) => withEnv({ GBRAIN_HOME: home }, () => runUnattendedMaintenance(e, opts));++ async function maintainJson(args: string[]): Promise<Record<string, unknown>> {+ const out: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ try { await withEnv({ GBRAIN_HOME: home }, () => runMaintain(engine, args)); } finally { spy.mockRestore(); }+ return JSON.parse(out.join('\n'));+ }++ test('maintain --unattended removes GC rows past retention while a page soft-deleted 100h ago survives', async () => {+ await engine.putPage('notes/old', { type: 'concept', title: 'Old', compiled_truth: 'An old note.' });+ await engine.softDeletePage('notes/old');+ await engine.executeRaw("UPDATE pages SET deleted_at = now() - interval '100 hours' WHERE slug = 'notes/old'");+ await engine.executeRaw("INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ('upkeep-gc', 'a', '[]'::jsonb, now() - interval '8 days')");+ await engine.executeRaw("INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ('upkeep-fresh', 'b', '[]'::jsonb, now())");+ const out = await maintainJson(['--unattended', '--json']);+ expect(out).toMatchObject({ status: 'ran', exit: 0 });+ expect(await engine.executeRaw("SELECT op FROM op_checkpoints WHERE op LIKE 'upkeep-%' ORDER BY op")).toEqual([{ op: 'upkeep-fresh' }]);+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE slug = 'notes/old' AND deleted_at IS NOT NULL")).toEqual([{ slug: 'notes/old' }]);+ const record = await readUpkeepRecord(engine);+ expect(record!.steps.map((s) => s.name)).toContain('bookkeeping_gc');+ expect(record!.steps.map((s) => s.name)).not.toContain('purge');+ });++ test('stamp honesty: a keyed brain keeps last_full_cycle_at and last_source_cycle_at', async () => {+ await keyed();+ await engine.setConfig('maintenance.embed_daily_usd', '0');+ await engine.putPage('notes/a', { type: 'concept', title: 'A', compiled_truth: 'See [[notes/b]].' });+ const stamp = { last_full_cycle_at: '2026-01-01T00:00:00.000Z', last_source_cycle_at: '2026-01-02T00:00:00.000Z' };+ await engine.updateSourceConfig('default', stamp);+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYED });+ expect(outcome.status).toBe('ran');+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> }>("SELECT config FROM sources WHERE id = 'default'");+ const config = typeof source!.config === 'string' ? JSON.parse(source!.config as never) : source!.config;+ expect({ last_full_cycle_at: config.last_full_cycle_at, last_source_cycle_at: config.last_source_cycle_at }).toEqual(stamp);+ });++ test('a 3-source brain runs each global step once per window and each source step once per source', async () => {+ for (const id of ['wiki-a', 'wiki-b']) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [id]);+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ const plan = unattendedPlan(KEYLESS);+ const steps = outcome.record!.steps;+ for (const phase of plan.global) expect(steps.filter((s) => s.name === phase).map((s) => s.scope)).toEqual(['global']);+ for (const phase of plan.source) expect(steps.filter((s) => s.name === phase).map((s) => s.scope).sort()).toEqual(['default', 'wiki-a', 'wiki-b']);+ expect(outcome.record!.cursor).toBeNull();+ const again = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ expect(again).toMatchObject({ status: 'not_due', exit: 0 });+ const later = await upkeep(engine, { runner: 'test', providers: KEYLESS, now: () => new Date(Date.now() + UPKEEP_INTERVAL_MS + HOUR) });+ expect(later.status).toBe('ran');+ });++ describe('error contract, one test per row', () => {+ test('lock held by another cycle: cycle_already_running, exit 0, wait', async () => {+ const held = await tryAcquireDbLock(engine, 'gbrain-cycle', 5);+ try {+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'cycle_already_running', fix: { actor: 'provider' } });+ } finally { await held!.release(); }+ });++ test('engine degraded: engine_degraded, exit 0, report', async () => {+ const degraded = Object.assign(Object.create(engine), { [DEGRADED_STATE]: () => true }) as BrainEngine;+ const outcome = await upkeep(degraded, { runner: 'test', providers: KEYLESS });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'engine_degraded' });+ expect(outcome.fix?.argv).toBeUndefined();+ });++ test('migrations pending: migrations_pending, exit 0, run the migrate fix', async () => {+ const version = await engine.getConfig('version');+ await engine.setConfig('version', '1');+ try {+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'migrations_pending', fix: { argv: ['gbrain', 'apply-migrations', '--yes'], actor: 'agent' } });+ } finally { await engine.setConfig('version', version!); }+ });++ test('low write capacity: the capacity code, exit 0, tell_user_to_run', async () => {+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS,+ capacityPaused: async () => ({ command: 'gbrain config set persistence.capacity.max_request_ids 2000000', config_key: 'persistence.capacity.max_request_ids' }) });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'write_capacity_backpressure', fix: { actor: 'host_admin' } });+ });++ test('maintenance.auto=false: maintenance_disabled, exit 0, no fix', async () => {+ await engine.setConfig('maintenance.auto', 'false');+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'maintenance_disabled' });+ expect(outcome.fix).toBeUndefined();+ });++ test('autopilot owns upkeep: maintenance_owned_by_autopilot, exit 0, no fix', async () => {+ await engine.setConfig('autopilot.last_global_at', new Date(Date.now() - HOUR).toISOString());+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS });+ expect(outcome).toMatchObject({ status: 'skipped', exit: 0, code: 'maintenance_owned_by_autopilot' });+ expect(outcome.fix).toBeUndefined();+ });++ test('a step failed: its own code, exit 1; three runs in a row back it off and doctor warns', async () => {+ const failing: typeof runCycle = async (e, o) => {+ const report = await runCycle(e, o);+ return { ...report, phases: report.phases.map((p) => p.phase === 'orphans' ? { ...p, status: 'fail' as const, code: 'orphans_probe_failed' } : p) };+ };+ let at = Date.now();+ for (let i = 0; i < 3; i++) {+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYLESS, cycle: failing, now: () => new Date(at) });+ expect(outcome).toMatchObject({ status: 'ran', exit: 1, code: 'orphans_probe_failed' });+ at += UPKEEP_INTERVAL_MS + HOUR;+ }+ const record = await readUpkeepRecord(engine);+ expect(record!.consecutive_failures).toEqual([expect.objectContaining({ step: 'orphans', scope: 'global', code: 'orphans_probe_failed', count: 3 })]);+ const backedOff = await upkeep(engine, { runner: 'test', providers: KEYLESS, cycle: failing, now: () => new Date(at) });+ expect(backedOff.record!.steps).toContainEqual({ name: 'orphans', scope: 'global', status: 'skipped', reason: 'backed_off' });+ const check = await checkUnattendedMaintenance(engine, { nowMs: at });+ expect(check).toMatchObject({ status: 'warn', details: { state: 'failing' } });+ expect(check.message).toContain('orphans');+ });+ });++ describe('decision D: the embedding cap', () => {+ test('embed_daily_usd 0: zero gateway calls, extract_facts included', async () => {+ await keyed();+ await engine.setConfig('maintenance.embed_daily_usd', '0');+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: 'Alice works on search.\n\n' + FENCE('Alice leads the search team') });+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYED });+ expect(outcome.status).toBe('ran');+ expect(outcome.record!.steps).toContainEqual(expect.objectContaining({ name: 'extract_facts', status: 'ok' }));+ expect(outcome.record!.steps).toContainEqual({ name: 'embed', scope: 'global', status: 'skipped', reason: 'embed_cap_off' });+ expect(await engine.executeRaw('SELECT fact FROM facts WHERE embedding IS NULL')).toEqual([{ fact: 'Alice leads the search team' }]);+ expect(calls).toEqual([]);+ });++ test('at the default $1 cap the step stops, and doctor shows the spend', async () => {+ await keyed();+ await engine.putPage('notes/embed-me', { type: 'concept', title: 'Embed', compiled_truth: 'A page whose chunks need vectors.' });+ const today = new Date().toISOString().slice(0, 10);+ await engine.setConfig(MAINTENANCE_EMBED_SPEND_KEY, JSON.stringify({ day: today, usd: 1 }));+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYED });+ expect(outcome.record!.steps).toContainEqual({ name: 'embed', scope: 'global', status: 'skipped', reason: 'daily_cap_reached' });+ expect(calls).toEqual([]);+ const check = await withEnv({ OPENAI_API_KEY: 'test' }, () => checkUnattendedMaintenance(engine));+ expect(check.message).toContain('$1.00 of $1.00 today');+ });++ test('under the cap the backlog is embedded and the spend recorded', async () => {+ await keyed();+ await engine.putPage('notes/embed-me', { type: 'concept', title: 'Embed', compiled_truth: 'A page whose chunks need vectors.' });+ const outcome = await upkeep(engine, { runner: 'test', providers: KEYED });+ expect(outcome.record!.steps).toContainEqual(expect.objectContaining({ name: 'embed', status: 'ok' }));+ expect(outcome.record!.embed!.cap_usd).toBe(1);+ expect(outcome.record!.embed!.spent_today_usd).toBeLessThanOrEqual(1);+ });+ });++ describe('doctor states with a fixed clock', () => {+ const NOW = Date.parse('2026-11-12T12:00:00.000Z');+ const record = (at: number, extra: Record<string, unknown> = {}) => engine.setConfig('maintenance.last_run', JSON.stringify({+ at: new Date(at).toISOString(), runner: 'cli', status: 'ok', steps: [{ name: 'extract', scope: 'default', status: 'ok' }], held: [], cursor: null,+ next_due_at: new Date(at + UPKEEP_INTERVAL_MS).toISOString(), consecutive_failures: [], ...extra }));++ test('ok', async () => {+ await record(NOW - 3 * HOUR);+ const check = await checkUnattendedMaintenance(engine, { nowMs: NOW });+ expect(check).toMatchObject({ status: 'ok', details: { state: 'ok', runner: 'cli' } });+ expect(check.message).toMatch(/^Free upkeep ran 3h ago \(cli, 1 steps ok\)\. Next due in 21h\./);+ });++ test('info on a brain under 48h old with no run', async () => {+ await engine.putPage('notes/new', { type: 'concept', title: 'New', compiled_truth: 'Fresh.' });+ const check = await checkUnattendedMaintenance(engine, { nowMs: Date.now() });+ expect(check).toMatchObject({ status: 'ok', severity: 'info', details: { state: 'never' } });+ });++ test('off', async () => {+ await engine.setConfig('maintenance.auto', 'false');+ expect(await checkUnattendedMaintenance(engine, { nowMs: NOW })).toMatchObject({ status: 'ok', details: { state: 'off' } });+ });++ test('autopilot owns', async () => {+ await engine.setConfig('autopilot.last_global_at', new Date(NOW - HOUR).toISOString());+ expect(await checkUnattendedMaintenance(engine, { nowMs: NOW })).toMatchObject({ status: 'ok', details: { state: 'autopilot' } });+ });++ test('warn overdue, with a free fix on a keyless brain', async () => {+ await record(NOW - 72 * HOUR);+ const check = await checkUnattendedMaintenance(engine, { nowMs: NOW });+ expect(check).toMatchObject({ status: 'warn', details: { state: 'overdue' }, fix: { argv: ['gbrain', 'maintain', '--unattended'], consent: [] } });+ });++ test('warn after 3 failures', async () => {+ await record(NOW - HOUR, { consecutive_failures: [{ step: 'extract', scope: 'default', code: 'extract_failed', count: 3, last_at: new Date(NOW - HOUR).toISOString() }] });+ const check = await checkUnattendedMaintenance(engine, { nowMs: NOW });+ expect(check).toMatchObject({ status: 'warn', details: { state: 'failing' } });+ expect(check.message).toContain('The last 3 upkeep runs failed at extract (default) with extract_failed');+ });++ test('maintain --status --json shape', async () => {+ await record(Date.now() - HOUR);+ const out = await maintainJson(['--status', '--json']);+ expect(Object.keys(out).sort()).toEqual(['embed_daily_cap_usd', 'embed_spend_today_usd', 'failing', 'held', 'last_run', 'message', 'next_due_at',+ 'paid_phases_opt_in', 'pending_purge_count', 'runner', 'state', 'steps']);+ expect(out).toMatchObject({ state: 'ok', runner: 'cli', embed_spend_today_usd: null, embed_daily_cap_usd: null, pending_purge_count: 0 });+ expect(out.paid_phases_opt_in).toContain('embed');+ });++ test('cycle_freshness asks consent: [] on a keyless brain', async () => {+ await engine.putPage('notes/old', { type: 'concept', title: 'Old', compiled_truth: 'Old.' });+ await engine.executeRaw("UPDATE pages SET created_at = now() - interval '10 days'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [join(home, 'content')]);+ const check = await withEnv({ OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GEMINI_API_KEY: undefined }, () => checkCycleFreshness(engine));+ expect(check.status).toBe('warn');+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'dream', '--source', 'default'], consent: [] });+ });+ });+ });+}++function GBRA_TITLE(kind: string): string {+ return 'unattended upkeep (' + kind + ', repo-less)';+}diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex 25648d1e61..224ec87a3d 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -467,6 +467,18 @@ const MATRIX: Record<CyclePhase, Entry> = {expect((await committed(engine, sourceId, 'notes/expired')).at(-1)?.outcome?.status).toBe('purged');},},+ bookkeeping_gc: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'notes/kept-deleted', page('note', 'Kept', 'Deleted, but GC never purges pages.'));+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/kept-deleted'", [sourceId]);+ await engine.executeRaw("INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ('matrix-gc', $1, '[]'::jsonb, now() - interval '8 days')", [sourceId]);+ },+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details.purged_checkpoints_count).toBeGreaterThanOrEqual(1);+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='matrix-gc' AND fingerprint=$1", [sourceId])).toEqual([]);+ expect(await engine.readPageSnapshot('notes/kept-deleted', { sourceId, includeDeleted: true })).not.toBeNull();+ },+ },};test('every cycle phase is classified for managed brains, with no extra keys', () => {@@ -475,6 +487,11 @@ test('every cycle phase is classified for managed brains, with no extra keys', (for (const entry of Object.values(MANAGED_PHASE_TABLE)) expect(entry.reason.length).toBeGreaterThan(0);});+test('every cycle phase carries a tier (GBRA-438)', () => {+ const missing = ALL_PHASES.filter(phase => !['free', 'paid', 'deletes', 'filesystem'].includes((MANAGED_PHASE_TABLE[phase] as { tier?: string } | undefined)?.tier ?? ''));+ expect(missing).toEqual([]);+});+const REFUSALS = ['writer_coordinator_required', 'owner_unavailable'];/** Seeds one managed brain for `phase`, runs only that phase through runCycle, and hands the result (plus anything logged to stderr) to `check`. */diff --git a/test/phase-scope-coverage.test.ts b/test/phase-scope-coverage.test.tsindex 59579c1954..63472682af 100644--- a/test/phase-scope-coverage.test.ts+++ b/test/phase-scope-coverage.test.ts@@ -41,7 +41,7 @@ describe('PHASE_SCOPE coverage', () => {expect(invalid).toEqual([]);});- test('all 31 phases covered (regression on accidental omission)', () => {+ test('all 32 phases covered (regression on accidental omission)', () => {// Pin the count so a future PR that adds a phase to ALL_PHASES// without updating PHASE_SCOPE notices here too. The v0.39.1.0// master merge brought in the 17th phase (`schema-suggest`); v0.41@@ -53,9 +53,9 @@ describe('PHASE_SCOPE coverage', () => {// Temporal typed edges adds 'edge_contradictions' for 26; C4 pinned// questions adds 'standing_questions' for 27.// #6188 adds 'fence_repair' for 28; #6377 adds 'content_repair' for 29; #6865 adds 'unindexed_files' for 30.- // GBRA-216 adds 'claim_conflicts' for 31.- expect(ALL_PHASES.length).toBe(31);- expect(Object.keys(PHASE_SCOPE).length).toBe(31);+ // GBRA-216 adds 'claim_conflicts' for 31; GBRA-438 splits 'bookkeeping_gc' out of purge for 32.+ expect(ALL_PHASES.length).toBe(32);+ expect(Object.keys(PHASE_SCOPE).length).toBe(32);});test('embed remains global (the headline brain-wide phase)', () => {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 8844966e9f..1cf5276a1c 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -294,6 +294,7 @@ test/list-pages-empty-type-notice-gbra449.test.tstest/lower-tier-label-hold.test.tstest/maintenance-lowering-7917-7918.test.tstest/maintenance-trust-marker-7905.test.ts+test/maintenance-unattended.test.tstest/managed-cycle-pull-upstream.test.tstest/managed-facts-withdrawal-recovery-6506.test.tstest/managed-facts-withdrawn-skip-6506.test.ts