Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources): protect archives with invalid timestamps from purge (#5618, #5452)

garrytan5f3bb03e7aaa
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 3841081674..c174d4a924 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -21,7 +21,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; classification is `isClaudeCliSelfSessionId`; details carry `newest_capture_at`, a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`, and the message says new captures stopped (#5820) so only the existing files need one quarantine; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.test.ts`.
-- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`.
+- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Failures on archived sources (which sync refuses) are left out of the count and severity and only reported as an ignored total. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`, `test/doctor-sync-failures-archived.test.ts`.
- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks` (flag parse into a `DoctorContext`, then `runDoctorRegistry`), `runDoctor` and output rendering; the checks run as the ordered registry in `src/commands/doctor/registry.ts` (see that entry), the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check (`doctor/checks/supervisor-health.ts`) consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and in `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate; `pgliteDataDirEntry` in `doctor/checks/db-connection.ts`): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_capability` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered by the `supervisor` registry entry after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 09294273c3..9f293f4dd7 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -45,7 +45,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
-- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation.
+- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance instead of purging.
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.
- `src/core/sync-concurrency.ts` — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the sites can't drift. `DEFAULT_PARALLEL_SOURCES = 4` is a SEPARATE constant for the per-source fan-out under `gbrain sync --all` — kept distinct from `DEFAULT_PARALLEL_WORKERS` because total live Postgres connections per wave ≈ `DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool)` = 32 at both defaults (each per-file worker opens its own `PostgresEngine` with `poolSize = min(2, resolvePoolSize(2))`); `sync.ts` warns when `parallel × workers × 2 > 16`. `resolveWorkersWithClamp(engine, override, commandName, fileCount)` wraps `autoConcurrency` with a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with `_resetWorkersClampWarningsForTest()` seam) and is the canonical surface for every bulk-command `--workers N` flag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keeps `GBRAIN_EMBED_CONCURRENCY || 20`. `resolveMaxConnections()` (reads `GBRAIN_MAX_CONNECTIONS`, undefined when unset) + `clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool)` back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (`parent_pool + workers×perWorkerPool ≤ budget`); `gbrain doctor`'s `pool_budget` check (`computePoolBudgetCheck` / `checkPoolBudget` in `src/commands/doctor/checks/consolidation-cycle.ts`, re-exported by `src/commands/doctor.ts`) warns when the budget leaves no room for a worker, pointing at `GBRAIN_POOL_SIZE=2`. Pinned by `test/pglite-workers-clamp.test.ts`.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 3aad12214f..b47951d8f2 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.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/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
+- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting; an archive with a missing or epoch `archived_at`/`archive_expires_at` is never treated as expired and is reported in `blocked`. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index 647802ad26..e4e2b962cc 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -6,14 +6,20 @@ import { resolveHoursEnv } from '../../../core/env-number.ts';
import { makeRemediationStep } from '../../../core/remediation-step.ts';
export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean } = {}): Promise<Check | null> {
- const managed = engine ? await readManagedSyncFailures(engine, opts.sourceIds) : [];
- let legacy: SyncFailure[] = [];
- try { legacy = loadSyncFailures().filter(row => (!engine || !row.managed_cursor_key) && (!opts.sourceIds || opts.sourceIds.includes(row.source_id))); } catch { }
+ // #5452: sync refuses an archived source, so its failures cannot be cleared and are not a live health signal.
+ const archived = new Set(engine ? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived = true')).map(row => row.id) : []);
+ const allManaged = engine ? await readManagedSyncFailures(engine, opts.sourceIds) : [];
+ let allLegacy: SyncFailure[] = [];
+ try { allLegacy = loadSyncFailures().filter(row => (!engine || !row.managed_cursor_key) && (!opts.sourceIds || opts.sourceIds.includes(row.source_id))); } catch { }
+ const managed = allManaged.filter(row => !archived.has(row.source_id));
+ const legacy = allLegacy.filter(row => !archived.has(row.source_id));
+ const archivedCount = allManaged.length - managed.length + allLegacy.length - legacy.length;
+ const archivedNote = archivedCount ? ` ${archivedCount} failure(s) on archived source(s) ignored; restore a source to retry them.` : '';
const entries: SyncFailure[] = [...legacy, ...managed.map(row => ({ source_id: row.source_id, path: row.path, code: row.code, error: row.message,
commit: row.target ?? '', first_seen: row.first_seen, ts: row.first_seen, attempts: row.attempts, state: 'open' as const }))];
const severity = decideSyncFailureSeverity({ entries, nowMs: Date.now(), failHours: resolveHoursEnv('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72) });
- if (!severity.unresolved) return entries.length ? { name: 'sync_failures', status: 'ok', message: 'All historical sync failures are acknowledged.' } : null;
- const summary = `${severity.unresolved} unresolved sync failure(s)${severity.auto_skipped ? ` (${severity.auto_skipped} auto-skipped — pages NOT indexed)` : ''}.`;
+ if (!severity.unresolved) return entries.length || archivedCount ? { name: 'sync_failures', status: 'ok', message: `${entries.length ? 'All historical sync failures are acknowledged.' : 'No sync failures on active sources.'}${archivedNote}` } : null;
+ const summary = `${severity.unresolved} unresolved sync failure(s)${severity.auto_skipped ? ` (${severity.auto_skipped} auto-skipped — pages NOT indexed)` : ''}.${archivedNote}`;
if (opts.remote !== false) return { name: 'sync_failures', status: severity.status, message: summary + ' Ask the host operator to inspect doctor and repair the accepted sync; no paths or receipt details are exposed remotely.' };
const [brain] = engine ? await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1') : [];
const requiresManagedRetry = brain?.enabled || managed.length > 0 || legacy.some(row => row.managed_cursor_key);
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 02c3865988..6cdc8b3dc0 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1738,7 +1738,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas
duration_ms: 0,
summary:
`purged ${purgedSources.length} source(s)` +
- (purgeResult.blocked.length > 0 ? ` (${purgeResult.blocked.length} FK-blocked, see details)` : '') +
+ (purgeResult.blocked.length > 0 ? ` (${purgeResult.blocked.length} blocked, see details)` : '') +
`, ${purgedPages.count} page(s), ` +
`${purgedClones.count} orphan clone temp dir(s), ${purgedCheckpoints} stale op_checkpoint(s), ` +
`${purgedBrainstormCheckpoints} stale brainstorm checkpoint(s), ` +
diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.ts
index a2c306737d..dc62dccc1b 100644
--- a/src/core/destructive-guard.ts
+++ b/src/core/destructive-guard.ts
@@ -23,7 +23,7 @@ import { isPathContained } from './path-confine.ts';
import { defaultCloneDir } from './sources-ops.ts';
import { gbrainPath } from './config.ts';
import { isUndefinedColumnError, isUndefinedTableError } from './utils.ts';
-import { deleteSourceRow } from './source-delete.ts';
+import { deleteSourceRow, EXPIRED_ARCHIVE_SQL, UNVERIFIED_ARCHIVE_SQL, unverifiedArchiveReason } from './source-delete.ts';
// ── Types ───────────────────────────────────────────────────
@@ -468,14 +468,18 @@ export interface PurgeExpiredResult {
* table an EXISTS prefilter names, and the structured {purged, blocked}
* return is what every caller + test in this tree consumes.)
*/
+async function unverifiedArchives(engine: BrainEngine): Promise<PurgeExpiredResult['blocked']> {
+ const rows = await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE ${UNVERIFIED_ARCHIVE_SQL} ORDER BY id`);
+ return rows.map(({ id }) => ({ id, reason: unverifiedArchiveReason(id) }));
+}
+
export async function purgeExpiredSources(
engine: BrainEngine,
): Promise<PurgeExpiredResult> {
if(await managedPersistenceEnabled(engine)){
const {runManagedSourceLifecycle}=await import('./persistence/source-lifecycle.ts');
- const candidates=await engine.executeRaw<{id:string;incarnation:string}>(`SELECT id,incarnation FROM sources WHERE archived=true
- AND archive_expires_at IS NOT NULL AND archive_expires_at<=now() ORDER BY id`);
- const result:PurgeExpiredResult={purged:[],blocked:[]};
+ const candidates=await engine.executeRaw<{id:string;incarnation:string}>(`SELECT id,incarnation FROM sources WHERE ${EXPIRED_ARCHIVE_SQL} ORDER BY id`);
+ const result:PurgeExpiredResult={purged:[],blocked:await unverifiedArchives(engine)};
for(const source of candidates){
try{const receipt=await runManagedSourceLifecycle(engine,{operation:'purge',sourceId:source.id,expectedIncarnation:source.incarnation,confirmDestructive:true,expiredOnly:true});if(!receipt.noop)result.purged.push(source.id);}
catch(error){result.blocked.push({id:source.id,reason:error instanceof Error?error.message:'Source lifecycle could not finish.'});}
@@ -484,14 +488,10 @@ export async function purgeExpiredSources(
}
await assertUnmanagedCanonicalWriter(engine, 'sources purge');
const candidates = await engine.executeRaw<{ id: string; config: unknown; local_path: string | null }>(
- `SELECT id, config, local_path FROM sources
- WHERE archived = true
- AND archive_expires_at IS NOT NULL
- AND archive_expires_at <= now()
- ORDER BY id`,
+ `SELECT id, config, local_path FROM sources WHERE ${EXPIRED_ARCHIVE_SQL} ORDER BY id`,
);
const purged: string[] = [];
- const blocked: PurgeExpiredResult['blocked'] = [];
+ const blocked: PurgeExpiredResult['blocked'] = await unverifiedArchives(engine);
const cloneRoot = gbrainPath('clones');
for (const candidate of candidates) {
const { id } = candidate;
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 4f074d811d..33cf3a5520 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -5,6 +5,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { isValidSourceId } from '../source-id.ts';
+import { EXPIRED_ARCHIVE_SQL } from '../source-delete.ts';
import { parseSourceConfig } from '../sources-load.ts';
import { redactSourceConfig } from '../source-config-redact.ts';
import { discoverGitRoot } from '../sync-git.ts';
@@ -133,7 +134,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
throw new OperationError('writer_transfer_required','The source already has a different canonical binding. Use rebind or verified ownership transfer.');
if(input.operation==='claim'&&!currentBinding&&source?.local_path&&realpathSync(source.local_path)!==root!.source)
throw new OperationError('source_changed','The requested claim path differs from the configured source root.');
- const expired=input.expiredOnly?await tx.executeRaw('SELECT id FROM sources WHERE id=$1 AND archived=true AND archive_expires_at<=now()',[input.sourceId]):null;
+ const expired=input.expiredOnly?await tx.executeRaw(`SELECT id FROM sources WHERE id=$1 AND ${EXPIRED_ARCHIVE_SQL}`,[input.sourceId]):null;
const noop=expired?.length===0 || input.operation==='archive'&&source?.archived || input.operation==='restore'&&!source?.archived
|| input.operation==='claim'&&!!currentBinding || input.operation==='rebind'&&sameBinding;
if(noop){
diff --git a/src/core/source-delete.ts b/src/core/source-delete.ts
index f40b14acde..288a7d00ab 100644
--- a/src/core/source-delete.ts
+++ b/src/core/source-delete.ts
@@ -1,5 +1,17 @@
import type { BrainEngine } from './engine.ts';
+/**
+ * An archived source is purge-eligible only when both archive timestamps are real
+ * and its window has elapsed. A missing or epoch timestamp (#5452) cannot prove the
+ * 72h recovery window was honored, so it never reads as expired.
+ */
+export const EXPIRED_ARCHIVE_SQL = `archived = true AND archived_at > '1970-01-02'::timestamptz
+ AND archive_expires_at > '1970-01-02'::timestamptz AND archive_expires_at <= now()`;
+export const UNVERIFIED_ARCHIVE_SQL = `archived = true AND (archived_at IS NULL OR archived_at <= '1970-01-02'::timestamptz
+ OR archive_expires_at IS NULL OR archive_expires_at <= '1970-01-02'::timestamptz)`;
+export const unverifiedArchiveReason = (id: string) =>
+ `archive timestamps are missing or invalid, so the 72h recovery window cannot be verified; run gbrain sources restore ${id}, then gbrain sources archive ${id} to restart it`;
+
/**
* Delete a `sources` row together with that incarnation's persistence source
* binding (#5732). `persistence_source_bindings` has no FK to `sources`, so a
@@ -13,7 +25,7 @@ export async function deleteSourceRow(
opts: { expiredArchiveOnly?: boolean } = {},
): Promise<boolean> {
const expired = opts.expiredArchiveOnly
- ? 'AND archived = true AND archive_expires_at IS NOT NULL AND archive_expires_at <= now()'
+ ? `AND ${EXPIRED_ARCHIVE_SQL}`
: '';
const rows = await engine.executeRaw<{ id: string }>(
`WITH gone AS (DELETE FROM sources WHERE id = $1 ${expired} RETURNING id, incarnation),
diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.ts
index 2b89a67305..c3820ee9ac 100644
--- a/test/destructive-guard.test.ts
+++ b/test/destructive-guard.test.ts
@@ -394,6 +394,110 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
expect(remainingPages[0].n).toBe(0);
});
+ test('gbrain#5452 — epoch or missing archive timestamps are never purge-eligible and are reported', async () => {
+ const epochId = 'pe-epoch';
+ const nullId = 'pe-null-expiry';
+ await seedSource(engine, epochId, { withPages: 1 });
+ await seedSource(engine, nullId, { withPages: 1 });
+ await softDeleteSource(engine, epochId);
+ await softDeleteSource(engine, nullId);
+ await engine.executeRaw(
+ `UPDATE sources SET archived_at = '1970-01-01T00:00:00Z', archive_expires_at = '1970-01-01T00:00:00Z' WHERE id = $1`,
+ [epochId],
+ );
+ await engine.executeRaw(
+ `UPDATE sources SET archive_expires_at = NULL WHERE id = $1`,
+ [nullId],
+ );
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ expect(purged).not.toContain(epochId);
+ expect(purged).not.toContain(nullId);
+ expect(blocked.map((b) => b.id)).toEqual(expect.arrayContaining([epochId, nullId]));
+ // Both sources and their pages survive — full contents intact.
+ const intact = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id IN ($1, $2)`,
+ [epochId, nullId],
+ );
+ expect(intact[0].n).toBe(2);
+ // Cleanup: leftover archived rows are reported as suspects by every
+ // later purge sweep in this describe.
+ await engine.executeRaw(`DELETE FROM sources WHERE id IN ($1, $2)`, [epochId, nullId]);
+ });
+
+ test('gbrain#5452 — a missing/epoch archived_at refuses purge even with a normal past expiry', async () => {
+ const epochArchId = 'pe-epoch-arch';
+ const nullArchId = 'pe-null-arch';
+ await seedSource(engine, epochArchId, { withPages: 1 });
+ await seedSource(engine, nullArchId, { withPages: 1 });
+ await softDeleteSource(engine, epochArchId);
+ await softDeleteSource(engine, nullArchId);
+ // Past expiry is a perfectly normal value here — the refusal comes from
+ // archived_at, which can no longer prove the 72h window ever existed.
+ await engine.executeRaw(
+ `UPDATE sources SET archived_at = '1970-01-01T00:00:00Z', archive_expires_at = now() - INTERVAL '1 hour' WHERE id = $1`,
+ [epochArchId],
+ );
+ await engine.executeRaw(
+ `UPDATE sources SET archived_at = NULL, archive_expires_at = now() - INTERVAL '1 hour' WHERE id = $1`,
+ [nullArchId],
+ );
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ expect(purged).not.toContain(epochArchId);
+ expect(purged).not.toContain(nullArchId);
+ expect(blocked.map((b) => b.id)).toEqual(expect.arrayContaining([epochArchId, nullArchId]));
+ const intact = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id IN ($1, $2)`,
+ [epochArchId, nullArchId],
+ );
+ expect(intact[0].n).toBe(2);
+ await engine.executeRaw(`DELETE FROM sources WHERE id IN ($1, $2)`, [epochArchId, nullArchId]);
+ });
+
+ test('gbrain#5452 — timestamps flipped to epoch/missing after candidate selection are refused at delete time', async () => {
+ const flipExpiryId = 'pe-flip-expiry';
+ const flipArchId = 'pe-flip-arch';
+ await seedSource(engine, flipExpiryId, { withPages: 1 });
+ await seedSource(engine, flipArchId, { withPages: 1 });
+ await softDeleteSource(engine, flipExpiryId);
+ await softDeleteSource(engine, flipArchId);
+ // Both start as legitimate candidates: real archived_at, past expiry.
+ await engine.executeRaw(
+ `UPDATE sources SET archive_expires_at = now() - INTERVAL '1 hour' WHERE id IN ($1, $2)`,
+ [flipExpiryId, flipArchId],
+ );
+ // The sweep reads candidates, then deletes one row at a time. Reproduce a
+ // stamp flip landing in between: the moment the first DELETE arrives, both
+ // rows' stamps degrade to the refusal set — the DELETE itself must refuse.
+ const orig = engine.executeRaw.bind(engine);
+ let flipped = false;
+ engine.executeRaw = (async (sql: string, params?: unknown[]) => {
+ if (!flipped && typeof sql === 'string' && sql.includes('DELETE FROM sources')) {
+ flipped = true;
+ await orig(
+ `UPDATE sources SET archive_expires_at = '1970-01-01T00:00:00Z' WHERE id = $1`,
+ [flipExpiryId],
+ );
+ await orig(`UPDATE sources SET archived_at = NULL WHERE id = $1`, [flipArchId]);
+ }
+ return orig(sql, params);
+ }) as typeof engine.executeRaw;
+ let purged: string[] = [];
+ try {
+ ({ purged } = await purgeExpiredSources(engine));
+ } finally {
+ engine.executeRaw = orig;
+ }
+ expect(flipped).toBe(true);
+ expect(purged).not.toContain(flipExpiryId);
+ expect(purged).not.toContain(flipArchId);
+ const intact = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id IN ($1, $2)`,
+ [flipExpiryId, flipArchId],
+ );
+ expect(intact[0].n).toBe(2);
+ await engine.executeRaw(`DELETE FROM sources WHERE id IN ($1, $2)`, [flipExpiryId, flipArchId]);
+ });
+
test('gbrain#4115 — an FK-blocked source is reported and skipped; the deletable one still purges', async () => {
const blockedId = 'pe-fk-blocked';
const deletableId = 'pe-fk-deletable';
@@ -457,6 +561,7 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
test('gbrain#4115 — a source restored between SELECT and DELETE is neither purged nor blocked (review gap G8)', async () => {
const stub = {
async executeRaw(sql: string): Promise<Array<{ id: string }>> {
+ if (sql.includes('archive_expires_at IS NULL')) return []; // #5452 unverified-archive listing: none here
if (sql.trimStart().startsWith('SELECT')) return [{ id: 'restored-mid-sweep' }];
return []; // per-id DELETE re-checks the expiry predicate → 0 rows
},
diff --git a/test/doctor-sync-failures-archived.test.ts b/test/doctor-sync-failures-archived.test.ts
new file mode 100644
index 0000000000..8ca213ce99
--- /dev/null
+++ b/test/doctor-sync-failures-archived.test.ts
@@ -0,0 +1,81 @@
+import { describe, test, expect, beforeAll, afterAll, beforeEach } 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 { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';
+import { recordFailures } from '../src/core/sync-failure-ledger.ts';
+import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+// gbrain#5452 — failures on an archived source cannot be cleared (sync
+// refuses archived sources) and carry no live signal; doctor's
+// sync_failures check must exclude them and say so.
+const home = mkdtempSync(join(tmpdir(), 'gbrain-5452-'));
+const env = { GBRAIN_SYNC_FAILURES_DIR: home };
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('TRUNCATE sources CASCADE');
+ rmSync(join(home, 'sync-failures.jsonl'), { force: true });
+});
+
+describe('sync_failures ignores archived-source rows (#5452)', () => {
+ test('failures on an archived source are excluded and reported as ignored', async () => withEnv(env, async () => {
+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES('src-active','src-active'),('src-archived','src-archived')`);
+ await engine.executeRaw(`UPDATE sources SET archived=true, archived_at=now(), archive_expires_at=now()+interval '72 hours' WHERE id='src-archived'`);
+ recordFailures('src-active', [{ path: 'a.md', error: 'YAML broke' }], 'c1');
+ recordFailures('src-archived', [{ path: 'b.md', error: 'YAML broke' }], 'c2');
+
+ const check = await checkSyncFailures(engine, { remote: false });
+ expect(check).not.toBeNull();
+ expect(check!.status).not.toBe('ok');
+ expect(check!.message).toContain('1 unresolved');
+ expect(check!.message).toContain('1 failure(s) on archived source(s) ignored');
+ expect(check!.message).toContain('src-active');
+ expect(check!.message).not.toContain('src-archived');
+ }));
+
+ test('only-archived failures resolve to ok, not an unclearable fail', async () => withEnv(env, async () => {
+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES('src-archived','src-archived')`);
+ await engine.executeRaw(`UPDATE sources SET archived=true, archived_at=now(), archive_expires_at=now()+interval '72 hours' WHERE id='src-archived'`);
+ recordFailures('src-archived', [{ path: 'b.md', error: 'YAML broke' }], 'c2');
+
+ const check = await checkSyncFailures(engine, { remote: false });
+ expect(check?.status).toBe('ok');
+ expect(check!.message).toContain('1 failure(s) on archived source(s) ignored');
+ }));
+
+ test('managed-ledger failures on archived sources are excluded too', async () => withEnv(env, async () => {
+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES('src-m-arch','src-m-arch')`);
+ await engine.executeRaw(`UPDATE sources SET archived=true, archived_at=now(), archive_expires_at=now()+interval '72 hours' WHERE id='src-m-arch'`);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>(
+ `SELECT incarnation::text AS incarnation FROM sources WHERE id='src-m-arch'`);
+ // The managed ledger lives in op_checkpoints, not the JSONL file — this
+ // row exercises readManagedSyncFailures' orphan path (failure recorded
+ // for a source whose managed-sync cursor is gone).
+ await recordManagedSyncFailure(engine, {
+ source_id: 'src-m-arch', source_incarnation: incarnation, path: 'blocked.md',
+ code: 'sync_incomplete', message: 'cursor unfinished', request_id: null,
+ run_id: 'run-arch', target: null, cursor_key: 'ck-arch', phase: 'resume',
+ state: 'unfinished', observation_id: 'obs-arch',
+ });
+ const check = await checkSyncFailures(engine, { remote: false });
+ expect(check?.status).toBe('ok');
+ expect(check!.message).toContain('1 failure(s) on archived source(s) ignored');
+ expect(check!.message).not.toContain('src-m-arch');
+ expect(check!.message).not.toContain('blocked.md');
+ }));
+});
diff --git a/test/helpers/source-bindings-suite.ts b/test/helpers/source-bindings-suite.ts
index 50dc595d78..8868090fd4 100644
--- a/test/helpers/source-bindings-suite.ts
+++ b/test/helpers/source-bindings-suite.ts
@@ -55,7 +55,7 @@ export function sourceBindingsSuite(label: string, getEngine: () => BrainEngine)
test('purging an expired archive drops the binding', async () => {
await bind('expired-a', await addSource('expired-a'));
- await getEngine().executeRaw("UPDATE sources SET archived = true, archive_expires_at = now() - interval '1 day' WHERE id = 'expired-a'");
+ await getEngine().executeRaw("UPDATE sources SET archived = true, archived_at = now() - interval '4 days', archive_expires_at = now() - interval '1 day' WHERE id = 'expired-a'");
await withEnv({ GBRAIN_HOME: '/tmp/gbrain-5732-no-clones' }, () => quiet(() => purgeExpiredSources(getEngine())));
expect(await bindings('expired-a')).toBe(0);
});
diff --git a/test/persistence-source-lifecycle.test.ts b/test/persistence-source-lifecycle.test.ts
index f66580628f..9004780172 100644
--- a/test/persistence-source-lifecycle.test.ts
+++ b/test/persistence-source-lifecycle.test.ts
@@ -191,6 +191,32 @@ test('expiry sweep rechecks restored sources under the topology guard',()=>fixtu
}),60_000);
+test('gbrain#5452 managed purge refuses missing/epoch archive stamps and still purges a real expiry',()=>fixture(async(_home,source)=>{
+ await runManagedSourceLifecycle(engine,{operation:'archive',sourceId:source});
+ const purge=()=>runManagedSourceLifecycle(engine,{operation:'purge',sourceId:source,confirmDestructive:true,expiredOnly:true});
+ const survives=async()=>expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1',[source])).toHaveLength(1);
+ // Epoch expiry — pre-column-stamp archive shape from the report.
+ await engine.executeRaw(`UPDATE sources SET archive_expires_at='1970-01-01T00:00:00Z' WHERE id=$1`,[source]);
+ expect(await purge()).toMatchObject({state:'committed',noop:true});await survives();
+ // Missing expiry.
+ await engine.executeRaw(`UPDATE sources SET archive_expires_at=NULL WHERE id=$1`,[source]);
+ expect(await purge()).toMatchObject({state:'committed',noop:true});await survives();
+ // A normal past expiry is not enough on its own: an epoch/missing
+ // archived_at means the 72h window was never provably granted.
+ await engine.executeRaw(`UPDATE sources SET archive_expires_at=now()-INTERVAL '1 hour' WHERE id=$1`,[source]);
+ await engine.executeRaw(`UPDATE sources SET archived_at='1970-01-01T00:00:00Z' WHERE id=$1`,[source]);
+ expect(await purge()).toMatchObject({state:'committed',noop:true});await survives();
+ await engine.executeRaw(`UPDATE sources SET archived_at=NULL WHERE id=$1`,[source]);
+ expect(await purge()).toMatchObject({state:'committed',noop:true});await survives();
+ // Real stamps + past expiry purge normally — a real purge receipt carries
+ // no `noop` marker and the row is gone.
+ await engine.executeRaw(`UPDATE sources SET archived_at=now()-INTERVAL '73 hours' WHERE id=$1`,[source]);
+ const receipt=await purge();
+ expect(receipt).toMatchObject({state:'committed'});
+ expect('noop' in receipt).toBe(false);
+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1',[source])).toHaveLength(0);
+}),60_000);
+
test('a failed new clone retries under the retained physical identity and a new explicit request',()=>fixture(async(home)=>{
const target=join(home,'new-clone');
const first={operation:'add' as const,sourceId:'new-clone-source',path:target,remoteUrl:'https://example.invalid/brain.git',requestId:randomUUID()};
diff --git a/test/persistence-writer-fences.test.ts b/test/persistence-writer-fences.test.ts
index 9aa008629e..09153bad58 100644
--- a/test/persistence-writer-fences.test.ts
+++ b/test/persistence-writer-fences.test.ts
@@ -34,7 +34,7 @@ beforeAll(async () => {
await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)',
[sourceId, root, JSON.stringify({ managed_clone: true, remote_url: 'https://example.com/brain.git' })]);
- await engine.executeRaw("INSERT INTO sources(id,name,archived,archive_expires_at) VALUES($1,$1,true,now()-interval '1 hour')", [`${sourceId}-expired`]);
+ await engine.executeRaw("INSERT INTO sources(id,name,archived,archived_at,archive_expires_at) VALUES($1,$1,true,now()-interval '4 days',now()-interval '1 hour')", [`${sourceId}-expired`]);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
}
}, 120_000);