Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
maintain --safe runs only free phases that never purge pages (GST-2246)
garrytandc1b581328fb
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 98312c7f12..07441df667 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (`fileMatchesSnapshot`, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixable `managed-write-pending` issue with `code: 'managed_write_pending'`, a `reason` (the coordinator refusal's detail, `held_file`, `canonical_file_missing`, `revision_changed`, `not_indexed`), the refusal's own rendered `fix` (never a sync) and the guide link; the run continues (`LintResult.write_path` / `fix_pending` / `pending_issues`, first 50; #5180, `test/managed-lint.test.ts` on both engines). A file the scan listed that is gone by its scan read (ENOENT only; other read errors still fail the run) is reported instead of aborting: a managed `--fix` run asks the coordinator (pending `canonical_file_missing`), otherwise a non-fixable `file-removed-during-scan` issue with code `file_removed_during_scan` and a `gbrain lint <target>` fix; the CLI prints each issue's `Fix:` command and `Docs:` link (`test/lint-file-removed-during-scan.test.ts`). `llm-preamble` matches only a leading run at a body start (file top, after leading frontmatter, or after a whole-page ```markdown wrapper), and repair removes only that run, so a later line that begins like a preamble is never flagged or deleted. A filesystem fix write refused with EACCES/EPERM/EROFS leaves the file unchanged and becomes a non-fixable `fix-not-writable` issue (`code: 'fix_not_writable'`, the errno as `reason`, a user `fix` naming the permission change or `--exclude`) counted in `fix_pending`; the run continues (`test/lint-preamble-anchor.test.ts`). `placeholder-date` and `empty-section` read code-masked text (`stripCodeBlocks`, offset-preserving): a placeholder or a `## ` line inside a fence or inline code is code, an unclosed fence masks to the end of the file, and `empty-section` reads each section's body from the original text, so a section holding only a code block is not empty (`test/lint-3958.test.ts`). #5433: `missing-created` fires only when none of `created`, `event_date`, `date`, `published`, `captured_at`, `ingested_at` parses (`parseDateLoose` on the parsed frontmatter, never a regex; a block YAML could not read is already `frontmatter-yaml-parse`) and is never fixable: `fixContent` no longer promotes a capture timestamp into `created` (ingest time is not creation time, and the cycle's `fix: true` lint phase rewrote every native page), so a page `serializePageToMarkdown` emits stays byte-identical across repeated `--fix` runs; `promoteCreatedFromCapture` stays exported, deprecated, for explicit callers.-- `src/commands/maintain.ts` — `gbrain maintain [--safe] [--dry-run] [--json]`: stale extraction, then one source-scoped `runCycle` per source doctor's `cycle_freshness` names. A source whose cycle throws an item-scoped error is a `blocked` action with `details.code` and `fix` (`gbrain dream --source <id>`) and later sources still cycle (ItemRun site `maintain.cycle_sources`); run-scoped errors and `item_failures_systemic` stop maintain; any blocked action sets exit 1. Tests: `test/maintain.test.ts`, `test/pathological/a41-maintain-sources.test.ts`.+- `src/commands/maintain.ts` — `gbrain maintain [--safe] [--dry-run] [--json]`: stale extraction, then one source-scoped `runCycle` per source doctor's `cycle_freshness` names, limited to `MAINTAIN_SAFE_PHASES` (free and never hard-deleting: no `purge`, no paid phase); `maintainSafePhases` also holds back `extract_facts` when an embedding provider is available and the repair lanes when `fences.repair.llm` has a model (GST-2246). A source whose cycle throws an item-scoped error is a `blocked` action with `details.code` and `fix` (`gbrain dream --source <id>`) and later sources still cycle (ItemRun site `maintain.cycle_sources`); run-scoped errors and `item_failures_systemic` stop maintain; any blocked action sets exit 1. Tests: `test/maintain.test.ts`, `test/pathological/a41-maintain-sources.test.ts`.- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.- `src/commands/migrate-engine.ts` — Legacy engine copier (`gbrain migrate --to pglite`, and PGLite → Postgres when `migrate.graduation` is `false`). A PGLite → Postgres move routes to `src/commands/migrate-graduation.ts` (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286: `copyPageToTarget` forwards the full page row (`page_kind`, `source_path`, effective date and its source, `import_filename`, `source_kind`/`source_uri`/`ingested_via`, `ingested_at` restored in the timestamp UPDATE), the frontmatter aliases (`setPageAliases`) and each chunk's code metadata (`carryChunkMetadata`). A page sealed on the source is queued `engine_migration`; one the source had not sealed is queued `engine_migration_source_unsealed` and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, `runMigrateEngine` runs `drainProjections` (moved to `src/core/page-state/projections.ts`; `commands/projections.ts` re-exports it) on the target for the `engine_migration` and `rebuild_failed` reasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned by `test/migrate-full-row-projections.serial.test.ts`, `test/e2e/migrate-full-row-projections-postgres.test.ts` and a D2 case in `test/e2e/migrate-engine-pglite-to-postgres.test.ts`. Open-loop and loop-suppression rows the target refuses (`copyMigrationSimpleTable`, per-row `ItemRun` site `migrate_engine.loop_rows`) are printed with their id and reason, block the config flip and set exit 1; a run-scoped failure stops the copy (`test/pathological/a31-migrate-loop-rows.serial.test.ts`). Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.diff --git a/src/commands/maintain.ts b/src/commands/maintain.tsindex da783778f2..f0d8215e34 100644--- a/src/commands/maintain.ts+++ b/src/commands/maintain.ts@@ -3,7 +3,8 @@** This command automates the safe parts of the operator runbook:* - stale link/timeline extraction- * - stale per-source dream cycles when doctor reports cycle_freshness+ * - stale per-source dream cycles when doctor reports cycle_freshness,+ * limited to the free phases that never hard-delete (MAINTAIN_SAFE_PHASES)** It deliberately does NOT mutate source files, apply schema-pack upgrades, or* invent semantic hub links. Those need review or a separate command with an@@ -12,11 +13,15 @@import { existsSync } from 'fs';import { isAbsolute } from 'path';+import { isAvailable } from '../core/ai/gateway.ts';+import { fenceRepairLlmEnabled } from '../core/fence-repair/config.ts';+import { resolveFenceRepairModel } from '../core/fence-repair/model.ts';+import { resolveContentRepairModel } from '../core/content-repair/llm.ts';import type { BrainEngine } from '../core/engine.ts';import type { BrainHealth } from '../core/types.ts';import { buildChecks, computeDoctorReport, type DoctorReport, type Check } from './doctor.ts';import { extractStaleFromDB } from './extract.ts';-import { runCycle, type CycleReport } from '../core/cycle.ts';+import { resolveCyclePhases, runCycle, type CycleReport, type CyclePhase } from '../core/cycle.ts';import { ItemRun } from '../core/item-failure.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -72,6 +77,43 @@ export function extractCycleFreshnessSourceIds(checks: Check[]): string[] {return [...ids].sort();}+/**+ * The cycle phases `--safe` may run: free, and never hard-deleting. The page+ * purge and every phase that calls a model stay with `gbrain dream` and+ * `gbrain pages purge-deleted`.+ */+export const MAINTAIN_SAFE_PHASES: readonly CyclePhase[] = [+ 'lint', 'backlinks', 'sync', 'fence_repair', 'content_repair', 'unindexed_files',+ 'extract', 'extract_facts', 'resolve_symbol_edges', 'recompute_emotional_weight',+ 'consolidate', 'orphans', 'schema-suggest',+];++/** Which providers a safe phase would call on this brain; those phases are held back. */+export interface SafePhaseProviders {+ embedding: boolean;+ fenceRepairModel: boolean;+ contentRepairModel: boolean;+}++export function maintainSafePhases(sourceId: string, providers: SafePhaseProviders): { phases: CyclePhase[]; held: CyclePhase[] } {+ const held: CyclePhase[] = [];+ if (providers.embedding) held.push('extract_facts');+ if (providers.fenceRepairModel) held.push('fence_repair');+ if (providers.contentRepairModel) held.push('content_repair');+ const phases = resolveCyclePhases(undefined, sourceId)+ .filter((phase) => MAINTAIN_SAFE_PHASES.includes(phase) && !held.includes(phase));+ return { phases, held };+}++async function readSafePhaseProviders(engine: BrainEngine): Promise<SafePhaseProviders> {+ const repairLlm = await fenceRepairLlmEnabled(engine);+ return {+ embedding: isAvailable('embedding'),+ fenceRepairModel: repairLlm && (await resolveFenceRepairModel(engine)) !== null,+ contentRepairModel: repairLlm && (await resolveContentRepairModel(engine)) !== null,+ };+}+async function buildDoctorReport(engine: BrainEngine): Promise<DoctorReport> {const checks = await buildChecks(engine, ['--json', '--scope=brain']);return computeDoctorReport(checks);@@ -128,13 +170,17 @@ async function runCycleFreshnessMaintenance(return [{ name: 'cycle_freshness', status: 'ok', message: 'All sources cycled recently.' }];}+ const providers = await readSafePhaseProviders(engine);if (dryRun) {- return sourceIds.map((sourceId) => ({- name: 'cycle_freshness',- status: 'would_apply',- message: `Would run source-scoped dream cycle for ${sourceId}.`,- details: { source_id: sourceId },- }));+ return sourceIds.map((sourceId) => {+ const { phases, held } = maintainSafePhases(sourceId, providers);+ return {+ name: 'cycle_freshness',+ status: 'would_apply',+ message: `Would run the free source cycle for ${sourceId} (no page purge, no paid phases).`,+ details: { source_id: sourceId, phases, held_phases: held },+ };+ });}const sources = await engine.listAllSources();@@ -147,6 +193,7 @@ async function runCycleFreshnessMaintenance(const localPath = source?.local_path ?? null;// #7630: a relative local_path names whatever directory maintain runs from, so it is no checkout.const brainDir = localPath && isAbsolute(localPath) && existsSync(localPath) ? localPath : null;+ const { phases, held } = maintainSafePhases(sourceId, providers);let report: CycleReport;try {report = await runCycle(engine, {@@ -154,6 +201,7 @@ async function runCycleFreshnessMaintenance(dryRun: false,pull: false,sourceId,+ phases,});run.succeed();} catch (error) {@@ -170,12 +218,13 @@ async function runCycleFreshnessMaintenance(actions.push({name: 'cycle_freshness',status: report.status === 'failed' ? 'blocked' : 'applied',- message: `Ran source-scoped dream cycle for ${sourceId}: ${report.status}.`,+ message: `Ran the free source cycle for ${sourceId}: ${report.status}.`,details: {source_id: sourceId,brain_dir: brainDir,cycle_status: report.status,phases: report.phases.map((p) => ({ phase: p.phase, status: p.status })),+ held_phases: held,},});}@@ -198,6 +247,8 @@ Modes:Not auto-applied:source-file frontmatter fixes, schema-pack upgrades, atom-pack changes,semantic hub-link guesses, and destructive cleanup.+ The source cycle skips the page purge (\`gbrain pages purge-deleted\`) and+ every phase that calls a model (\`gbrain dream\`).`);return;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9368f567d1..e17fd6a026 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1494,6 +1494,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.622.0', id: 'purge_cancels_deferred_write_gst1602', text: 'With `persistence.refresh_barrier` on, `gbrain forget <id> --purge` no longer refuses `purge_blocked_pending_recovery` while a write deferred behind a refresh holds the claim in its staged body: the deferred write was never claimed, so the purge cancels it with `purged_content`, as it does a queued one, and removes the content at once instead of up to 15 minutes later.' },{ since: '0.60.623.0', id: 'owner_reads_private_gst2059', text: 'A brain can now name its owner: `gbrain access owner set <member>` (config `access.owner_member`, an enabled member). Every remote credential or stdio server bound to that member reads the whole brain, `visibility: private` pages, privacy-alias pages (`access: private`, ...), derived and pinned-question pages included, through `get_page`, `search`, `query`, `recall` and the other page reads in the sources its grant reads, and `recall` returns its private facts. `readable_by` and folder rules still bind it, and it is not relaxed when it speaks for a shared-room audience. A page the owner\'s credential creates in `default` through `put_page` is not kept to the owner (no `readable_by: [member:<id>]`). Other members, unbound and public callers are unchanged. `_meta.access.relaxation` reads `owner` for such a call, and `gbrain access check --token <name>` reports it. `gbrain repair private-labels` (named runs only) previews the `access: private` labels stamped on ordinary pages with counts per category, keeps real restrictions, and clears the rest in reviewed batches (`--apply --expect <hash>`), recording each change so `--class restore` can put it back. The bulk-ingestion page template no longer writes an `access:` line; what each designation means is in docs/guides/access-designations.md.' },{ since: '0.60.626.0', id: 'record_origin_checkout_lockdown_8888', text: '`gbrain sources record-origin <id>... --remote --apply` now also turns git-lfs downloads and hooks off in each recorded source\'s existing checkout (its `.git/config`: `lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`), not only on later reclones, in the repository\'s shared config, and refuses `write_failed` naming the key when a worktree-scoped or included setting still overrides one; a source already recorded as remote gets the lock-down on the next `--remote --apply` when its checkout lacks it, even when its files now use git-lfs, and a key that holds several values in that config is replaced by the one clone-time value. On a managed brain it takes the same worktree locks a reclone takes, refusing the id `source_busy` while a reclone, refresh or write holds them, and a reclone reads the record under its own locks. A write that fails is reported for its own id (`write_failed`) instead of ending the run. The git-lfs check reads a committed `.gitattributes` under a directory whose name holds a tab, ignores commented-out `filter=lfs` lines, says when a committed rule only declares an LFS filter, records a clone of an empty repository instead of refusing it, and names the cause of an `lfs_unknown` refusal.' },+ { since: 'TBD', id: 'maintain_safe_free_phases_gst2246', text: '`gbrain maintain --safe` no longer hard-deletes pages or runs paid phases. Its source cycle now runs only free phases that never purge (lint, backlinks, sync, the fence and content repair lanes, unindexed files, extract, extract_facts, symbol edges, emotional weight, consolidate, orphans and schema suggestions), and it holds back `extract_facts` when an embedding provider is set up and the repair lanes when `fences.repair.llm` has a repair model, because those would call a provider. Pages soft-deleted more than 72 hours ago are still purged by `gbrain pages purge-deleted` (preview it with `--dry-run`), `gbrain dream` and an installed autopilot; paid phases run from `gbrain dream`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/maintain.test.ts b/test/maintain.test.tsindex b8d387518e..0a4a6a4d2d 100644--- a/test/maintain.test.ts+++ b/test/maintain.test.ts@@ -4,9 +4,12 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import {extractCycleFreshnessSourceIds,+ MAINTAIN_SAFE_PHASES,+ maintainSafePhases,parseMaintainArgs,runMaintain,} from '../src/commands/maintain.ts';+import type { CyclePhase } from '../src/core/cycle.ts';import type { Check } from '../src/commands/doctor.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { withEnv } from './helpers/with-env.ts';@@ -101,3 +104,79 @@ describe('runMaintain --json keeps stdout a single JSON document', () => {expect(report.actions.some((a) => a.name === 'extract_stale' && a.status === 'applied')).toBe(true);});});++// GST-2246: `--safe` once ran the whole dream cycle on the default source, page purge and paid phases included.+const UNSAFE_PHASES: CyclePhase[] = [+ 'purge', 'embed', 'synthesize', 'patterns', 'extract_atoms', 'synthesize_concepts', 'propose_takes',+ 'grade_takes', 'calibration_profile', 'edge_contradictions', 'claim_conflicts', 'drift', 'standing_questions',+ 'chronicle', 'facts_drain', 'conversation_facts_backfill', 'enrich_thin', 'skillopt',+];+const NO_PROVIDERS = { embedding: false, fenceRepairModel: false, contentRepairModel: false };++describe('maintainSafePhases', () => {+ test('never includes the page purge or a paid phase', () => {+ expect(MAINTAIN_SAFE_PHASES.filter((phase) => UNSAFE_PHASES.includes(phase))).toEqual([]);+ for (const sourceId of ['default', 'wiki']) {+ expect(maintainSafePhases(sourceId, NO_PROVIDERS).phases.filter((phase) => UNSAFE_PHASES.includes(phase))).toEqual([]);+ }+ });++ test('a keyless brain runs the free fact and repair phases', () => {+ const { phases, held } = maintainSafePhases('default', NO_PROVIDERS);+ expect(phases).toEqual(expect.arrayContaining(['extract', 'extract_facts', 'fence_repair', 'content_repair', 'orphans']));+ expect(held).toEqual([]);+ });++ test('holds back each phase that would call a provider on this brain', () => {+ const { phases, held } = maintainSafePhases('default', { embedding: true, fenceRepairModel: true, contentRepairModel: true });+ expect(held).toEqual(['extract_facts', 'fence_repair', 'content_repair']);+ expect(phases.filter((phase) => held.includes(phase))).toEqual([]);+ expect(phases).toContain('extract');+ });++ test('a non-default source keeps its source-freshness subset', () => {+ expect(maintainSafePhases('wiki', NO_PROVIDERS).phases).toEqual(['lint', 'backlinks', 'sync', 'extract', 'extract_facts', 'recompute_emotional_weight']);+ });+});++describe('runMaintain --safe on a stale default source', () => {+ let engine: PGLiteEngine;+ let home: string;++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-maintain-safe-'));+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+ });++ test('a page soft-deleted past the purge window survives, and no paid phase runs', async () => {+ await engine.putPage('notes/old', { type: 'concept', title: 'Old', compiled_truth: 'An old note.' });+ await engine.softDeletePage('notes/old');+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() - interval '100 hours' WHERE slug = 'notes/old'`);+ const lastCycle = new Date(Date.now() - 30 * 60 * 60 * 1000).toISOString();+ await engine.executeRaw(+ `UPDATE sources SET local_path = $1, config = config || jsonb_build_object('last_full_cycle_at', $2::text) WHERE id = 'default'`,+ [join(home, 'no-checkout'), lastCycle],+ );++ const out: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { out.push(args.map(String).join(' ')); });+ try {+ await withEnv({ GBRAIN_HOME: home }, () => runMaintain(engine, ['--safe', '--json']));+ } finally {+ spy.mockRestore();+ }+ const report = JSON.parse(out.join('\n')) as { actions: Array<{ name: string; status: string; details?: { source_id?: string; phases?: Array<{ phase: CyclePhase }> } }> };+ const cycle = report.actions.find((a) => a.name === 'cycle_freshness' && a.details?.source_id === 'default');+ expect(cycle?.status).toBe('applied');+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages WHERE slug = 'notes/old' AND deleted_at IS NOT NULL`);+ expect(rows.map((r) => r.slug)).toEqual(['notes/old']);+ expect((cycle?.details?.phases ?? []).map((p) => p.phase).filter((phase) => UNSAFE_PHASES.includes(phase))).toEqual([]);+ });+});