Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
frontmatter validate checks every path, and doctor, serve idle upkeep and update-check fixes (small-fix wave 6) (#9560)
Garry Tan8bbfd0b5e83c
diff --git a/behavior-changes.d/frontmatter_validate_every_path.md b/behavior-changes.d/frontmatter_validate_every_path.mdnew file mode 100644index 0000000000..ee9c8711e3--- /dev/null+++ b/behavior-changes.d/frontmatter_validate_every_path.md@@ -0,0 +1,4 @@+---+kind: fix+---+gbrain frontmatter validate now checks every path it is given. With several paths it used to check only the last one, so a bad file named earlier could pass with exit 0. It now checks all of them, exits 1 if any fails, and refuses before checking anything when a path does not exist. With --json and more than one path, the output adds a targets list.diff --git a/behavior-changes.d/serve_http_refused_not_activity_9484.md b/behavior-changes.d/serve_http_refused_not_activity_9484.mdnew file mode 100644index 0000000000..59a860f8d2--- /dev/null+++ b/behavior-changes.d/serve_http_refused_not_activity_9484.md@@ -0,0 +1,4 @@+---+kind: fix+---+gbrain serve --http no longer counts a request refused for a missing or wrong bearer token as activity. Idle upkeep waits for a quiet interval, and requests anyone could send without a token used to reset that interval, so upkeep might never run. Authenticated requests, including pings, still count as before.diff --git a/behavior-changes.d/update_cache_future_stamp_8795.md b/behavior-changes.d/update_cache_future_stamp_8795.mdnew file mode 100644index 0000000000..57020dee4e--- /dev/null+++ b/behavior-changes.d/update_cache_future_stamp_8795.md@@ -0,0 +1,4 @@+---+kind: fix+---+The update check no longer trusts a saved answer stamped in the future. After a computer's clock moved backwards, the saved answer could stay "fresh" and block every refresh, which hid newer releases and a withdrawn-release notice. A saved answer more than 5 minutes ahead of the clock is now stale and is replaced on the next check.diff --git a/changelog.d/capy-small-fix-wave-6.md b/changelog.d/capy-small-fix-wave-6.mdnew file mode 100644index 0000000000..9f499da605--- /dev/null+++ b/changelog.d/capy-small-fix-wave-6.md@@ -0,0 +1,13 @@+**`gbrain frontmatter validate` checks every path you give it, and doctor, `gbrain serve --http`, the update check and the agent-session repair each get a small fix.**++### Fixed+- `gbrain frontmatter validate a.md b.md` validated only the last path and could report ok for a bad file named earlier. It now checks every path, walks each directory, checks a file named twice once, refuses before checking anything when a path is missing, and lists the paths as `targets` in `--json` when there is more than one.+- Doctor no longer tells you to run `gbrain sync` for a gbrain-owned content folder on a brain with persistence off, which sync refuses. The check still fails, and it now names the `gbrain import` command that works for that folder.+- `gbrain transcripts archive status` says when `maintenance.auto` is false, because free upkeep then doesn't archive conversations by itself (an installed autopilot still does). The line names `gbrain transcripts archive run`.+- `gbrain serve --http` no longer treats a request refused for a missing or wrong token as activity, so unauthenticated traffic can't keep idle upkeep from running (#9484).+- If your computer's clock moved backwards, the update check no longer goes quiet. A saved answer stamped more than 5 minutes in the future counts as stale and is replaced, so a notice that your version was withdrawn still reaches you (#8795, also reported in #9157).+- `gbrain repair agent-session-facts` reads only the listed sources' facts when it looks up takes, so its cost follows the source instead of the whole brain.++<!-- behavior-change: frontmatter_validate_every_path -->+<!-- behavior-change: serve_http_refused_not_activity_9484 -->+<!-- behavior-change: update_cache_future_stamp_8795 -->diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 01ad522703..50883a896c 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -36,4 +36,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`), one item per source and, while the conversation archive resolves on, a last `transcript_archive` item (`runArchiveMaintenance`; its errors are a `warn` step, never a failed pass); 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. A budgeted run parks an item its budget stopped `UPKEEP_PARK_AFTER_SLICES` (30) times, in `parked` (a foreground abort never counts; skipped by budgeted runs for the rest of the round, rerun each new round, by an unbudgeted run or by `retryParked`, a serve's first idle run; `readUpkeepStatus` state `parked` warns); test `test/maintenance-park-gbra438.test.ts`. The embedding step runs under `maintenance.embed_daily_usd` (default $1 per UTC day, 0 = off; spend in `maintenance.embed_spend`), one runner at a time (`MAINTENANCE_EMBED_LOCK_ID`; a busy lock skips it as `embed_running`). 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).-- `src/core/maintenance/idle.ts` + `src/commands/maintain-schedule.ts` — GBRA-438 PR 2, the upkeep runners. `runIdleUpkeep` runs `runUnattendedMaintenance` as runner `serve` with `IDLE_UPKEEP_BUDGET_MS` (3 s) when upkeep is on and due (`upkeepDue`); the stdio serve calls it from its idle tick after the sweep, in the same in-flight slot, and stdin data, `onForegroundRequest` or shutdown aborts it. `armIdleUpkeep` is the HTTP serve's idle timer: `mcpForegroundMiddleware` (in `src/core/foreground-activity.ts`, mounted on `/mcp` by `serve-http.ts`) marks each `/mcp` POST foreground, the first tick only opens the window, one run at a time. A finished round on PGLite ends with a `CHECKPOINT` step. `maintain-schedule.ts` is routed engine-free from `src/cli/main.ts`: `--schedule` (consent `persistent_install`, `--dry-run` preview) writes a wrapper and a launchd plist, systemd user service and timer, or a `# gbrain-maintain` crontab line (pure renderers, every 6 hours); Windows and containers refuse `schedule_unsupported`; `--unschedule` removes it. A scheduled `--unattended --runner schedule` run exits 0 `maintenance_owned_by_serve` while a live serve holds the brain (PGLite lock holder, or the CLI socket on Postgres). Tests: `test/serve-idle-upkeep-gbra438.test.ts`, `test/maintenance-idle-gbra438.test.ts` (both engines, two serves on one brain), `test/maintain-schedule-gbra438.test.ts`, `test/e2e/serve-idle-upkeep-keyless-pglite.test.ts`. The cycle hands its signal to the repo-less stale link drain (`extractStaleFromDB` `signal`), so a slice stops between 25-page batches, and `runExtractFacts` yields a macrotask every 50 pages of its walk, so a timer or stdin can trip the abort mid-walk on PGLite. Bench: `scripts/bench/serve-upkeep-latency.ts` (tool-call latency during idle upkeep on a keyless repo-less PGLite brain, against a sweep-only baseline).+- `src/core/maintenance/idle.ts` + `src/commands/maintain-schedule.ts` — GBRA-438 PR 2, the upkeep runners. `runIdleUpkeep` runs `runUnattendedMaintenance` as runner `serve` with `IDLE_UPKEEP_BUDGET_MS` (3 s) when upkeep is on and due (`upkeepDue`); the stdio serve calls it from its idle tick after the sweep, in the same in-flight slot, and stdin data, `onForegroundRequest` or shutdown aborts it. `armIdleUpkeep` is the HTTP serve's idle timer: `mcpForegroundMiddleware` (in `src/core/foreground-activity.ts`, mounted on POST `/mcp` after the bearer check by `serve-http-mcp.ts`) marks each authenticated `/mcp` POST foreground, so a 401 never counts (#9484), the first tick only opens the window, one run at a time. A finished round on PGLite ends with a `CHECKPOINT` step. `maintain-schedule.ts` is routed engine-free from `src/cli/main.ts`: `--schedule` (consent `persistent_install`, `--dry-run` preview) writes a wrapper and a launchd plist, systemd user service and timer, or a `# gbrain-maintain` crontab line (pure renderers, every 6 hours); Windows and containers refuse `schedule_unsupported`; `--unschedule` removes it. A scheduled `--unattended --runner schedule` run exits 0 `maintenance_owned_by_serve` while a live serve holds the brain (PGLite lock holder, or the CLI socket on Postgres). Tests: `test/serve-idle-upkeep-gbra438.test.ts`, `test/maintenance-idle-gbra438.test.ts` (both engines, two serves on one brain), `test/maintain-schedule-gbra438.test.ts`, `test/e2e/serve-idle-upkeep-keyless-pglite.test.ts`. The cycle hands its signal to the repo-less stale link drain (`extractStaleFromDB` `signal`), so a slice stops between 25-page batches, and `runExtractFacts` yields a macrotask every 50 pages of its walk, so a timer or stdin can trip the abort mid-walk on PGLite. Bench: `scripts/bench/serve-upkeep-latency.ts` (tool-call latency during idle upkeep on a keyless repo-less PGLite brain, against a sweep-only baseline).diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 0ae7d0bb7b..f157b6d290 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`. #6157: `parseMarkdown` (`markdown.ts` `yamlBlockError`) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and `brain-writer.ts` `autoFixFrontmatter` skips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, so `validate`, `--fix`, `lint` and `repair frontmatter` never flag or rewrite valid YAML. A block (or tags/aliases line) with more than `MAX_FRONTMATTER_YAML_ALIASES` (16) aliases outside quotes counts as not parsing and is never rewritten (`yamlAliasesWithinLimit`; alias-bomb guard, `test/frontmatter-alias-bomb.test.ts`).+- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: one or more files or directories (every path is checked and each directory walked, a file named twice is checked once, a missing path refuses before anything is checked, and `--json` lists the paths as `targets` when there is more than one), `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`. #6157: `parseMarkdown` (`markdown.ts` `yamlBlockError`) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and `brain-writer.ts` `autoFixFrontmatter` skips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, so `validate`, `--fix`, `lint` and `repair frontmatter` never flag or rewrite valid YAML. A block (or tags/aliases line) with more than `MAX_FRONTMATTER_YAML_ALIASES` (16) aliases outside quotes counts as not parsing and is never rewritten (`yamlAliasesWithinLimit`; alias-bomb guard, `test/frontmatter-alias-bomb.test.ts`).- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex 9206728885..0279c62ead 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -10,10 +10,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; `runTakesRebuild` (W9F item 8) is `gbrain takes rebuild`'s parser and renderer, running `takes_rebuild` through a resident owner or the local engine (thin clients refused); queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.-- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `archive run|backfill|status|adopt-legacy|on|off` dispatches to `src/commands/transcripts-archive.ts` (core `src/core/transcripts/archive.ts`, see core-services-3; no MCP operation). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout, `session_meta` payload.source.subagent, has no user turn by design: the adapter reports `subagentRollout`, the scan counts it in `subagentRollouts` and prints `N sub-agent rollouts (no user turns by design)`, and it keeps the scan clean; an ordinary assistant-only rollout is still `userTurnsMissing` drift); no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1; a pass that stopped at its budget reports `facts.budgetExhausted` and `facts.budgetReason`, and pages skipped as too large or held by another run count in `facts.pagesSkippedTooLarge` and `facts.pagesLockSkipped` (#8722). Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.+- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `archive run|backfill|status|adopt-legacy|on|off` dispatches to `src/commands/transcripts-archive.ts` (human `status` adds a line naming `gbrain transcripts archive run` when the archive is on and `maintenance.auto` is false; `--json` is unchanged) (core `src/core/transcripts/archive.ts`, see core-services-3; no MCP operation). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout, `session_meta` payload.source.subagent, has no user turn by design: the adapter reports `subagentRollout`, the scan counts it in `subagentRollouts` and prints `N sub-agent rollouts (no user turns by design)`, and it keeps the scan clean; an ordinary assistant-only rollout is still `userTurnsMissing` drift); no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1; a pass that stopped at its budget reports `facts.budgetExhausted` and `facts.budgetReason`, and pages skipped as too large or held by another run count in `facts.pagesSkippedTooLarge` and `facts.pagesLockSkipped` (#8722). Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.- `src/commands/upgrade.ts` — self-update CLI. The package has no postinstall, so the install step runs no migrations; post-upgrade owns them (`GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` is still set for the install step). An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Install methods are bun, bun-link and binary (a compiled binary is found by Bun's `/$bunfs/` entrypoint, so a release asset keeps its published name); anything else is `unknown` and prints manual steps. It never runs `clawhub update gbrain`, which would install whatever skill anyone publishes under that name (#8464; `test/upgrade.serial.test.ts`). Before the swap of a bun-link or package install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: `--channel stable|alpha` (`latest` is an alias of `alpha`; resolution order in the Release channels entry below): `resolveStableRelease` maps the commit `refs/tags/stable` peels to onto its `v<version>` tag through `git ls-remote`, and `installStableRelease` installs exactly that release (bun: remove then add `#v<version>`, restoring the previous release on failure; bun-link: fast-forward only; binary: `fetchReleaseByTag`), never downgrading. Before the swap `preflightHostRestart` refuses (`restart_refused`, exit 3) when a running process could not be restarted; after post-upgrade the new build runs `gbrain upgrade --restart-only` (`--no-restart` skips it). Tests: `upgrade-stable-channel.test.ts`. A global install pinned to a tag or commit (`bunGlobalExactTagPin(root, true)`) is replaced with the newest published release the same way instead of `bun update`, which keeps the pin. `parseChannelArg` and `resolveStableRelease` live in `src/core/stable-channel.ts` (re-exported).-- Release channels: `src/core/self-upgrade.ts` resolves the channel (`resolveReleaseChannel`: `--channel`, `GBRAIN_RELEASE_CHANNEL`, `self_upgrade.channel`, default `stable`; `latest` normalizes to `alpha`; an invalid value at the first present source is an error) and keeps the update cache (`update-check.<channel>.json`, tagged with the evidence policy; an older answer never overwrites a newer one) and the time-based snooze (`update-snoozed.<channel>.json`) per channel; `offeredVersion` never offers a downgrade except to move off a `known_bad` version. `src/core/stable-channel.ts` reads and strictly parses the evidence record (`stable.json` on `stable-record`; `requiredEvidenceKeys`: `soak_run`, plus `matrix_run` from `MATRIX_REQUIRED_FROM`), maps failures to `stable_missing` / `stable_invalid` / `stable_unreadable` with sanitized causes, and `resolveStableRelease` checks the `stable` and `v<version>` tags against the record commit. `src/commands/upgrade-channel.ts` plans an upgrade's target (`channelTarget`, `runUpgradeDryRun` for `gbrain upgrade --dry-run --json`) and refuses with the typed code. `src/commands/check-update.ts` `refreshUpdateCache` never reads a bare VERSION for stable and never falls back to alpha. `src/core/release-channel-notice.ts` prints the one-time `[gbrain notice release_channel]` line on stderr (marker file under `notices/`; not under `--json`, `serve` or `mcp`; only when no channel is set). `src/core/install-ref.ts` is the one ref every install surface names, linted by `scripts/check-install-ref.ts`. Tests: `test/release-channel-w1.serial.test.ts`, `test/upgrade-stable-channel.test.ts`, `test/install-ref.test.ts`. Docs: `docs/guides/upgrades-auto-update.md#stable-channel`.+- Release channels: `src/core/self-upgrade.ts` resolves the channel (`resolveReleaseChannel`: `--channel`, `GBRAIN_RELEASE_CHANNEL`, `self_upgrade.channel`, default `stable`; `latest` normalizes to `alpha`; an invalid value at the first present source is an error) and keeps the update cache (`update-check.<channel>.json`, tagged with the evidence policy; an older answer never overwrites a newer one, unless the stored check time is more than 5 minutes ahead of the clock, and a cache file dated more than 5 minutes ahead is stale, so a clock that moved back never freezes the cache (#8795)) and the time-based snooze (`update-snoozed.<channel>.json`) per channel; `offeredVersion` never offers a downgrade except to move off a `known_bad` version. `src/core/stable-channel.ts` reads and strictly parses the evidence record (`stable.json` on `stable-record`; `requiredEvidenceKeys`: `soak_run`, plus `matrix_run` from `MATRIX_REQUIRED_FROM`), maps failures to `stable_missing` / `stable_invalid` / `stable_unreadable` with sanitized causes, and `resolveStableRelease` checks the `stable` and `v<version>` tags against the record commit. `src/commands/upgrade-channel.ts` plans an upgrade's target (`channelTarget`, `runUpgradeDryRun` for `gbrain upgrade --dry-run --json`) and refuses with the typed code. `src/commands/check-update.ts` `refreshUpdateCache` never reads a bare VERSION for stable and never falls back to alpha. `src/core/release-channel-notice.ts` prints the one-time `[gbrain notice release_channel]` line on stderr (marker file under `notices/`; not under `--json`, `serve` or `mcp`; only when no channel is set). `src/core/install-ref.ts` is the one ref every install surface names, linted by `scripts/check-install-ref.ts`. Tests: `test/release-channel-w1.serial.test.ts`, `test/upgrade-stable-channel.test.ts`, `test/install-ref.test.ts`. Docs: `docs/guides/upgrades-auto-update.md#stable-channel`.- `src/commands/upgrade-restart.ts` — GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry, `ps -U <uid> -ww -o pid=,ppid=,etime=,command=` with `/proc/<pid>/environ` GBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (`hostServices`: `systemctl --user show -p MainPID`, `launchctl list`), `terminateIfUnchanged` (SIGTERM an MCP pid only while `ps` still shows the same server and start time), `restartRefusal` (ask_user + `--stop-mcp` when only MCP servers block, else the first manual step for the user), `preflightHostRestart` (pre-swap, every process stale) and `runHostRestart` (`gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: plan, run, verify for up to 180 s (360 s after an autopilot hand-off) with the warm-socket probe `probeCliSocket`). #7475: `restartServeAfterSelfUpgrade`, called each autopilot-daemon tick, restarts the serve the serve service runs once it is on an older build than the relaunched autopilot. It runs once per installed build (#8013: `serve-restart-attempt.json` survives autopilot relaunches), skips a serve service whose wrapper belongs to another brain (`serveServiceRunsWrapper`), runs the restart without blocking the daemon (`hostExecutor` spawns asynchronously, 120 s cap), only in auto mode, in quiet hours and when the brain is idle (`computeAutopilotIdle`), and audits as `restart_serve`. #8776: `autopilotLauncher` (this brain's gbrain cron line from `crontab -l`, else `self_upgrade.autopilot_launcher external`) feeds the planner's hand-off; `upgradeRestartReadiness` is the preflight plan from the process table alone, which doctor's `self_upgrade_health` reads (local doctor only). `planServeRestart` reports a serve the service does not run, or one on another install, as `manual` and never restarts it. A serve counts as older only on evidence (a recorded build below this one, or no recorded build and a start before the install's `package.json` was written); a newer or unknown serve, or an install on disk that is not this build, is left alone. Tests: `upgrade-restart.test.ts`, `autopilot-serve-restart-7475.test.ts`, `autopilot-serve-restart-8013.test.ts`.- `src/core/upgrade-restart.ts` — GBRA-175: the pure half of the upgrade restart. `collectHostProcesses` (the process table is the authority: a heartbeat, PID-file or registry record whose pid `ps` does not show as gbrain is dropped; `gbrainEntry` skips wrappers such as tini, `bunx`, `bun x` and `bun run <bin>`, skips interpreter flags that take a value, resolves a relative entry against the process's `/proc/<pid>/cwd` and accepts a `src/cli.ts` whose package two levels up is named gbrain (#8723); a process's parent is its nearest gbrain ancestor, and a worker with none is refused naming its parent's pid and executable, never its command line), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file, read from `--pid-file <path>`, and drops a `--flag=value` token that is neither a global flag nor `--job-isolation=`, because the supervisor that holds it ignored it and this build's `=` gate refuses it (#7619); an autopilot under no installed service gets a `handoff` step when `ctx.autopilotLauncher` is known (#8776: SIGTERM while the pid is unchanged, then the launcher must bring autopilot back), else a manual step naming `gbrain autopilot --install`; anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`. A stale process whose `install_root` is another install than the one being upgraded gets a `replace_copy` step first when it is a Bun global copy (`bunGlobalCopyOf`: probe the tag, `bun remove -g` then `bun add -g` under its `BUN_INSTALL`, restore on failure), else a manual step from `copyFix`; after the restart `mismatchedBuilds` names any process back on another build, and the host's `mismatchFix` chains that replacement with `gbrain upgrade --restart-only`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 7e490f7d38..46108a1929 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `assertSyncAnchorAbsolute` refuses `sync_anchor_relative` (`syncAnchorRelativeError`: exit 3, an `ask_user` fix naming `gbrain sources set-path <id> <absolute-directory>`, or `gbrain config set sync.repo_path` with no source) when the stored anchor (`sources.local_path`, else `sync.repo_path`) is not absolute on this host (`isHostAbsolutePath`: on win32 only a drive or UNC path) and no absolute `repoPath`, or relative one resolving elsewhere, was passed; `sync --all --json` puts the refusal's `code`, `why` and `fix` in the source's entry, and the `sync` Minion job completes as a skip carrying them; single-source and `--all` CLI syncs refuse it before the cost gate walks the directory, and a cycle whose directory matches no source checks `default` and fails its sync phase with that code. A path absolute only on another operating system (a Windows drive path read on Linux or macOS) gets the same code with a `set-path`-only fix, since `--clear` refuses it. `src/core/sync-anchor.ts` never proves ownership from a relative anchor: `isAnchorOwnedSyncPath`, `ownsSourceSyncAnchor` and `sourceCommitAnchorAllowed` treat it as not owned, and for `default` the commit-anchor check skips a relative `sync.repo_path` and judges the row's `local_path` (a null row falls back to that relative key and refuses), so an explicit absolute `--repo` never advances the commit anchor of a source whose stored path is relative. `performSync` calls `assertSyncApplicable` first (the anchor check, then the content-directory check), so a content-directory source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts` and `test/sync-relative-anchor-refusal-7630.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.- `src/core/sync-upstream-rewrite.ts` — classic sync's upstream watch for a source that syncs with pull (GBRA-133 S-58/S-59). `recordUpstreamBeforeFetch` (called by `src/commands/sync/preflight.ts` before every pull) stores in `sources.config.upstream_baseline` the upstream commit HEAD contains, only when HEAD contains it, so a rewritten upstream fetched earlier never replaces it; `settleUpstreamAfterPull` records the new baseline and clears `sources.config.upstream_divergence` after a pull that fast-forwarded or was up to date, and after a pull that failed with HEAD and `@{upstream}` diverged stores `upstream_rewritten` (baseline not an ancestor of the new upstream), `upstream_unknown` (no baseline or its object is gone) or `upstream_diverged` (baseline contained: plain local commits); nothing is classified while a rebase, merge, cherry-pick or revert marker (`GIT_OPERATION_MARKERS` in `src/core/git/commit-push.ts`) exists. Best effort: it never throws into the sync and never writes a sync-failure ledger row. `upstreamFix` is the typed next step (`ask_user` reset bound to the observed SHAs for rewritten/unknown, never a merge; `gbrain git commit-push --pull` for diverged; both `then` the sync). Read by `performSyncInner` (`result.upstream`), `buildSingleSyncJsonEnvelope`, `gbrain sources status --json` (`upstream`) and doctor `sync_failures` (`details.upstream`, warn, local fix; remote callers get counts only). Pinned by `test/pathological/s-58-upstream-rewrite.test.ts`.-- `src/core/sync-attempt.ts` + `src/commands/doctor/sync-outcome.ts` — doctor `sync_freshness` for a source with no successful sync (`last_sync_at` NULL, #4960). `readLastSyncAttempt` reads, read-only, the newest `sync` Minions job of the source and, on a managed brain, `readSyncStatus` (holds, last error, cursor, its `next`); nothing found is `no_attempt`, an unreadable read is `no_attempt` with `unreadable`. A live first-sync lock inside the staleness ceiling is `warn` (`sync_first_run_in_progress`, fix `next: wait`); no lock is `fail` (`sync_no_successful_sync`) naming last attempt, result and held count, with a per-`reason` fix (`attempt_queued` wait, `holds_pending` the managed `next` or `sync status`, `last_attempt_unsuccessful` inspect the job then retry, `no_attempt` retry). Entries land in `details.no_successful_sync[]`; these sources stay in `stale_count`. Test: `test/doctor-sync-freshness-outcome-4960.test.ts`.+- `src/core/sync-attempt.ts` + `src/commands/doctor/sync-outcome.ts` — doctor `sync_freshness` for a source with no successful sync (`last_sync_at` NULL, #4960). `readLastSyncAttempt` reads, read-only, the newest `sync` Minions job of the source and, on a managed brain, `readSyncStatus` (holds, last error, cursor, its `next`); nothing found is `no_attempt`, an unreadable read is `no_attempt` with `unreadable`. A live first-sync lock inside the staleness ceiling is `warn` (`sync_first_run_in_progress`, fix `next: wait`); no lock is `fail` (`sync_no_successful_sync`) naming last attempt, result and held count, with a per-`reason` fix (`attempt_queued` wait, `holds_pending` the managed `next` or `sync status`, `last_attempt_unsuccessful` inspect the job then retry, `no_attempt` retry; `content_directory`, a root only a content-setup receipt claims on a brain with persistence off, sync refuses: `receiptContentDirectory` names the `sync_not_applicable` import fix, test `test/doctor-sync-freshness-receipt-root.test.ts`). Entries land in `details.no_successful_sync[]`; these sources stay in `stale_count`. Test: `test/doctor-sync-freshness-outcome-4960.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth unless `SyncableOptions.metafilePage` says a nested one is a page: `metafileIsPage(path, head, mode)` is true for an `isNestedSkipMetafile` path whose closed leading frontmatter has a non-empty top-level `type:` or `title:` under `sync.metafile_pages` `typed` and no top-level `slug:` naming another page (#7341: such a file stays scaffolding instead of being held `frontmatter_slug_conflict`), the one default `DEFAULT_METAFILE_PAGES_MODE`; `off` skips every metafile; `readMetafilePagesMode` reads the key); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` adds the head of the file on disk, so a typed nested metafile page is mirrored and published like any page), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.- `src/core/sync-metafile-pages.ts` — the head readers behind `sync.metafile_pages`: `metafilePagePredicate(mode, read, rootRelative)` (memoized, the `SyncableOptions.metafilePage` every classifying caller passes), `diskMetafileHeads(root)` (regular files only, never a symlink), `gitMetafileHeads(gitRoot, commits)` (first commit that has the path; `prime` batch-reads blobs a caller already streams through one `cat-file --batch-check` plus one `--batch`), `firstMetafileHead` (disk, then the last synced blob, so a deleted file is judged as last committed), `listMetafileNamedBlobs` (one `ls-tree`), and the classic backfill marker `sync.metafile_pages.applied.<source>` (`metafileBackfillDue` / `recordMetafilePagesApplied`, written with the bookmark): a source that has not finished a sync under `typed` adds its tree's nested metafile-named files to the next delta once. Managed sync instead folds the mode into the pass selection fingerprint (`sync-pass-run.ts`; unchanged under `off`). Only metafile-named paths are ever read. `config set sync.metafile_pages` refuses a value outside `typed | off` (`src/commands/config/sync-metafile-pages-value.ts`); the restore check and doctor `missing_recorded_files` (`persistence/detached-pages.ts`) judge a recorded nested metafile with the same disk-then-last-synced predicate `sync --full` uses. Pinned by `test/sync-metafile-pages.test.ts` (classic) and `test/persistence-sync-metafile-pages.test.ts` (managed, PGLite and Postgres).diff --git a/docs/guides/conversation-archive.md b/docs/guides/conversation-archive.mdindex 0f6f6d13e2..ca95718b2f 100644--- a/docs/guides/conversation-archive.md+++ b/docs/guides/conversation-archive.md@@ -52,7 +52,7 @@ a time, never when the archive is off, and never fails the pass: its outcome, erand the next pass picks up the rest.`gbrain transcripts archive run` archives now, on demand, whatever the pass is doing; it works with automatic-maintenance turned off (`maintenance.auto false`).+maintenance turned off (`maintenance.auto false`), and `gbrain transcripts archive status` says so when it is off.`run` and `backfill` exit 1 when anything in the run failed, and 0 otherwise, even when most days were written:the days that did not make it are retried by the next run on their own, and a script or scheduler should see thatdiff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex ad6b2eabc9..c420291925 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -37,7 +37,7 @@ import { readOnlyCatalogPackSourceIds } from '../../../core/shared-skills/adopteimport { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';import { checkError } from '../check-fix.ts';-import { checkpointMovedFix, firstSyncRunning, noSuccessfulSync, stoppedConnectorIssues, type SyncOutcomeEntry } from '../sync-outcome.ts';+import { checkpointMovedFix, firstSyncRunning, noSuccessfulSync, receiptContentDirectory, stoppedConnectorIssues, type SyncOutcomeEntry } from '../sync-outcome.ts';import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */@@ -1213,7 +1213,7 @@ export async function checkSyncFreshness(// #6076: an adopted read-only catalog pack (no commit history) has nothing to sync.const catalogPacks = await readOnlyCatalogPackSourceIds(engine, sources, localOnly);let writer_owned_count = 0, read_only_pack_count = 0;- // #9471: roots inside gbrain's own content directory, which sync refuses (a receipt-claimed root stays writer-owned above).+ // #9471: roots inside gbrain's own content directory, which sync refuses (a receipt-claimed root is writer-owned above while persistence is on, else fails naming the import).const contentDirectories: Array<{ id: string; keyless: boolean }> = [];// v0.41.27.0: D6 count math. Every source falls into// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:@@ -1329,7 +1329,7 @@ export async function checkSyncFreshness(const stopped = stoppedConnectors.get(source.id);if (stopped) { issues.push(stopped.issue); stale_count++; hasFailures ||= stopped.fail; hasWarnings ||= !stopped.fail; continue; }if (!source.last_sync_at) {- const never = await noSuccessfulSync(engine, source.id, display, managed);+ const never = contentDirectory ? receiptContentDirectory(contentDirectory, display) : await noSuccessfulSync(engine, source.id, display, managed);issues.push(never.issue); outcomes.push(never.entry);hasFailures = true;stale_count++;diff --git a/src/commands/doctor/sync-outcome.ts b/src/commands/doctor/sync-outcome.tsindex 8e9e936684..d9b4018e72 100644--- a/src/commands/doctor/sync-outcome.ts+++ b/src/commands/doctor/sync-outcome.ts@@ -10,12 +10,13 @@ import type { BrainEngine } from '../../core/engine.ts';import { readLastSyncAttempt, type SyncAttemptState } from '../../core/sync-attempt.ts';import { classifyManagedSyncOrphans } from '../../core/persistence/managed-sync-orphans.ts';import { isOwnedContentSchemaMissing, staleOwnedContent } from '../../core/shared-skills/content-freshness.ts';+import { syncNotApplicableError, type SyncContentDirectory } from '../../core/sync-applicability.ts';import { agentFix, doctorVerify } from './check-fix.ts';export interface SyncOutcomeEntry {source_id: string;code: 'sync_first_run_in_progress' | 'sync_no_successful_sync' | 'content_receipt_stale';- reason: 'first_sync_running' | 'receipt_root_moved' | SyncAttemptState;+ reason: 'first_sync_running' | 'receipt_root_moved' | 'content_directory' | SyncAttemptState;last_attempt_at: string | null;result: string | null;held: number;@@ -66,6 +67,19 @@ export async function noSuccessfulSync(engine: BrainEngine, sourceId: string, di};}+/**+ * A content directory only its content-setup receipt claims (an owned root outside gbrain's own content directory) is+ * writer-owned only while persistence is on; otherwise it still has no successful sync, but sync refuses it+ * (`sync_not_applicable`), so the step named is the import that refusal names.+ */+export function receiptContentDirectory(dir: SyncContentDirectory, display: string): { issue: string; entry: SyncOutcomeEntry } {+ const fix = syncNotApplicableError(dir).fix!;+ return {+ issue: `Source ${display}: no successful sync recorded; its content-setup receipt makes it a gbrain-owned content directory, where sync does not apply; add files with \`${fix.argv!.join(' ')}\``,+ entry: { source_id: dir.sourceId, code: 'sync_no_successful_sync', reason: 'content_directory', last_attempt_at: null, result: null, held: 0, job_id: null, fix },+ };+}+/*** C-7 (#6892): a gbrain-owned content source never syncs, and doctor exempts it only while its content receipt names* the source's root. A receipt left on an old root (a transfer or relocation, or a set-path still to run) isdiff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.tsindex c7624cff86..9654cf25fe 100644--- a/src/commands/frontmatter.ts+++ b/src/commands/frontmatter.ts@@ -3,7 +3,7 @@ import { assertManagedFilesystemWrite, managedFilesystemRootFor } from '../core/* gbrain frontmatter — Frontmatter validation, audit, and auto-repair.** Subcommands:- * gbrain frontmatter validate <path> [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]+ * gbrain frontmatter validate <path>... [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]* gbrain frontmatter validate --stdin|- [--path <source-relative path>] [--importable] [--json]* gbrain frontmatter validate --staged [<path>...] [--importable] [--json]* Validate one file, a directory, piped content, or staged git blobs.@@ -103,7 +103,7 @@ function printHelp() {console.log(`gbrain frontmatter — frontmatter validation, audit, auto-repair, and generationUsage:- gbrain frontmatter validate <path> [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]+ gbrain frontmatter validate <path>... [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]gbrain frontmatter validate --stdin [--path <source-relative path>] [--importable] [--json]gbrain frontmatter validate --staged [<path>...] [--importable] [--json]gbrain frontmatter generate <path> [--fix] [--dry-run] [--json] [--include-catch-all]@@ -375,6 +375,7 @@ async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {const results: FileValidation[] = [];let scanned = 0;let targetLabel: string;+ let targetList: string[] | undefined;let slugCheckSkipped = false;const fixedInGit: string[] = [];@@ -416,27 +417,29 @@ async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {results.push(result);}} else {- const target = targets[targets.length - 1];- if (!target) {+ if (targets.length === 0) {usage('gbrain frontmatter validate requires a <path> argument (or --stdin, or --staged)');return;}- const resolved = resolve(target);- if (!existsSync(resolved)) {- usage(`path not found: ${target}`);- return;- }- if (lstatSync(resolved).isFile() && !isMarkdownFilePath(resolved)) {- usage(`frontmatter validation supports only .md and .mdx files: ${target}`);- return;+ const roots: Array<{ resolved: string; files: string[] }> = [];+ const seen = new Set<string>();+ for (const target of targets) {+ const resolved = resolve(target);+ if (!existsSync(resolved)) {+ usage(`path not found: ${target}`);+ return;+ }+ if (lstatSync(resolved).isFile() && !isMarkdownFilePath(resolved)) {+ usage(`frontmatter validation supports only .md and .mdx files: ${target}`);+ return;+ }+ roots.push({ resolved, files: collectFiles(resolved).filter(f => !seen.has(f) && !!seen.add(f)) });}- targetLabel = resolved;+ targetLabel = roots[0]!.resolved;+ if (roots.length > 1) targetList = roots.map(r => r.resolved);- const brainRoot = findBrainRoot(resolved);- const inGit = existsSync(join(brainRoot, '.git'));- const files = collectFiles(resolved);if (flags.fix && !flags.dryRun) {- for (const file of files) {+ for (const file of roots.flatMap(r => r.files)) {try {assertManagedFilesystemWrite(file);} catch (error) {@@ -446,36 +449,40 @@ async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {}}const backupRunId = makeFrontmatterBackupRunId();- scanned = files.length;-- for (const file of files) {- const content = readFileSync(file, 'utf8');- const rel = relative(brainRoot, file);- // Files above/outside the brain root fall back to basename rather than- // emitting a "../"-prefixed slug for non-brain files.- const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);- const check = checkContent(content, slugPath, flags.importable);- const result = toResult(file, check);- const rescuable = flags.includeAmbiguous && check.warnings.some(w => w.code === 'FRONTMATTER_COMMENT_VALUE');-- if (flags.fix && (check.errors.length > 0 || rescuable)) {- // #5053: the fixer derives the slug from the same path validate used;- // the absolute path re-keyed every declared slug as a mismatch.- const auto = autoFixFrontmatter(content, { filePath: slugPath });- const repaired = repairRecoverableFrontmatter(auto.content, { includeAmbiguous: flags.includeAmbiguous });- result.fixesApplied = [...auto.fixes, ...repaired.fixes];- if (result.fixesApplied.length > 0 && !flags.dryRun) {- assertManagedFilesystemWrite(file);- result.backupPath = createFrontmatterBackup(file, { sourcePath: resolved, runId: backupRunId });- writeFileSync(file, repaired.content, 'utf8');- if (inGit) fixedInGit.push(relative(brainRoot, file));+ scanned = seen.size;++ for (const { resolved, files } of roots) {+ const brainRoot = findBrainRoot(resolved);+ const inGit = existsSync(join(brainRoot, '.git'));+ for (const file of files) {+ const content = readFileSync(file, 'utf8');+ const rel = relative(brainRoot, file);+ // Files above/outside the brain root fall back to basename rather than+ // emitting a "../"-prefixed slug for non-brain files.+ const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);+ const check = checkContent(content, slugPath, flags.importable);+ const result = toResult(file, check);+ const rescuable = flags.includeAmbiguous && check.warnings.some(w => w.code === 'FRONTMATTER_COMMENT_VALUE');++ if (flags.fix && (check.errors.length > 0 || rescuable)) {+ // #5053: the fixer derives the slug from the same path validate used;+ // the absolute path re-keyed every declared slug as a mismatch.+ const auto = autoFixFrontmatter(content, { filePath: slugPath });+ const repaired = repairRecoverableFrontmatter(auto.content, { includeAmbiguous: flags.includeAmbiguous });+ result.fixesApplied = [...auto.fixes, ...repaired.fixes];+ if (result.fixesApplied.length > 0 && !flags.dryRun) {+ assertManagedFilesystemWrite(file);+ result.backupPath = createFrontmatterBackup(file, { sourcePath: resolved, runId: backupRunId });+ writeFileSync(file, repaired.content, 'utf8');+ if (inGit) fixedInGit.push(relative(brainRoot, file));+ }+ const after = result.fixesApplied.length > 0 ? checkContent(repaired.content, slugPath, flags.importable) : check;+ result.remaining_errors = after.errors;+ if (flags.importable) result.remaining_hold = after.hold;+ result.failed = after.failed;}- const after = result.fixesApplied.length > 0 ? checkContent(repaired.content, slugPath, flags.importable) : check;- result.remaining_errors = after.errors;- if (flags.importable) result.remaining_hold = after.hold;- result.failed = after.failed;+ results.push(result);}- results.push(result);}}@@ -489,6 +496,7 @@ async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {ok: failed.length === 0,mode: flags.importable ? 'importable' : 'strict',target: targetLabel,+ ...(targetList ? { targets: targetList } : {}),...(flags.stdin ? { stdin: true, slug_check: slugCheckSkipped ? 'skipped' : 'checked' } : {}),...(flags.staged ? { staged: true } : {}),total_files: scanned,diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 69c5c6cf2b..ee4ec856e0 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -61,6 +61,7 @@ import { VERSION } from '../version.ts';import { executeRawJsonb } from '../core/sql-query.ts';import { withRequestConfigSnapshot } from '../core/config-snapshot.ts';import { withBearerScopeHint } from './serve-http-oauth.ts';+import { mcpForegroundMiddleware } from '../core/foreground-activity.ts';import type { ServeHttpContext } from './serve-http.ts';/** Per-request state shared by the tools/list and tools/call handlers of one POST /mcp. */@@ -162,7 +163,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {req => createHash('sha256').update(((req as any).auth as AuthInfo).token).digest('hex'), 'Too many requests for this token');app.post('/mcp', ipLimit, withBearerScopeHint(requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read', 'write'],- ), tokenLimit, (req: Request, res: Response) => withEngineScope(engine, () => withRequestConfigSnapshot(engine, () => handleMcpPost(req, res))));+ ), mcpForegroundMiddleware, tokenLimit, (req: Request, res: Response) => withEngineScope(engine, () => withRequestConfigSnapshot(engine, () => handleMcpPost(req, res))));// #6721: one config snapshot serves every config read of one POST /mcp (the// surface, row-shape and writeback reads below, tools/list and a read op'sdiff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex a72f521475..af27d02253 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -55,7 +55,6 @@ import { VERSION } from '../version.ts';import { NoticeLedger } from '../core/notice-ledger.ts';import { createReadinessCache, type ReadinessCache } from '../core/readiness.ts';import { withLocalScope } from '../core/engine-scope-store.ts';-import { mcpForegroundMiddleware } from '../core/foreground-activity.ts';export { extractGitHubItemRef, githubKindCoversRepo, selectGitHubItemSources } from './serve-http-webhooks.ts';export { HEALTH_TIMEOUT_MS, probeHealth, probeLiveness, type ProbeHealthResult } from './serve-http-metrics.ts';@@ -773,7 +772,6 @@ export async function buildServeHttpApp(app: express.Express, engine: BrainEngin// below requireAdmin's definition.const metricsCounters = createMetricsCounters();app.use(metricsTrackingMiddleware(metricsCounters));- app.use('/mcp', mcpForegroundMiddleware);const oauthTokenRateLimit = resolveOAuthTokenRateLimit();const ccRateLimiter = rateLimit({diff --git a/src/commands/transcripts-archive.ts b/src/commands/transcripts-archive.tsindex f38a884f93..d1462b7b02 100644--- a/src/commands/transcripts-archive.ts+++ b/src/commands/transcripts-archive.ts@@ -56,6 +56,7 @@ export async function runTranscriptsArchive(engine: BrainEngine, args: string[],if (sub === 'status') {const status = await archive.archiveStatus(engine, { sourceId });+ const upkeepOff = !json && status.enabled && !await (await import('../core/maintenance/run.ts')).upkeepEnabled(engine);out(status, () => {console.log('conversation archive: ' + (status.enabled ? 'on' : 'off') + ' (source: ' + status.source_id + ', timezone: ' + (status.timezone ?? status.configured_timezone + ', pinned at the first run') + ')');for (const h of status.harnesses) {@@ -66,6 +67,7 @@ export async function runTranscriptsArchive(engine: BrainEngine, args: string[],for (const h of status.held) console.log(' held: ' + h.harness + ' ' + h.day + ' (' + h.code + ')');for (const e of status.errors) console.log(' error on the last run' + (e.at ? ' (' + e.at + ')' : '') + ': ' + e.reader + ' ' + e.code + ': ' + e.message);if (status.rescope) console.log(' not kept to the owner yet (' + status.rescope.code + '): ' + status.rescope.message);+ if (upkeepOff) console.log(' maintenance.auto is false, so free upkeep does not archive by itself (an installed autopilot still does); archive now with "gbrain transcripts archive run"');});if (status.errors.length) setCliExitVerdict(1);return;diff --git a/src/core/foreground-activity.ts b/src/core/foreground-activity.tsindex 5c414af901..e8aada2ec4 100644--- a/src/core/foreground-activity.ts+++ b/src/core/foreground-activity.ts@@ -47,7 +47,8 @@ export function _resetForegroundActivityForTests(): void {/*** GBRA-438: the HTTP serve's /mcp middleware. A POST is foreground activity, so idle upkeep waits for a quiet window- * and a request aborts a run in flight; GET /mcp (a long-lived event stream) does not count.+ * and a request aborts a run in flight; GET /mcp (a long-lived event stream) does not count. #9484: mounted after the+ * bearer check on POST /mcp, so a request refused there (401) never counts and cannot hold upkeep off.*/export function mcpForegroundMiddleware(req: { method: string }, res: { once(event: 'finish' | 'close', fn: () => void): unknown }, next: () => void): void {if (req.method === 'POST') {diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.tsindex b714822eab..79c9d63250 100644--- a/src/core/repair/agent-session-facts.ts+++ b/src/core/repair/agent-session-facts.ts@@ -307,8 +307,9 @@ export async function classifyAgentSessionFacts(db: BrainEngine, sourceIds: stri/*** Active, unresolved `kind: fact` / `holder: self` takes whose every contributing fact is non-user once the facts in* `reattributed` are: at least one of them must be in that set or already carry a speaker note, so takes this repair- * has nothing to do with are never listed. Contributing facts are grouped in one pass over the facts table, never one- * pass per take (#9503).+ * has nothing to do with are never listed. Contributing facts are grouped in one pass over the listed sources' facts,+ * never one pass per take (#9503) and never over other sources: consolidation only links a fact to a take on a page of+ * the fact's own source.*/export async function agentSessionTakes(db: BrainEngine, sourceIds: string[], reattributed: ReadonlySet<number>, ids?: number[]): Promise<AgentSessionTake[]> {const rows = await db.executeRaw<{ id: number | string; source_id: string; slug: string; row_num: number | string; claim: string;@@ -319,7 +320,7 @@ export async function agentSessionTakes(db: BrainEngine, sourceIds: string[], reCOALESCE(bool_or(f.attributed_to='other' AND position($3::text in COALESCE(f.context,''))>0), false) AS noted,min(f.consolidated_at) AS first_consolidated_atFROM facts f- WHERE f.consolidated_into IS NOT NULL AND ($2::bigint[] IS NULL OR f.consolidated_into=ANY($2::bigint[]))+ WHERE f.source_id=ANY($1::text[]) AND f.consolidated_into IS NOT NULL AND ($2::bigint[] IS NULL OR f.consolidated_into=ANY($2::bigint[]))GROUP BY f.consolidated_into)SELECT t.id, p.source_id, p.slug, t.row_num, t.claim, c.fact_ids, c.user_fact_ids, c.notedFROM contributing c JOIN takes t ON t.id=c.take_id JOIN pages p ON p.id=t.page_iddiff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex 757456aaa3..691a3c47e3 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -421,6 +421,8 @@ export interface CacheWriteOptions {}const STABLE_CODES = new Set(['stable_missing', 'stable_invalid', 'stable_unreadable']);+/** How far ahead of this clock a stored check time may be (NTP skew); further ahead means the clock moved back since the write, so it is ignored (#8795). The file's mtime is not checked: a network home's file server sets it by its own clock. */+const CACHE_FUTURE_SKEW_MS = 5 * 60 * 1000;let _tmpCounter = 0;function atomicWrite(path: string, content: string): void {@@ -476,13 +478,15 @@ export function readUpdateCache(channel: ReleaseChannel | null = currentReleaseC/*** Atomically write one channel's cache (0600). A refresh that started before the stored answer's refresh never- * overwrites it (reversed completion). Best-effort: throws only on truly unexpected fs errors.+ * overwrites it (reversed completion), unless the stored check time is more than CACHE_FUTURE_SKEW_MS ahead of this clock.+ * Best-effort: throws only on truly unexpected fs errors.*/export function writeUpdateCache(marker: UpdateMarker | null, opts: CacheWriteOptions = {}): void {const channel = opts.channel ?? currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL;- const checkedAt = opts.checkedAt ?? Date.now();+ const now = Date.now();+ const checkedAt = opts.checkedAt ?? now;const prior = readUpdateCache(channel);- if (prior && prior.checkedAt > checkedAt) return;+ if (prior && prior.checkedAt > checkedAt && prior.checkedAt <= now + CACHE_FUTURE_SKEW_MS) return;atomicWrite(updateCachePath(channel), JSON.stringify({schema: 2,channel,@@ -504,7 +508,7 @@ export function clearUpdateCache(): void {export function isCacheFresh(entry: CacheEntry, now: number): boolean {const ttl = entry.marker?.kind === 'upgrade_available' && !entry.error ? CACHE_TTL_UPGRADE_AVAILABLE_MS : CACHE_TTL_UP_TO_DATE_MS;- return now - entry.mtimeMs < ttl;+ return entry.checkedAt <= now + CACHE_FUTURE_SKEW_MS && now - entry.mtimeMs < ttl;}/**diff --git a/test/doctor-sync-freshness-receipt-root.test.ts b/test/doctor-sync-freshness-receipt-root.test.tsnew file mode 100644index 0000000000..aa43722572--- /dev/null+++ b/test/doctor-sync-freshness-receipt-root.test.ts@@ -0,0 +1,69 @@+/**+ * A source whose root a content-setup receipt claims (an owned `--content-root` outside gbrain's own content+ * directory) on a brain whose persistence is off: the writer-owned exemption needs persistence on, and #9471's+ * content-directory exemption covers only roots inside gbrain's own content directory, so sync_freshness still fails+ * it (the graduation verify step relies on that fail). Sync refuses the source with `sync_not_applicable`, so the+ * advice names the import that refusal names instead of a `gbrain sync` that cannot run, and that import is accepted.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';+import { runImport } from '../src/commands/import.ts';+import { assertSyncApplicable } from '../src/core/sync-applicability.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { contentSetupKey } from '../src/core/shared-skills/setup.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ home = mkdtempSync(join(tmpdir(), 'gbrain-receipt-root-'));+});++test('a receipt-claimed root on a persistence-off brain still fails, names the import, and that import runs', () => withEnv({ GBRAIN_HOME: home }, async () => {+ const sourceId = 'notes-example', root = join(home, 'content-root-example');+ mkdirSync(root);+ await engine.setConfig('embedding_disabled', 'true');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ const binding = await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');+ await engine.setConfig(contentSetupKey(sourceId, binding.source_incarnation), JSON.stringify({ version: 1, brain_id: brain!.brain_id,+ source_id: sourceId, source_incarnation: binding.source_incarnation, root, owned_root: true, repository_kind: 'content_directory', status: 'ready', stage: 'complete' }));++ const refusal = await assertSyncApplicable(engine, { sourceId }).then(() => null, (error: unknown) => error instanceof OperationError ? error.code : String(error));+ expect(refusal).toBe('sync_not_applicable');++ for (const localOnly of [true, false]) {+ const check = await checkSyncFreshness(engine, { localOnly, sourceIds: [sourceId] });+ expect(check.status).toBe('fail');+ expect(check.message).toContain(`'${sourceId}': no successful sync recorded`);+ expect(check.message).not.toContain('gbrain sync');+ expect(check.message).toContain(`gbrain import <dir> --no-embed --source ${sourceId}`);+ expect(check.fix?.argv).toEqual(['gbrain', 'import', '<dir>', '--no-embed', '--source', sourceId]);+ }++ const check = await checkSyncFreshness(engine, { localOnly: true, sourceIds: [sourceId] });+ const notes = join(home, 'markdown-example');+ mkdirSync(notes);+ writeFileSync(join(notes, 'alice-example.md'), '---\ntitle: Alice Example\n---\nA note about acme-example.\n');+ const result = await runImport(engine, check.fix!.argv!.slice(2).map(arg => arg === '<dir>' ? notes : arg));+ expect(result).toMatchObject({ imported: 1, errors: 0, failures: [] });+ const [page] = await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM pages WHERE slug=$1', ['alice-example']);+ expect(page?.source_id).toBe(sourceId);+}), 120_000);diff --git a/test/fixtures/goldens/serve-http/routes-runtime.json b/test/fixtures/goldens/serve-http/routes-runtime.jsonindex d579b10503..d5209d2ee4 100644--- a/test/fixtures/goldens/serve-http/routes-runtime.json+++ b/test/fixtures/goldens/serve-http/routes-runtime.json@@ -25,13 +25,6 @@"method": "use","path": null},- {- "handlers": [- "mcpForegroundMiddleware"- ],- "method": "use",- "path": "/mcp"- },{"handlers": ["corsMiddleware"@@ -734,6 +727,7 @@"handlers": ["<anonymous>","<anonymous>",+ "mcpForegroundMiddleware","<anonymous>","<anonymous>"],@@ -782,13 +776,6 @@"method": "use","path": null},- {- "handlers": [- "mcpForegroundMiddleware"- ],- "method": "use",- "path": "/mcp"- },{"handlers": ["corsMiddleware"@@ -1535,6 +1522,7 @@"handlers": ["<anonymous>","<anonymous>",+ "mcpForegroundMiddleware","<anonymous>","<anonymous>"],diff --git a/test/fixtures/goldens/serve-http/routes.json b/test/fixtures/goldens/serve-http/routes.jsonindex 125019c20b..e81922761e 100644--- a/test/fixtures/goldens/serve-http/routes.json+++ b/test/fixtures/goldens/serve-http/routes.json@@ -32,14 +32,6 @@"path": null,"when": []},- {- "handlers": [- "mcpForegroundMiddleware"- ],- "method": "use",- "path": "/mcp",- "when": []- },{"handlers": ["cors(corsOAuthOptions)"@@ -609,6 +601,7 @@"handlers": ["ipLimit","withBearerScopeHint(requireBearerAuth({ verifier : resourceVerifier , resourceMetadataUrl }), [ 'read' , 'write' ])",+ "mcpForegroundMiddleware","tokenLimit","<inline>"],diff --git a/test/frontmatter-validate-many-paths.test.ts b/test/frontmatter-validate-many-paths.test.tsnew file mode 100644index 0000000000..c394b57377--- /dev/null+++ b/test/frontmatter-validate-many-paths.test.ts@@ -0,0 +1,68 @@+import { afterEach, beforeEach, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++import { runFrontmatter } from '../src/commands/frontmatter.ts';+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';++let tmp: string;+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'fm-many-')); });+afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });++interface Report { ok: boolean; total_files: number; targets?: string[]; results: Array<{ path: string; failed: boolean }> }++async function validate(args: string[]): Promise<{ json: Report | null; verdict: number }> {+ const logOrig = console.log;+ const errOrig = console.error;+ const prevExitCode = process.exitCode;+ const out: string[] = [];+ _resetCliExitVerdictForTests();+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };+ console.error = () => {};+ try {+ await runFrontmatter(['validate', ...args, '--json']);+ } finally {+ console.log = logOrig;+ console.error = errOrig;+ }+ const verdict = currentExitCode();+ _resetCliExitVerdictForTests();+ process.exitCode = prevExitCode ?? 0;+ return { json: out.length ? JSON.parse(out.join('\n')) as Report : null, verdict };+}++function files() {+ mkdirSync(join(tmp, 'a'));+ mkdirSync(join(tmp, 'b'));+ const good = join(tmp, 'a', 'good.md');+ const bad = join(tmp, 'b', 'bad.md');+ writeFileSync(good, '---\ntitle: Good\n---\nbody\n');+ writeFileSync(bad, '---\ntitle: [unclosed\n---\nbody\n');+ return { good, bad };+}++test('a bad file named before a good one fails the run instead of reporting ok', async () => {+ const { good, bad } = files();+ const { json, verdict } = await validate([bad, good]);+ expect(json!.ok).toBe(false);+ expect(verdict).toBe(1);+ expect(json!.total_files).toBe(2);+ expect(json!.targets).toEqual([bad, good]);+ expect(json!.results.map(r => [r.path, r.failed])).toEqual([[bad, true], [good, false]]);+});++test('every directory named is walked, and a file named twice is checked once', async () => {+ const { good, bad } = files();+ const { json, verdict } = await validate([join(tmp, 'b'), join(tmp, 'a'), good]);+ expect(verdict).toBe(1);+ expect(json!.total_files).toBe(2);+ expect(json!.results.map(r => r.path).sort()).toEqual([bad, good].sort());+});++test('a missing path anywhere in the list refuses before anything is checked', async () => {+ const { good } = files();+ const { json, verdict } = await validate([good, join(tmp, 'missing.md')]);+ expect(verdict).toBe(1);+ expect(json).toBeNull();+});diff --git a/test/release-channel-w1.serial.test.ts b/test/release-channel-w1.serial.test.tsindex c6674b1b19..6a6908400f 100644--- a/test/release-channel-w1.serial.test.ts+++ b/test/release-channel-w1.serial.test.ts@@ -11,7 +11,7 @@* Serial: stubs globalThis.fetch and process-global env.*/import { afterEach, beforeEach, describe, expect, test } from 'bun:test';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { spawnSync } from 'node:child_process';@@ -19,6 +19,7 @@ import { VERSION } from '../src/version.ts';import { parseSemver } from '../src/core/semver.ts';import {STABLE_EVIDENCE_POLICY,+ isCacheFresh,offeredVersion,parseMarker,pendingUpgradeVersion,@@ -184,6 +185,41 @@ for (const brain of ['repo-less', 'repo'] as const) {expect(readUpdateCache('stable')).toBeNull();});+ for (const [shape, mtimeOffset] of [['only checked_at is ahead', -2 * 3600_000], ['the file was written while the clock was ahead', 24 * 3600_000]] as const) {+ test(`#8795: a cache stamped a day in the future (${shape}) is stale, and the next check replaces it with the withdrawal`, async () => {+ writeConfig({}, brain);+ const path = join(dotG(), 'update-check.stable.json');+ writeUpdateCache({ kind: 'up_to_date', current: VERSION }, { channel: 'stable', checkedAt: Date.now() + 24 * 3600_000, latest: VERSION });+ const mtime = (Date.now() + mtimeOffset) / 1000;+ utimesSync(path, mtime, mtime);+ expect(isCacheFresh(readUpdateCache('stable')!, Date.now())).toBe(false);+ serve({ record: record(BEHIND, { known_bad: [VERSION] }) });+ await refreshUpdateCache();+ expect(readUpdateCache('stable')).toMatchObject({ latest: BEHIND, knownBad: [VERSION], error: null, marker: { kind: 'upgrade_available', latest: BEHIND } });+ expect(isCacheFresh(readUpdateCache('stable')!, Date.now())).toBe(true);+ expect(pendingUpgradeVersion(VERSION)).toBe(BEHIND);+ });+ }++ test('#8795: a stored check a few seconds ahead still wins over an older refresh', () => {+ writeConfig({}, brain);+ const now = Date.now();+ writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD2 }, { channel: 'stable', checkedAt: now + 30_000 });+ expect(isCacheFresh(readUpdateCache('stable')!, now)).toBe(true);+ writeUpdateCache({ kind: 'up_to_date', current: VERSION }, { channel: 'stable', checkedAt: now });+ expect(readUpdateCache('stable')?.latest).toBe(AHEAD2);+ });++ test('#8795: a cache file a network home\'s file server stamped ahead, checked by this clock, stays fresh', () => {+ writeConfig({}, brain);+ const path = join(dotG(), 'update-check.stable.json');+ writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD }, { channel: 'stable' });+ const mtime = (Date.now() + 10 * 60_000) / 1000;+ utimesSync(path, mtime, mtime);+ expect(isCacheFresh(readUpdateCache('stable')!, Date.now())).toBe(true);+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD);+ });+test('an invalid configured channel checks and offers nothing', async () => {writeConfig({ self_upgrade: { channel: 'nightly' } }, brain);writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD }, { channel: 'stable' });diff --git a/test/repair-agent-session-facts-scale-9503.test.ts b/test/repair-agent-session-facts-scale-9503.test.tsindex 35d108845e..a56aa46947 100644--- a/test/repair-agent-session-facts-scale-9503.test.ts+++ b/test/repair-agent-session-facts-scale-9503.test.ts@@ -6,7 +6,8 @@* the old per-fact table scan ran past the 5 minute statement timeout); the owner-twin classification is unchanged.* The test counts fingerprint evaluations with a counting copy of gbrain_fact_fingerprint that returns the same hash, and* prices sequential scans out so a table this small takes the index path the planner picks on a real-size brain. The- * take lookup groups contributing facts in one pass over the table instead of scanning it once per take.+ * take lookup groups contributing facts in one pass over the table instead of scanning it once per take, and reads only+ * the listed sources' facts, so its cost does not grow with facts in other sources.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';@@ -19,6 +20,7 @@ import { agentSessionTakes, classifyAgentSessionFacts } from '../src/core/repairconst ALICE = 'people/alice-example';const UNLISTED_FACTS = 200;const TAKES = 30;+const OTHER_SOURCE_FACTS = 400;describe('agent-session-facts classification cost follows the suspect facts (#9503)', () => {let engine: PGLiteEngine;@@ -105,4 +107,31 @@ describe('agent-session-facts classification cost follows the suspect facts (#95expect(takes.map(t => t.claim)).toEqual(Array.from({ length: TAKES }, (_, i) => `Agent claim ${i + 1}`));expect(read).toBeLessThanOrEqual(2 * total);});++ test('the take lookup reads only the facts of the sources it lists', async () => {+ const factsRead = async () => {+ await engine.executeRaw('SELECT pg_stat_force_next_flush()');+ const [row] = await engine.executeRaw<{ n: string }>(+ "SELECT (COALESCE(seq_tup_read, 0) + COALESCE(idx_tup_fetch, 0))::text AS n FROM pg_stat_user_tables WHERE relname='facts'");+ return Number(row!.n);+ };+ const lookup = async () => {+ await engine.executeRaw('ANALYZE facts');+ const before = await factsRead();+ const takes = await agentSessionTakes(engine, ['default'], new Set());+ return { read: (await factsRead()) - before, takes: takes.length };+ };+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-b', 'source-b') ON CONFLICT DO NOTHING");+ await engine.executeRaw("INSERT INTO pages (source_id, slug, type, title, compiled_truth) VALUES ('source-b', $1, 'person', 'Alice Example', '')", [ALICE]);+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug=$1 AND source_id='source-b'", [ALICE]);+ const [take] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, source, active)+ VALUES ($1, 1, 'Other source claim', 'fact', 'self', 0.8, '2026-10-01', 'hook:writeback', true) RETURNING id`, [page!.id]);+ const small = await lookup();+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, attributed_to, consolidated_into, consolidated_at)+ SELECT 'source-b', $1, 'Other source claim ' || g, 'preference', 'private', 'hook:writeback', 'sess-b-' || g, 'user', $2, now() - interval '1 minute'+ FROM generate_series(1, $3::int) g`, [ALICE, take!.id, OTHER_SOURCE_FACTS]);+ const large = await lookup();+ expect(large.takes).toBe(small.takes);+ expect(large.read - small.read).toBeLessThan(OTHER_SOURCE_FACTS / 10);+ });});diff --git a/test/serve-http-foreground-auth.test.ts b/test/serve-http-foreground-auth.test.tsnew file mode 100644index 0000000000..935909ba0a--- /dev/null+++ b/test/serve-http-foreground-auth.test.ts@@ -0,0 +1,60 @@+/**+ * #9484: a POST /mcp refused at bearer auth is not serve activity.+ *+ * 1. Protects: `gbrain serve --http` runs idle upkeep only after a full quiet+ * interval with no foreground request. A POST /mcp with no bearer token or a+ * wrong one (401) never marks foreground activity, so anyone who can reach+ * the port cannot hold upkeep off; an authenticated POST /mcp still counts.+ * 2. Fails when: the foreground mark runs before the bearer check (every POST+ * /mcp counted, refused or not), or an authenticated request stops counting.+ * 3. Existing coverage: test/serve-idle-upkeep-gbra438.test.ts pins the+ * middleware's POST/GET split and the idle tick itself.+ * 4. Real seams: the production serve-http app on a loopback port over a+ * repo-less PGLite brain, real fetch, the real foreground-activity window.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { _resetForegroundActivityForTests, foregroundWindow, onForegroundRequest } from '../src/core/foreground-activity.ts';+import { legacyToken, rpc, startServeHttp, type LiveServeHttp } from './helpers/live-mcp-servers.ts';++describe('serve --http: a 401 on POST /mcp is not foreground activity (#9484)', () => {+ let engine: PGLiteEngine;+ let app: LiveServeHttp;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ app = await startServeHttp(engine);+ }, 120_000);+ afterAll(async () => { await app.close(); await engine.disconnect(); }, 60_000);+ beforeEach(() => { _resetForegroundActivityForTests(); });++ const post = (authorization?: string) => fetch(`${app.base}/mcp`, {+ method: 'POST',+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' }),+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...(authorization ? { Authorization: authorization } : {}) },+ });++ test('missing, wrong and malformed bearer tokens are refused 401 and mark no activity', async () => {+ let starts = 0;+ onForegroundRequest(() => { starts++; });+ const window = foregroundWindow();+ const statuses: number[] = [];+ for (const authorization of [undefined, 'Bearer not-a-real-token', 'Bearer gbrain_0000000000000000', 'Basic YWxpY2UtZXhhbXBsZTpwdw==']) {+ const res = await post(authorization);+ await res.text();+ statuses.push(res.status);+ }+ expect(statuses).toEqual([401, 401, 401, 401]);+ expect({ starts, active: window() }).toEqual({ starts: 0, active: false });+ }, 60_000);++ test('an authenticated POST /mcp still marks activity', async () => {+ let starts = 0;+ onForegroundRequest(() => { starts++; });+ const window = foregroundWindow();+ const token = await legacyToken(engine, ['read']);+ expect((await rpc(app.base, token, 'tools/list')).status).toBe(200);+ expect({ starts, active: window() }).toEqual({ starts: 1, active: true });+ }, 60_000);+});diff --git a/test/transcripts-archive-status-maintenance-auto.test.ts b/test/transcripts-archive-status-maintenance-auto.test.tsnew file mode 100644index 0000000000..940e52ad33--- /dev/null+++ b/test/transcripts-archive-status-maintenance-auto.test.ts@@ -0,0 +1,64 @@+/**+ * gbrain transcripts archive status says when free upkeep will not run the archive by itself: with maintenance.auto+ * false the serve's idle upkeep and gbrain maintain --unattended skip it, so the line names the on-demand run. The+ * --json document is unchanged. PGLite, no reader is run.+ */+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runTranscriptsArchive } from '../src/commands/transcripts-archive.ts';+import { ARCHIVE_TIMEZONE_KEY, setArchiveEnabled } from '../src/core/transcripts/archive.ts';+import { MAINTENANCE_AUTO_KEY } from '../src/core/maintenance/run.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'archive-status-auto-'));+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});+beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig(ARCHIVE_TIMEZONE_KEY, 'UTC');+ await engine.setConfig('brain.audience', 'personal');+ await setArchiveEnabled(engine, true);+});++async function status(auto: string | null, json = false): Promise<string> {+ if (auto !== null) await engine.setConfig(MAINTENANCE_AUTO_KEY, auto);+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await withEnv({ GBRAIN_HOME: home, HOME: home, GBRAIN_OPENCLAW_GATEWAY_URL: undefined }, () => runTranscriptsArchive(engine, ['status', ...(json ? ['--json'] : [])]));+ return log.mock.calls.map(call => call.join(' ')).join('\n');+ } finally {+ log.mockRestore();+ }+}++const LINE = 'maintenance.auto is false';++test('maintenance.auto false: status says upkeep will not archive and names the on-demand run', async () => {+ const out = await status('false');+ expect(out).toContain(LINE);+ expect(out).toContain('gbrain transcripts archive run');+}, 60_000);++test('maintenance.auto true or unset: no such line', async () => {+ expect(await status(null)).not.toContain(LINE);+ expect(await status('true')).not.toContain(LINE);+}, 60_000);++test('the --json document is the same whatever maintenance.auto says', async () => {+ const unset = JSON.parse(await status(null, true));+ const off = JSON.parse(await status('false', true));+ expect(off).toEqual(unset);+}, 60_000);