Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): resolve the phase pack gate through DB-config tiers; newly activated paid phases wait for consent (#6393)
time-attack9fda4fa67020
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 66569744d4..27afb294b1 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.-- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged.+- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged. #6393: the extract_atoms / synthesize_concepts pack gate (`resolvePackPhaseGate`, behind `packDeclaresPhase(engine, phase, sourceId?)`) resolves through `engineSchemaInput` (DB config and per-source DB config, the tiers `gbrain schema active` uses) with the cycle's source; a phase that only a DB-config tier declares and the file-plane resolution did not skips with `reason: 'consent_required'` (plus `resolved_pack`, `source_tier`) until `cycle.<phase>.enabled` is `true`; a resolution error skips as `pack_resolution_failed`. Pinned by `test/cycle-pack-gate-db-config.test.ts`.- `src/core/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 3b47cfe03d..ca5d2252f8 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -582,6 +582,14 @@ More: [docs/guides/write-refusals.md#drain-connection-lost](../../docs/guides/wr|---|---|---|---|---|---|---|| The connector request no longer matches the stored connector intent. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### consent_required++<a id="consent_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A paid step is waiting for the user's opt-in, so it was skipped and nothing was spent. | A dream-cycle phase that a database-config schema pack newly declares (extract_atoms, synthesize_concepts) did not run before this release; resolving the pack correctly must not start paid model calls on its own (#6393). | Ask the user; with their agreement run gbrain config set cycle.<phase>.enabled true (the phase skip names the exact command). Run: gbrain schema active --json | agent | `repeat the read that failed` | 1 | no |+### consent_timeout<a id="consent_timeout"></a>diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex da16fd20b5..86665544f1 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -710,10 +710,10 @@ export async function computeExtractAtomsBacklogCheck(return { name, status: 'warn', message: 'backlog query failed (could not count eligible pages)' };}- const { packDeclaresPhase } = await import('../../../core/cycle.ts');+ const { resolvePackPhaseGate } = await import('../../../core/cycle.ts');const { extractAtomsPhaseStaleWarning } = await import('../../../core/cycle/extract-atoms-stamp.ts');- let declared = false;- try { declared = await packDeclaresPhase(engine, 'extract_atoms'); } catch { declared = false; }+ const gate = await resolvePackPhaseGate(engine, 'extract_atoms').catch(() => ({ declared: false, consent_required: false }));+ const declared = gate.declared && !gate.consent_required;if (backlog === 0) {return {@@ -727,7 +727,7 @@ export async function computeExtractAtomsBacklogCheck(// it will grow forever without a signal. WARN with the drain command.if (!declared && backlog > 10) {const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);- const fix = buildExtractAtomsBacklogFixHint(backlogBySource);+ const fix = gate.consent_required ? 'gbrain config set cycle.extract_atoms.enabled true' : buildExtractAtomsBacklogFixHint(backlogBySource);return {name, status: 'warn',message: `${backlog} pages eligible for atom extraction but the active pack does not run extract_atoms — backlog growing. Fix: ${fix}`,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 548ebfc68a..cc7e173470 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -373,6 +373,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },+ // Fix wave 13 PR3 (GBRA-57). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.152.0', text: 'The dream cycle now reads a schema pack set with `gbrain config set schema_pack` (or `schema_pack.source.<id>`) when it decides whether to run extract_atoms and synthesize_concepts, as `gbrain schema active` already did. A paid phase that only such a database-config pack declares, and that did not run before, is skipped with `consent_required` until you run `gbrain config set cycle.extract_atoms.enabled true` (or `cycle.synthesize_concepts.enabled true`); doctor `extract_atoms_backlog` names the same command.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 0ce094256f..3ab938720b 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1238,19 +1238,58 @@ export async function resolveSourceForDir(export async function packDeclaresPhase(engine: BrainEngine,phase: CyclePhase,+ sourceId?: string,): Promise<boolean> {+ return (await resolvePackPhaseGate(engine, phase, sourceId)).declared;+}++export interface PackPhaseGate {+ declared: boolean;+ resolved_pack?: string;+ source_tier?: string;+ reason?: 'pack_resolution_failed';+ /** #6393 (T4): a DB-config pack newly runs this paid phase; it waits for `cycle.<phase>.enabled true`. */+ consent_required?: boolean;+}++// #6393: resolve through the same tiers `gbrain schema active` uses (DB+// config and per-source DB config included). A paid phase that only the DB+// tiers declare, and that the file-plane resolution this gate used before+// did not, stays skipped until the operator sets `cycle.<phase>.enabled`.+export async function resolvePackPhaseGate(+ engine: BrainEngine,+ phase: CyclePhase,+ sourceId?: string,+): Promise<PackPhaseGate> {try {- const { loadActivePack } = await import('./schema-pack/load-active.ts');+ const { engineSchemaInput } = await import('./schema-pack/engine-resolution.ts');+ const { loadActivePack, resolveActivePackNameOnly } = await import('./schema-pack/load-active.ts');+ const input = await engineSchemaInput(engine, { remote: false, ...(sourceId ? { sourceId } : {}) });+ const resolved = await loadActivePack(input);+ const gate: PackPhaseGate = {+ declared: (resolved.manifest.phases ?? []).includes(phase),+ resolved_pack: resolved.manifest.name,+ source_tier: resolveActivePackNameOnly(input).source,+ };+ if (!gate.declared || (gate.source_tier !== 'db-config' && gate.source_tier !== 'per-source-db')) return gate;const { loadConfig } = await import('./config.ts');- const cfg = loadConfig();- const resolved = await loadActivePack({ cfg, remote: false });- const phases = resolved.manifest.phases ?? [];- return phases.includes(phase);+ const filePlane = await loadActivePack({ cfg: loadConfig(), remote: false }).catch(() => null);+ if ((filePlane?.manifest.phases ?? []).includes(phase)) return gate;+ if ((await engine.getConfig(`cycle.${phase}.enabled`))?.trim() === 'true') return gate;+ return { ...gate, consent_required: true };} catch {- return false;+ return { declared: false, reason: 'pack_resolution_failed' };}}+function packGateSkipDetails(gate: PackPhaseGate): Record<string, unknown> {+ const reason = gate.consent_required ? 'consent_required' : gate.reason ?? 'not_in_active_pack';+ return {+ reason, pack_gated: true,+ ...(gate.resolved_pack ? { resolved_pack: gate.resolved_pack, source_tier: gate.source_tier } : {}),+ };+}+async function runPhaseSync(engine: BrainEngine,brainDir: string,@@ -2408,6 +2447,7 @@ export async function runCycle(// or borrow_from targets.if (phases.includes('extract_atoms')) {checkAborted(cycleSignal);+ const xaGate = engine ? await resolvePackPhaseGate(engine, 'extract_atoms', cycleSourceId) : null;if (!engine) {phaseResults.push({phase: 'extract_atoms',@@ -2416,7 +2456,7 @@ export async function runCycle(summary: 'no database connected',details: { reason: 'no_database' },});- } else if (!(await packDeclaresPhase(engine, 'extract_atoms'))) {+ } else if (xaGate && (!xaGate.declared || xaGate.consent_required)) {// issue #1678: the routine cycle skip stays cheap (no per-tick backlog// count), but the detail is greppable — `pack_gated: true` lets the// `extract_atoms_backlog` doctor check / log scrapers tell a@@ -2426,8 +2466,10 @@ export async function runCycle(phase: 'extract_atoms',status: 'skipped',duration_ms: 0,- summary: 'extract_atoms: active pack does not declare this phase in its phases: list — add it or activate a lens pack that ships it (gbrain-creator / gbrain-everything); run `gbrain dream --phase extract_atoms --drain` to drain a backlog',- details: { reason: 'not_in_active_pack', pack_gated: true },+ summary: xaGate.consent_required+ ? `extract_atoms: the active pack ${xaGate.resolved_pack} (from ${xaGate.source_tier}) declares this paid phase, which did not run before; run \`gbrain config set cycle.extract_atoms.enabled true\` to let the cycle run it`+ : 'extract_atoms: active pack does not declare this phase in its phases: list — add it or activate a lens pack that ships it (gbrain-creator / gbrain-everything); run `gbrain dream --phase extract_atoms --drain` to drain a backlog',+ details: packGateSkipDetails(xaGate),});} else {progress.start('cycle.extract_atoms');@@ -2544,6 +2586,7 @@ export async function runCycle(// declared. Real body in T6 — synthesize-concepts.ts is a stub today.if (phases.includes('synthesize_concepts')) {checkAborted(cycleSignal);+ const scGate = engine ? await resolvePackPhaseGate(engine, 'synthesize_concepts', cycleSourceId) : null;if (!engine) {phaseResults.push({phase: 'synthesize_concepts',@@ -2552,7 +2595,7 @@ export async function runCycle(summary: 'no database connected',details: { reason: 'no_database' },});- } else if (!(await packDeclaresPhase(engine, 'synthesize_concepts'))) {+ } else if (scGate && (!scGate.declared || scGate.consent_required)) {// issue #1678: same greppable marker as extract_atoms. (No doctor// backlog check for synthesize_concepts this wave — Codex #12: that// phase has no real eligibility predicate yet, so a check would be a@@ -2561,8 +2604,10 @@ export async function runCycle(phase: 'synthesize_concepts',status: 'skipped',duration_ms: 0,- summary: 'synthesize_concepts: active pack does not declare this phase in its phases: list — add it or activate a lens pack that ships it (gbrain-creator / gbrain-everything)',- details: { reason: 'not_in_active_pack', pack_gated: true },+ summary: scGate.consent_required+ ? `synthesize_concepts: the active pack ${scGate.resolved_pack} (from ${scGate.source_tier}) declares this paid phase, which did not run before; run \`gbrain config set cycle.synthesize_concepts.enabled true\` to let the cycle run it`+ : 'synthesize_concepts: active pack does not declare this phase in its phases: list — add it or activate a lens pack that ships it (gbrain-creator / gbrain-everything)',+ details: packGateSkipDetails(scGate),});} else {progress.start('cycle.synthesize_concepts');diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f6df2a343f..971ee9a630 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -114,6 +114,7 @@ export const CODES = {connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },+ consent_required: { class: 'consent', summary: "A paid step is waiting for the user's opt-in, so it was skipped and nothing was spent.", why: "A dream-cycle phase that a database-config schema pack newly declares (extract_atoms, synthesize_concepts) did not run before this release; resolving the pack correctly must not start paid model calls on its own (#6393).", suggestion: 'Ask the user; with their agreement run gbrain config set cycle.<phase>.enabled true (the phase skip names the exact command).', fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows which pack is active and the tier it comes from.', requires_exclusive: false } },consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },consumers_without_heartbeat: { class: 'host_only', summary: "Running write claims on this host are stamped by a process that writes no `persistence_consumers` heartbeat row, so its liveness and mode cannot be read.", why: "Every full consumer on this release renews a heartbeat row every 10 s; a claim owner with no row is a gbrain process from before the heartbeat table (an older `serve`, jobs worker or sync CLI), which also never defers to the resident consumer, so the host may run two full consumers until it is upgraded.", docs: 'docs/guides/troubleshooting.md#consumers-without-heartbeat', suggestion: 'Upgrade and restart the process whose pid the check names (its kind and gbrain version come from the claim stamp); until then the host runs its consumer beside the resident one.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with their heartbeat rows beside the running claims and the owner each claim stamps.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'consumers_without_heartbeat', '--json'] } } },content_repair_needs_human: { class: 'caller', retryable: false, actor: 'user',diff --git a/test/cycle-pack-gate-db-config.test.ts b/test/cycle-pack-gate-db-config.test.tsnew file mode 100644index 0000000000..c93cfd590b--- /dev/null+++ b/test/cycle-pack-gate-db-config.test.ts@@ -0,0 +1,97 @@+// #6393: the cycle's pack gate resolves through the same tiers+// `gbrain schema active` uses (DB config, per-source DB config), and a paid+// phase that only those tiers newly activate waits for explicit consent+// (`cycle.<phase>.enabled true`) instead of starting silently (T4).++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { packDeclaresPhase, resolvePackPhaseGate, runCycle } from '../src/core/cycle.ts';+import { withEnv, emptyHome } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let brainDir: string;+let gbrainHome: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other-example','other-example') ON CONFLICT DO NOTHING");+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-pack-gate-db-'));+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});++beforeEach(async () => {+ gbrainHome = emptyHome();+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'schema_pack%' OR key LIKE 'cycle.%'");+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+});++const isolated = <T>(fn: () => Promise<T>) =>+ withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SCHEMA_PACK: undefined, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, fn);++describe('packDeclaresPhase reads the DB-config tiers', () => {+ test('a brain-wide DB config pack that declares the phase → true', async () => {+ await engine.setConfig('schema_pack', 'gbrain-creator');+ await isolated(async () => {+ expect(await packDeclaresPhase(engine, 'extract_atoms')).toBe(true);+ expect(await packDeclaresPhase(engine, 'synthesize_concepts')).toBe(true);+ });+ });++ test('a per-source override on another source does not leak', async () => {+ await engine.setConfig('schema_pack.source.other-example', 'gbrain-creator');+ await isolated(async () => {+ expect(await packDeclaresPhase(engine, 'extract_atoms', 'default')).toBe(false);+ expect(await packDeclaresPhase(engine, 'extract_atoms', 'other-example')).toBe(true);+ expect((await resolvePackPhaseGate(engine, 'extract_atoms', 'other-example')).source_tier).toBe('per-source-db');+ });+ });++ test('the brain-wide base pack → false', async () => {+ await engine.setConfig('schema_pack', 'gbrain-base');+ await isolated(async () => {+ expect(await packDeclaresPhase(engine, 'extract_atoms')).toBe(false);+ });+ });+});++describe('newly activated paid phases wait for consent (T4)', () => {+ test('a DB-config pack the file plane did not declare skips with consent_required and names the opt-in', async () => {+ await engine.setConfig('schema_pack', 'gbrain-creator');+ const report = await isolated(() => runCycle(engine, { brainDir, phases: ['extract_atoms', 'synthesize_concepts'], dryRun: true }));+ for (const phase of ['extract_atoms', 'synthesize_concepts']) {+ const r = report.phases.find(p => p.phase === phase);+ expect(r?.status).toBe('skipped');+ expect(r?.details).toMatchObject({ reason: 'consent_required', resolved_pack: 'gbrain-creator', source_tier: 'db-config' });+ expect(r?.summary).toContain(`gbrain config set cycle.${phase}.enabled true`);+ }+ }, 60_000);++ test('cycle.<phase>.enabled true opens the gate', async () => {+ await engine.setConfig('schema_pack', 'gbrain-creator');+ await engine.setConfig('cycle.extract_atoms.enabled', 'true');+ const report = await isolated(() => runCycle(engine, { brainDir, phases: ['extract_atoms', 'synthesize_concepts'], dryRun: true }));+ const atoms = report.phases.find(p => p.phase === 'extract_atoms');+ expect(atoms?.details?.reason).not.toBe('consent_required');+ expect(atoms?.details?.reason).not.toBe('not_in_active_pack');+ expect(report.phases.find(p => p.phase === 'synthesize_concepts')?.details?.reason).toBe('consent_required');+ }, 60_000);++ test('a pack the file plane already declared needs no new consent', async () => {+ mkdirSync(join(gbrainHome, '.gbrain'), { recursive: true });+ writeFileSync(join(gbrainHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', schema_pack: 'gbrain-creator' }));+ await engine.setConfig('schema_pack', 'gbrain-creator');+ const report = await isolated(() => runCycle(engine, { brainDir, phases: ['extract_atoms'], dryRun: true }));+ const atoms = report.phases.find(p => p.phase === 'extract_atoms');+ expect(atoms?.details?.reason).not.toBe('consent_required');+ expect(atoms?.details?.reason).not.toBe('not_in_active_pack');+ }, 60_000);+});diff --git a/test/doctor-extract-atoms-backlog.test.ts b/test/doctor-extract-atoms-backlog.test.tsindex 1c4a409176..e7e52e1a07 100644--- a/test/doctor-extract-atoms-backlog.test.ts+++ b/test/doctor-extract-atoms-backlog.test.ts@@ -127,6 +127,16 @@ describe('computeExtractAtomsBacklogCheck (issue #1678)', () => {expect((check.details as { known_approximation: string }).known_approximation).toContain('page backlog only');});+ it('a DB-config pack that newly declares the phase WARNs with the consent command (#6393)', async () => {+ for (let i = 0; i < 12; i++) await seedArticle(`article-${i}`);+ await engine.setConfig('schema_pack', 'gbrain-creator');+ const check = await withEnv({ GBRAIN_HOME: EMPTY_HOME, GBRAIN_SCHEMA_PACK: undefined }, () =>+ computeExtractAtomsBacklogCheck(engine));+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain config set cycle.extract_atoms.enabled true');+ expect(check.details?.pack_declares_phase).toBe(false);+ });+it('includes the source in the drain hint when backlog lives outside default', async () => {await addSource(engine, { id: 'gbrain-raw' });for (let i = 0; i < 11; i++) await seedArticle(`raw-article-${i}`, 'gbrain-raw');