Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(cycle): move the pack phase gate to cycle/pack-phase-gate.ts; keep ratchets
time-attack4ffd88976e80
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 71e3982ee0..5c81503267 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -24,3 +24,5 @@ Synthesis, patterns, consolidation and connector atom gating.- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`).- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.++- `src/core/cycle/pack-phase-gate.ts` — the extract_atoms / synthesize_concepts pack gate (#6393). `resolvePackPhaseGate(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 is `consent_required` (plus `resolved_pack`, `source_tier`) until `cycle.<phase>.enabled` is `true`; a resolution error is `pack_resolution_failed`. `packGateSkip` returns the skipped `PhaseResult` (`pack_gated: true`, the `gbrain config set cycle.<phase>.enabled true` summary) or null when the phase runs; `cycle.ts` re-exports `resolvePackPhaseGate` and `packDeclaresPhase` delegates to it. Pinned by `test/cycle-pack-gate-db-config.test.ts`.diff --git a/docs/architecture/key-files/core-cycle-primitive.md b/docs/architecture/key-files/core-cycle-primitive.mdnew file mode 100644index 0000000000..7b68bc23f3--- /dev/null+++ b/docs/architecture/key-files/core-cycle-primitive.md@@ -0,0 +1,6 @@+# Key files: Core Cycle primitive++[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/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. The extract_atoms / synthesize_concepts pack gate (#6393) is `src/core/cycle/pack-phase-gate.ts` ([Core Cycle (continued)](core-cycle-continued.md)); `packDeclaresPhase(engine, phase, sourceId?)` delegates to it.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex a57a2705ad..58d077ae30 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -25,7 +25,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. #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`.+The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cycle-primitive.md).- `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/src/commands/config.ts b/src/commands/config.tsindex 8a615ffe55..cf2d440cdd 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -1202,12 +1202,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {args.includes('--coverage-override') || args.includes('--yes');// #6290: provider_chat_options rows are one JSON object per selector; a dotted leaf would be inert.- if (key.startsWith('provider_chat_options.')) {- const { assertProviderChatOptionsSetValue } = await import('../core/config-db-merge.ts');- try { assertProviderChatOptionsSetValue(key, value); }- catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }- }-+ if (key.startsWith('provider_chat_options.')) await import('../core/config-db-merge.ts').then(m => m.assertProviderChatOptionsSetValue(key, value)).catch((error: Error) => { console.error(`[config] ${error.message}`); process.exit(1); });// #5470: every admission parses the journal caps; a malformed value// would refuse all managed writes, so reject it here.const { JOURNAL_CONFIG_KEYS, parseJournalConfigValue } = await import('../core/persistence/limits.ts');diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex ba54a2d3e1..55d1842864 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],- 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],+ 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 3ab938720b..59ba24580b 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -52,6 +52,7 @@ import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';import { tryAcquireDbLock, reapDeadHolderLocks, inspectLock, LockStolenError, type DbLockHandle } from './db-lock.ts';import { timeContainedPhase } from './cycle/phase-containment.ts';import { isManagedBrain } from './cycle/phase-table.ts';+import { packGateSkip, resolvePackPhaseGate } from './cycle/pack-phase-gate.ts';import { managedPullWarning, type UpstreamRefresh } from './sync-upstream.ts';import { assertValidSourceId } from './source-id.ts';import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';@@ -1243,52 +1244,7 @@ export async function packDeclaresPhase(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 { 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 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 { 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 } : {}),- };-}+export { resolvePackPhaseGate, type PackPhaseGate } from './cycle/pack-phase-gate.ts';async function runPhaseSync(engine: BrainEngine,@@ -2447,7 +2403,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;+ const xaSkip = engine ? await packGateSkip(engine, 'extract_atoms', cycleSourceId) : null;if (!engine) {phaseResults.push({phase: 'extract_atoms',@@ -2456,21 +2412,13 @@ export async function runCycle(summary: 'no database connected',details: { reason: 'no_database' },});- } else if (xaGate && (!xaGate.declared || xaGate.consent_required)) {+ } else if (xaSkip) {// 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// deliberately-off phase apart from a phase that ran with no work. The// backlog signal itself lives in doctor (one count, on demand).- phaseResults.push({- phase: 'extract_atoms',- status: 'skipped',- duration_ms: 0,- 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),- });+ phaseResults.push(xaSkip);} else {progress.start('cycle.extract_atoms');const { runPhaseExtractAtomsStamped: runPhaseExtractAtoms } = await import('./cycle/extract-atoms-stamp.ts');@@ -2586,7 +2534,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;+ const scSkip = engine ? await packGateSkip(engine, 'synthesize_concepts', cycleSourceId) : null;if (!engine) {phaseResults.push({phase: 'synthesize_concepts',@@ -2595,20 +2543,12 @@ export async function runCycle(summary: 'no database connected',details: { reason: 'no_database' },});- } else if (scGate && (!scGate.declared || scGate.consent_required)) {+ } else if (scSkip) {// 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// fake signal. Filed as a follow-up.)- phaseResults.push({- phase: 'synthesize_concepts',- status: 'skipped',- duration_ms: 0,- 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),- });+ phaseResults.push(scSkip);} else {progress.start('cycle.synthesize_concepts');const { runPhaseSynthesizeConcepts } = await import('./cycle/synthesize-concepts.ts');diff --git a/src/core/cycle/pack-phase-gate.ts b/src/core/cycle/pack-phase-gate.tsnew file mode 100644index 0000000000..66e5862f27--- /dev/null+++ b/src/core/cycle/pack-phase-gate.ts@@ -0,0 +1,68 @@+/**+ * #6393: the pack gate for pack-declared paid phases (extract_atoms,+ * synthesize_concepts). Resolves 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`.+ */+import type { BrainEngine } from '../engine.ts';+import type { CyclePhase, PhaseResult } from '../cycle.ts';++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;+}++export async function resolvePackPhaseGate(+ engine: BrainEngine,+ phase: CyclePhase,+ sourceId?: string,+): Promise<PackPhaseGate> {+ try {+ 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 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 { declared: false, reason: 'pack_resolution_failed' };+ }+}++const NOT_DECLARED: Partial<Record<CyclePhase, string>> = {+ extract_atoms: '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',+ synthesize_concepts: '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)',+};++/** The skipped phase result when the pack gate keeps `phase` off, else null (the phase runs). */+export async function packGateSkip(engine: BrainEngine, phase: CyclePhase, sourceId?: string): Promise<PhaseResult | null> {+ const gate = await resolvePackPhaseGate(engine, phase, sourceId);+ if (gate.declared && !gate.consent_required) return null;+ return {+ phase,+ status: 'skipped',+ duration_ms: 0,+ summary: gate.consent_required+ ? `${phase}: the active pack ${gate.resolved_pack} (from ${gate.source_tier}) declares this paid phase, which did not run before; run \`gbrain config set cycle.${phase}.enabled true\` to let the cycle run it`+ : NOT_DECLARED[phase] ?? `${phase}: active pack does not declare this phase`,+ details: {+ reason: gate.consent_required ? 'consent_required' : gate.reason ?? 'not_in_active_pack',+ pack_gated: true,+ ...(gate.resolved_pack ? { resolved_pack: gate.resolved_pack, source_tier: gate.source_tier } : {}),+ },+ };+}diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 8e87c2698f..529df336be 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1148,8 +1148,7 @@ async function runPhaseSynthesizeInner(// chunks or the markdown body. Fail-open (abort still unwinds); kill// switch: dream.synthesize.quote_verify=false.let quoteVerifyStats: QuoteVerifyStats | null = null;- let publishPending = 0;- let postprocessConflicts: PostprocessConflict[] = [];+ let publishPending = 0, postprocessConflicts: PostprocessConflict[] = [];const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);const grounding = config.quoteVerify ? await resolveGroundingDecide(engine) : undefined;if (maintenance) {@@ -1157,8 +1156,7 @@ async function runPhaseSynthesizeInner(worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal, grounding, meetingTranscriptsDir: config.meetingTranscriptsDir });writtenRefs = processed.writtenRefs;finalizedRefs = processed.finalizedRefs;- publishPending = processed.pending;- postprocessConflicts = processed.conflicts;+ [publishPending, postprocessConflicts] = [processed.pending, processed.conflicts];quoteVerifyStats = config.quoteVerify ? processed.stats : null;} else if (config.quoteVerify && writtenRefs.length > 0) {const transcriptsForVerify = new Map<string, TranscriptForVerify>(worthProcessing.map(t => [t.filePath, { content: t.content }]));