Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(cycle): fence_repair maintenance phase runs the fences repair kind, bounded per run (#6188)
garrytan2d07f8b7f0b4
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 0e3da94712..0ed796e5b5 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -43,10 +43,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.-- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps each of the 24 phases (source: safe to parallelize per source; global: must serialize across the brain; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).+- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps every `ALL_PHASES` entry (source: safe to parallelize per source; global: must serialize across the brain, so `fence_repair` and the other brain-wide phases run once in the global maintenance job and never in a per-source payload; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. One read plus bounded writes: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(slice)` in slices of 1000 rows. Between slices it checks `opts.signal` (throws → `fail`), awaits `opts.yieldDuringPhase` (cycle-lock refresh / steal detection), fires `opts.onProgress`, and yields a macrotask (`setTimeout(0)`) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; `runCycle` wires these exactly like consolidate (`racedTimePhase` + `buildYieldDuringPhase` + `cycleSignal` + `progress.tick`). Both engines' `setEmotionalWeightBatch` rewrite only rows whose weight changes (`IS DISTINCT FROM` in the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED; `details.pages_recomputed` = pages evaluated (feeds the cycle totals), `details.pages_updated` = rows changed. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.- `src/core/cycle/phase-containment.ts` — `timeContainedPhase` is the timer every `runCycle` phase runs under: a phase runner that throws returns a `fail` phase result carrying `{ class, code, message }` and `details.contained`, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; `gbrain dream` exits non-zero). Cancellation (an aborted cycle signal or `AbortError`), `LockStolenError` and `BudgetExhausted` are never contained. Successful `gateway.chat` calls inside the phase are counted through `withChatCallMeter` (`ai/chat-usage.ts`); a contained failure after at least one paid call is recorded under `dream:phase:<phase>:<source>` for `dream_paid_loop`. Tests: `test/cycle-phase-containment.test.ts`. Each phase also runs under `withAIAttribution({ phase: 'cycle:<phase>' })`, so model calls it makes carry the phase in invocation observers and `GBRAIN_AI_CALL_LOG`.+- `src/core/cycle/fence-repair.ts` — the `fence_repair` maintenance phase: `runFenceRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, registry?, now? })` runs the `fences` repair kind (`src/core/repair/fences.ts`) once through the trusted `repairRunner` (apply; a preview on a dry run) over every active source, with no rule logic of its own: the kind plans from its census, skips sources this host does not own (`owner_unavailable`) or that are mid-sync (`sync_in_progress`), reads `fences.repair.llm` and the daily USD ledger, and re-plans on the next run. `fences.repair.enabled` false skips it without calling the kind (the summary names `gbrain config set fences.repair.enabled true`). The run's deadline is min(`FENCE_REPAIR_PHASE_BUDGET_MS` = 300 s, a third of the maintenance job's remaining time), 300 s without a job deadline; past it `runRepair` stops before the next item with `time_budget` (status ok, resumed by the next run). Details read the kind's `FenceRepairVerification`: `candidates`, `repaired`, `repaired_by_tier`, `held_by_reason`, `llm_usd`, `llm_usd_per_repair`, `oldest_hold_at`/`oldest_hold_age_hours`, `llm_enabled`, `scan_partial`, `time_budget_ms`, `stopped_reason`; the summary says when Tier 3 is off and how many fences need a manual edit (`fix`: `gbrain repair fences`). Any other stop reports `warn` with the kind's fix; an internal error reports `warn` with its code only (no message, which could carry fence content) unless the cycle is aborted. Brain-global, after `sync` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-fence-repair.test.ts`.+- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex e18be6a6e3..25ca9d6d59 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 (24 phases; `ALL_PHASES` is the ordered source of truth). `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); 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`). 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, AND synthesize 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`; 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); 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`). 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`; 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/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/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex f616172f67..676ad6328b 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -151,6 +151,12 @@ phases like atoms/concepts/drift slot in between):lint -> backlinks -> sync -> synthesize -> extract -> patterns -> embed -> orphans```+`fence_repair` runs right after `sync`, once per maintenance pass: it repairs+the facts and takes fences sync held or pages store malformed (the same plan+`gbrain repair fences` previews), for at most 300 s or a third of the job's+remaining time, and resumes on the next run. Pause it with+`gbrain config set fences.repair.enabled false`.+The two new phases consolidate yesterday's conversations into long-term memory:**Synthesize phase (two-stage cascade):** reads transcripts fromdiff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex f616172f67..676ad6328b 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -151,6 +151,12 @@ phases like atoms/concepts/drift slot in between):lint -> backlinks -> sync -> synthesize -> extract -> patterns -> embed -> orphans```+`fence_repair` runs right after `sync`, once per maintenance pass: it repairs+the facts and takes fences sync held or pages store malformed (the same plan+`gbrain repair fences` previews), for at most 300 s or a third of the job's+remaining time, and resumes on the next run. Pause it with+`gbrain config set fences.repair.enabled false`.+The two new phases consolidate yesterday's conversations into long-term memory:**Synthesize phase (two-stage cascade):** reads transcripts fromdiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex a8dd5d4657..b498687355 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -30,7 +30,7 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wavsrc/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane mergesrc/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle.ts runCycle 1271 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)+src/core/cycle.ts runCycle 1277 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallbacksrc/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bd101e8c86..ea1c601d41 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field-src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)+src/core/cycle.ts 3264 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts)src/core/cycle/synthesize.ts 3207 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg)src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms promptsrc/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contractdiff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex 92b14d1937..85a0798144 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -150,6 +150,12 @@ phases like atoms/concepts/drift slot in between):lint -> backlinks -> sync -> synthesize -> extract -> patterns -> embed -> orphans```+`fence_repair` runs right after `sync`, once per maintenance pass: it repairs+the facts and takes fences sync held or pages store malformed (the same plan+`gbrain repair fences` previews), for at most 300 s or a third of the job's+remaining time, and resumes on the next run. Pause it with+`gbrain config set fences.repair.enabled false`.+The two new phases consolidate yesterday's conversations into long-term memory:**Synthesize phase (two-stage cascade):** reads transcripts fromdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex a7d660321c..5a193cb30f 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -93,7 +93,7 @@"idea-lineage/SKILL.md": "3432a9cca1626c7876eb12d7ec0d6cc37feeb8f3c18cf99f08028ef3174ae0e0","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "887d1dc43d1dd4d541172b40ce64385090813132ef80fc05c4616b5c32087448",- "maintain/SKILL.md": "5613fa8339d8760613851ae3c2b5d09cb96102177b0aa22cc147749b330f22a8",+ "maintain/SKILL.md": "401e68260f047bfe2cc7bfab358f492f4b216bf36ff3acb92cc7922dd0babdc1","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4","mcp-access/SKILL.md": "d308714208f457a9853fec4e83fe035dcd911bc8e506cefec817bd218f3340df","measure-before-you-fix/SKILL.md": "ec55bac9b8b052b854c828a4b60ec37108ecc21c8d2dcede266181026b191c2d",diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 3b23867ac6..1990f704fa 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -66,6 +66,7 @@ export { anyAbortSignal } from './abort-signals.ts';export type CyclePhase =| 'lint' | 'backlinks' | 'sync' | 'synthesize' | 'extract' | 'extract_facts'+ | 'fence_repair' // #6188: repairs held and stored malformed facts/takes fences (global maintenance lane)| 'resolve_symbol_edges'| 'patterns' | 'recompute_emotional_weight' | 'consolidate'// v0.36.1.0 Hindsight calibration wave:@@ -121,6 +122,8 @@ export const ALL_PHASES: CyclePhase[] = ['lint','backlinks','sync',+ // #6188: right after sync, so a fence the sync just held is repaired before extract and extract_facts read the page.+ 'fence_repair','synthesize','extract',// v0.32.2 — reconcile DB facts index from the `## Facts` fence on@@ -319,6 +322,7 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['lint','backlinks','sync',+ 'fence_repair', // #6188: writes repaired fences through coordinated writes'synthesize','extract',// v0.32.2 — wipes + re-inserts facts per affected page.@@ -2225,6 +2229,12 @@ export async function runCycle(await safeYield(opts.yieldBetweenPhases);}+ if (phases.includes('fence_repair')) { // #6188: one bounded run of the `fences` repair kind (src/core/cycle/fence-repair.ts)+ checkAborted(cycleSignal);+ const { result, duration_ms } = await timePhase(async () => (await import('./cycle/fence-repair.ts')).runFenceRepairPhase(engine, { dryRun, signal: cycleSignal, deadlineAtMs: opts.deadlineAtMs ?? null }), 'fence_repair');+ phaseResults.push({ ...result, duration_ms }); await safeYield(opts.yieldBetweenPhases);+ }+// ── Phase 4: synthesize (v0.23) ─────────────────────────────if (phases.includes('synthesize')) {if (!engine) {diff --git a/src/core/cycle/fence-repair.ts b/src/core/cycle/fence-repair.tsnew file mode 100644index 0000000000..3ea849f714--- /dev/null+++ b/src/core/cycle/fence-repair.ts@@ -0,0 +1,124 @@+/**+ * `fence_repair` cycle phase (#6188): one bounded run of the `fences` repair+ * kind (src/core/repair/fences.ts) in the global maintenance lane, so fences+ * that sync held and malformed fences that pages store are repaired with no+ * operator. The phase has no rule logic of its own: the kind plans from its+ * census, skips sources this host does not own (`owner_unavailable`) or that+ * are mid-sync (`sync_in_progress`), reads `fences.repair.llm` and the daily+ * USD ledger itself, and re-plans on the next run, where items already+ * repaired drop out.+ *+ * The phase gates on `fences.repair.enabled`, runs the kind through the+ * shared trusted repair runner (an apply, or a preview on a dry run) with a+ * deadline of min(300 s, a third of the maintenance job's remaining time),+ * and reports the kind's verification: candidates, repairs per tier, what is+ * still held by reason, model spend, the oldest unresolved hold's age and the+ * USD per model repair. It never fails the cycle: a stop other than the time+ * budget, or an internal error, reports `warn` with the next step. Output is+ * counts and reason codes only, never a path, claim or cell value.+ */+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';+import type { Action } from '../agent-output.ts';+import { resolveRepairScope, type RepairResult } from '../repair/core.ts';+import { repairRunner, type RepairKindSpec } from '../repair/registry.ts';+import type { FenceRepairVerification } from '../repair/fences.ts';+import { FENCE_REASONS } from '../fence-repair/reasons.ts';+import type { FenceReason } from '../fence-repair/types.ts';+import { FENCE_REPAIR_ENABLED_KEY, FENCE_REPAIR_LLM_KEY, fenceRepairEnabled, fenceRepairLlmEnabled } from '../fence-repair/config.ts';+import { isUncontainedPhaseError } from './phase-containment.ts';++/** The longest one phase run spends repairing fences; inside a maintenance job it is also at most a third of the job's remaining time. */+export const FENCE_REPAIR_PHASE_BUDGET_MS = 300_000;++export interface FenceRepairPhaseOpts {+ dryRun: boolean;+ signal?: AbortSignal;+ /** The enclosing maintenance job's absolute deadline (epoch ms); null or unset for a direct `gbrain dream`. */+ deadlineAtMs?: number | null;+ /** Replaces the registered repair kinds, as `repairRunner` takes it (tests pass stub specs). */+ registry?: readonly RepairKindSpec[];+ now?: () => number;+}++const PREVIEW = 'gbrain repair fences';+const previewFix = (why: string): Action => ({ argv: ['gbrain', 'repair', 'fences'], consent: [], actor: 'agent', why, requires_exclusive: false,+ docs: 'docs/guides/repair.md#fences' });++export async function runFenceRepairPhase(engine: BrainEngine | null, opts: FenceRepairPhaseOpts): Promise<PhaseResult> {+ const base = { phase: 'fence_repair' as const, duration_ms: 0 };+ if (!engine) return { ...base, status: 'skipped', summary: 'no database connected', details: { reason: 'no_database' } };+ if (!(await fenceRepairEnabled(engine))) {+ return { ...base, status: 'skipped', details: { reason: 'disabled' },+ summary: `fence repair is paused (${FENCE_REPAIR_ENABLED_KEY} false), so nothing was repaired. Turn it back on with `+ + `\`gbrain config set ${FENCE_REPAIR_ENABLED_KEY} true\`, or preview and apply by hand with \`${PREVIEW}\`.` };+ }+ const now = opts.now ?? Date.now;+ const start = now();+ const timeBudgetMs = opts.deadlineAtMs == null ? FENCE_REPAIR_PHASE_BUDGET_MS+ : Math.min(FENCE_REPAIR_PHASE_BUDGET_MS, Math.floor((opts.deadlineAtMs - start) / 3));+ if (timeBudgetMs <= 0) {+ return { ...base, status: 'skipped', summary: 'no maintenance-job time left for fence repair; the next run continues', details: { reason: 'deadline' } };+ }+ const llmEnabled = await fenceRepairLlmEnabled(engine);+ let result: RepairResult;+ try {+ const runner = await repairRunner(engine, { apply: !opts.dryRun, logger: { info() {}, warn: console.warn, error: console.error },+ ...(opts.registry ? { registry: opts.registry } : {}) });+ result = await runner.run('fences', await resolveRepairScope(engine), { deadline: start + timeBudgetMs });+ } catch (error) {+ if (isUncontainedPhaseError(error, opts.signal)) throw error;+ const rawCode = (error as { code?: unknown } | null)?.code;+ const code = typeof rawCode === 'string' ? rawCode : 'internal';+ return { ...base, status: 'warn', details: { reason: 'error', code, time_budget_ms: timeBudgetMs,+ fix: previewFix('The fence repair stopped on an error; the preview shows the plan and the error on the brain host.') },+ summary: `fence repair stopped on an error (${code}) and the next maintenance run retries. Run \`${PREVIEW}\` on the brain host `+ + 'to see the plan and the error; ask the user if it keeps failing.' };+ }++ const v = result.verification as Partial<FenceRepairVerification> | undefined;+ const repairedByTier = v?.repaired_by_tier ?? { deterministic: 0, resolver: 0, llm: 0 };+ const heldByReason: Record<string, number> = v?.held_by_reason ?? result.remaining ?? {};+ const candidates = v?.candidates ?? result.affected;+ const repaired = result.repaired ?? result.applied;+ const oldestHoldAt = v?.oldest_hold_at ?? null;+ const oldestHoldAgeHours = oldestHoldAt ? Math.max(0, Math.round((now() - Date.parse(oldestHoldAt)) / 3_600_000)) : null;+ const llmUsd = result.cost.llm_usd ?? null;+ const llmUsdPerRepair = v?.llm_usd_per_repair ?? null;+ const scanPartial = v?.partial ?? result.scan?.partial ?? false;+ const stopped = result.stopped;+ const held = Object.values(heldByReason).reduce((sum, n) => sum + n, 0);+ const manual = Object.entries(heldByReason).filter(([reason]) => FENCE_REASONS[reason as FenceReason]?.manualOnly).reduce((sum, [, n]) => sum + n, 0);+ const llmDisabled = heldByReason.llm_disabled ?? 0;++ const usd = (n: number | null) => n === null ? 'unpriced' : `$${n.toFixed(4)}`;+ const parts = [+ result.mode === 'dry_run' ? `dry run: ${candidates} fence candidate(s) planned, nothing written`+ : candidates === 0 && held === 0 ? 'no malformed fences to repair'+ : `repaired ${repaired} of ${candidates} fence candidate(s) (deterministic ${repairedByTier.deterministic}, resolver ${repairedByTier.resolver}, `+ + `model ${repairedByTier.llm}; ${usd(llmUsd)} on the model${llmUsdPerRepair !== null ? `, ${usd(llmUsdPerRepair)} per model repair` : ''})`,+ held ? `${held} still held (${Object.entries(heldByReason).filter(([, n]) => n).map(([reason, n]) => `${reason} ${n}`).join(', ')})` : '',+ oldestHoldAgeHours !== null ? `the oldest unresolved hold is ${oldestHoldAgeHours} h old` : '',+ ].filter(Boolean).join('; ');+ const notes = [+ stopped?.reason === 'time_budget' ? `Stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s); the next maintenance run resumes.` : '',+ stopped && stopped.reason !== 'time_budget' ? `Stopped (${stopped.reason}): ${stopped.message}` : '',+ scanPartial ? 'The fence census scan is still partial; the next run continues it.' : '',+ llmEnabled ? '' : `Model (Tier 3) repair is off (${FENCE_REPAIR_LLM_KEY} false)${llmDisabled ? `: ${llmDisabled} fence(s) wait for it; ask the user before `+ + `turning it on (\`gbrain config set ${FENCE_REPAIR_LLM_KEY} true\`, paid) or edit them by hand` : ''}.`,+ manual ? `${manual} need a manual edit: run \`${PREVIEW}\` on the brain host for each exact fix.` : '',+ ].filter(Boolean);+ const fix = stopped && stopped.reason !== 'time_budget' ? stopped.fix : manual ? previewFix('Some fences need a manual edit; the preview names each exact fix.') : undefined;+ return {+ ...base,+ status: stopped && stopped.reason !== 'time_budget' ? 'warn' : 'ok',+ summary: [`${parts}.`, ...notes].join(' '),+ details: {+ mode: result.mode, candidates, repaired, repaired_by_tier: repairedByTier, held_by_reason: heldByReason,+ llm_enabled: llmEnabled, llm_usd: llmUsd, llm_cap_remaining_usd: result.cost.llm_cap_remaining_usd ?? null,+ llm_repairs: v?.llm_repairs ?? 0, llm_usd_per_repair: llmUsdPerRepair, oldest_hold_at: oldestHoldAt, oldest_hold_age_hours: oldestHoldAgeHours,+ scan_partial: scanPartial, complete: result.complete, time_budget_ms: timeBudgetMs, stopped_reason: stopped?.reason ?? null,+ ...(stopped ? { stopped } : {}), ...(fix ? { fix } : {}),+ },+ };+}diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 46712ce6f6..3fa1ed231c 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -16,6 +16,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {lint: 'source',backlinks: 'source',sync: 'source',+ fence_repair: 'global',synthesize: 'mixed',extract: 'source',extract_facts: 'source',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex da4e1d3db5..a599ec305b 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -23,6 +23,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>lint: { class: 'writes', reason: 'Lint repairs publish through the maintenance coordinator, one page per repair; a file with no indexed page is reported and left for the next cycle.' },backlinks: { class: 'no_coordinated_write', reason: 'Audit-only: counts missing back-links and never writes files.' },sync: { class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },+ fence_repair: { class: 'writes', reason: 'Fence repairs publish through managed_file_repair (managed sources), a revision-bound put_page (database-only pages) or the legacy confined write, one coordinated write per repaired file or page.' },synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },extract: { class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },extract_facts: { class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },diff --git a/test/core/cycle.serial.test.ts b/test/core/cycle.serial.test.tsindex 879802dabf..685e41b15c 100644--- a/test/core/cycle.serial.test.ts+++ b/test/core/cycle.serial.test.ts@@ -246,6 +246,17 @@ describe('runCycle — phase selection', () => {await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['orphans'], sourceId: 'source-a' });expect(orphansOpts.at(-1)).toEqual({ sourceId: 'source-a' });});++ test('fence_repair runs right after sync; a dry run previews the fences kind and a real run applies it (#6188)', async () => {+ const dry = await runCycle(sharedEngine, { brainDir: '/tmp/brain', dryRun: true });+ const names = dry.phases.map(p => p.phase);+ expect(names.indexOf('fence_repair')).toBe(names.indexOf('sync') + 1);+ expect(dry.phases.find(p => p.phase === 'fence_repair')?.details.mode).toBe('dry_run');+ await truncateCycleLocks(sharedEngine);+ const live = await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['fence_repair'] });+ expect(live.phases).toHaveLength(1);+ expect(live.phases[0]).toMatchObject({ phase: 'fence_repair', status: 'ok', details: { mode: 'apply' } });+ });});// ─── Lock-skip for non-DB-write phase selections ──────────────────@@ -277,6 +288,15 @@ describe('runCycle — cycle lock acquire/release semantics', () => {const { rows } = await (sharedEngine as any).db.query('SELECT COUNT(*)::int AS n FROM gbrain_cycle_locks');expect(rows[0].n).toBe(0);});++ test('phases: [fence_repair] holds the cycle lock while it writes (#6188)', async () => {+ let held = -1;+ await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['fence_repair'], yieldBetweenPhases: async () => {+ const { rows } = await (sharedEngine as any).db.query(`SELECT COUNT(*)::int AS n FROM gbrain_cycle_locks WHERE id = 'gbrain-cycle'`);+ held = rows[0].n;+ } });+ expect(held).toBe(1);+ });});// ─── Lock held by another live holder ──────────────────────────────@@ -361,6 +381,7 @@ describe('runCycle — engine = null (filesystem-only mode)', () => {expect(syncPhase?.details.reason).toBe('no_database');const embedPhase = report.phases.find(p => p.phase === 'embed');expect(embedPhase?.status).toBe('skipped');+ expect(report.phases.find(p => p.phase === 'fence_repair')?.details.reason).toBe('no_database');// syncCalls + embedCalls are empty because DB-required phases skipped.expect(syncCalls.length).toBe(0);expect(embedCalls.length).toBe(0);@@ -465,7 +486,8 @@ describe('runCycle — yieldBetweenPhases hook', () => {// conversation_facts_backfill). #5876: 24 (added `chronicle` after drift).// GBRA-40 Lane D: 25 (added `facts_drain` after chronicle).// Temporal typed edges: 26 (added `edge_contradictions` after calibration_profile).- expect(hookCalls).toBe(26);+ // #6188: 27 (added `fence_repair` after sync).+ expect(hookCalls).toBe(27);});test('hook exceptions do not abort the cycle', async () => {@@ -481,7 +503,8 @@ describe('runCycle — yieldBetweenPhases hook', () => {// v0.41.11.0: 20 phases (+extract_atoms, +synthesize_concepts, +conversation_facts_backfill).// v0.41.39 (#1700) + v0.42.0.0: 22 phases (+enrich_thin, +skillopt).// #2653: 23 phases (+drift). #5876: 24 (+chronicle). GBRA-40 Lane D: 25 (+facts_drain). Temporal typed edges: 26 (+edge_contradictions).- expect(report.phases.length).toBe(26);+ // #6188: 27 (+fence_repair).+ expect(report.phases.length).toBe(27);});});diff --git a/test/cycle-fence-repair.test.ts b/test/cycle-fence-repair.test.tsnew file mode 100644index 0000000000..de657861c6--- /dev/null+++ b/test/cycle-fence-repair.test.ts@@ -0,0 +1,242 @@+/**+ * #6188 `fence_repair` maintenance phase (src/core/cycle/fence-repair.ts).+ *+ * Protects: the global maintenance lane repairs fences on its own, bounded and+ * honest. `fences.repair.enabled false` pauses it without calling the kind; the+ * run's deadline is min(300 s, a third of the maintenance job's remaining time)+ * all the way from the job handler; a run past its deadline stops with+ * `time_budget` and the next run resumes after the last committed item; the+ * report carries the kind's verification (candidates, repairs per tier, held+ * by reason, model spend, oldest hold age, USD per model repair) and says when+ * Tier 3 is off; a non-time stop or an internal error reports `warn` with the+ * next step and no error text; the phase is brain-global, after sync, and never+ * in a per-source freshness payload.+ * Fails when: the enabled gate is dropped, the budget formula or its plumbing+ * changes, the phase drops the kind's stop or verification, an error fails the+ * cycle or leaks its message, or the phase lands in a per-source lane.+ * Why new: runRepair's own tests cover the cursor and the time_budget stop for+ * direct callers; nothing covered the cycle wrapper, its gate, its budget or its+ * place in the scheduling lists. The managed phase matrix runs the real kind+ * once per engine (Postgres arm there).+ * Seams: the repair runner's existing `registry` stub-spec seam, which the phase+ * passes through (production passes none); `now` pins the deadline arithmetic;+ * bun's setSystemTime moves the clock past the deadline inside a stub apply.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, setSystemTime, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';+import { dispatchGlobalMaintenance, dispatchPerSource } from '../src/commands/autopilot-fanout.ts';+import { ALL_PHASES, GLOBAL_PHASES, MAINTENANCE_PHASES, PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, SOURCE_PHASES, normalizeQueuedSourcePhases } from '../src/core/cycle.ts';+import { CONNECTOR_SOURCE_PHASES } from '../src/core/cycle/phase-scope.ts';+import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';+import { FENCE_REPAIR_PHASE_BUDGET_MS, runFenceRepairPhase } from '../src/core/cycle/fence-repair.ts';+import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlanOptions } from '../src/core/repair/core.ts';+import type { RepairKindSpec } from '../src/core/repair/registry.ts';+import type { FenceRepairVerification } from '../src/core/repair/fences.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import type { BrainEngine } from '../src/core/engine.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++interface Stub {+ spec: RepairKindSpec;+ plans: Array<{ after: RepairCursor | null; opts?: RepairPlanOptions }>;+ applied: Array<{ id: number; deadline?: number }>;+}++/** A stub `fences` kind over `count` items that honors the core's resume cursor, like the real kind's plan. */+function stubKind(count: number, behavior: {+ onApply?: (item: RepairItem) => Partial<RepairItemOutcome> | void;+ plan?: () => never;+ verification?: Partial<FenceRepairVerification>;+} = {}): Stub {+ const items: RepairItem[] = Array.from({ length: count }, (_, id) => ({ cursor: { phase: 0, id }, source_id: 'default',+ slug: `people/alice-example-${id}`, chars: 10, action: 'repair' }));+ const stub: Stub = { plans: [], applied: [], spec: undefined as never };+ const handler: RepairHandler = {+ kind: 'fences', publication: 'projection', embeds: false,+ async plan(_engine, _scope, after, opts) {+ stub.plans.push({ after, opts });+ behavior.plan?.();+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {}, llm: { usd: 0, cap_remaining_usd: 1 }, scan: { fresh_at: null, partial: false } };+ },+ async apply(_ctx, item, opts) {+ stub.applied.push({ id: item.cursor.id, deadline: opts?.deadline });+ return { applied: true, outcome: 'repaired', detail: { tier: 'deterministic' }, ...behavior.onApply?.(item) };+ },+ ...(behavior.verification ? { async report() { return { repaired: stub.applied.length, verification: behavior.verification as Record<string, unknown> }; } } : {}),+ };+ stub.spec = { kind: 'fences', handler, summary: 'stub', embeds: 'none', checks: ['fence_integrity'], preview_bound: true, spends: 'llm' };+ return stub;+}++describe('fence_repair phase gates and budget', () => {+ test('fences.repair.enabled false skips the phase and never calls the kind', async () => {+ const stub = stubKind(2);+ await engine.setConfig('fences.repair.enabled', 'false');+ const paused = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec] });+ expect(paused.status).toBe('skipped');+ expect(paused.details.reason).toBe('disabled');+ expect(paused.summary).toContain('nothing was repaired');+ expect(paused.summary).toContain('gbrain config set fences.repair.enabled true');+ expect(stub.plans).toHaveLength(0);+ expect(stub.applied).toHaveLength(0);++ await engine.setConfig('fences.repair.enabled', 'true');+ const resumed = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec] });+ expect(resumed.status).toBe('ok');+ expect(stub.applied.map(a => a.id)).toEqual([0, 1]);+ });++ test('the deadline is min(300 s, a third of the remaining job deadline), 300 s without a job deadline', async () => {+ const t = Date.now();+ const cases: Array<[number | null, number]> = [[t + 600_000, 200_000], [t + 3_600_000, FENCE_REPAIR_PHASE_BUDGET_MS], [null, FENCE_REPAIR_PHASE_BUDGET_MS]];+ for (const [deadlineAtMs, budget] of cases) {+ const stub = stubKind(1);+ const result = await runFenceRepairPhase(engine, { dryRun: false, deadlineAtMs, registry: [stub.spec], now: () => t });+ expect(result.details.time_budget_ms).toBe(budget);+ expect(stub.plans[0]?.opts?.deadline).toBe(t + budget);+ expect(stub.applied[0]?.deadline).toBe(t + budget);+ }+ const stub = stubKind(1);+ const late = await runFenceRepairPhase(engine, { dryRun: false, deadlineAtMs: t, registry: [stub.spec], now: () => t });+ expect(late).toMatchObject({ status: 'skipped', details: { reason: 'deadline' } });+ expect(stub.plans).toHaveLength(0);+ });++ test('a run past its deadline stops with time_budget, and the next run resumes after the last committed item', async () => {+ const stub = stubKind(3, { onApply: item => { if (item.cursor.id === 0) setSystemTime(new Date(Date.now() + FENCE_REPAIR_PHASE_BUDGET_MS + 1_000)); } });+ let first;+ try { first = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec] }); }+ finally { setSystemTime(); }+ expect(first.status).toBe('ok');+ expect(first.details).toMatchObject({ stopped_reason: 'time_budget', complete: false, repaired: 1 });+ expect(first.summary).toContain('the next maintenance run resumes');+ expect(stub.applied.map(a => a.id)).toEqual([0]);++ const second = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec] });+ expect(stub.plans[1]?.after).toEqual({ phase: 0, id: 0 });+ expect(stub.applied.map(a => a.id)).toEqual([0, 1, 2]);+ expect(second.details).toMatchObject({ stopped_reason: null, complete: true });+ });++ test('a dry run previews the kind and writes nothing', async () => {+ const stub = stubKind(2);+ const result = await runFenceRepairPhase(engine, { dryRun: true, registry: [stub.spec] });+ expect(result.details).toMatchObject({ mode: 'dry_run', candidates: 2, repaired: 0 });+ expect(result.summary).toContain('dry run: 2 fence candidate(s) planned, nothing written');+ expect(stub.applied).toHaveLength(0);+ });+});++describe('fence_repair phase report', () => {+ test('aggregates the kind verification, spend and hold age, and says when Tier 3 is off', async () => {+ const t = Date.now();+ const stub = stubKind(2, {+ onApply: item => item.cursor.id === 1 ? { llm_usd: 0.012, detail: { tier: 'llm' } } : undefined,+ verification: { candidates: 5, repaired_by_tier: { deterministic: 1, resolver: 0, llm: 1 }, held_by_reason: { holder_unresolved: 1, llm_disabled: 1, missing_begin: 1 },+ oldest_hold_at: new Date(t - 26 * 3_600_000).toISOString(), llm_repairs: 1, llm_usd_per_repair: 0.012, partial: false },+ });+ await engine.setConfig('fences.repair.llm', 'false');+ const result = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec], now: () => t });+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({+ mode: 'apply', candidates: 5, repaired: 2, repaired_by_tier: { deterministic: 1, resolver: 0, llm: 1 },+ held_by_reason: { holder_unresolved: 1, llm_disabled: 1, missing_begin: 1 }, llm_usd: 0.012, llm_usd_per_repair: 0.012, llm_repairs: 1,+ oldest_hold_age_hours: 26, llm_enabled: false, scan_partial: false, stopped_reason: null,+ });+ expect(result.summary).toContain('repaired 2 of 5 fence candidate(s) (deterministic 1, resolver 0, model 1; $0.0120 on the model, $0.0120 per model repair)');+ expect(result.summary).toContain('3 still held (holder_unresolved 1, llm_disabled 1, missing_begin 1)');+ expect(result.summary).toContain('the oldest unresolved hold is 26 h old');+ expect(result.summary).toContain('Model (Tier 3) repair is off (fences.repair.llm false): 1 fence(s) wait for it');+ expect(result.summary).toContain('gbrain config set fences.repair.llm true');+ expect(result.summary).toContain('1 need a manual edit');+ expect((result.details.fix as { argv?: string[] }).argv).toEqual(['gbrain', 'repair', 'fences']);+ });++ test('a stop other than the time budget reports warn with the kind fix', async () => {+ const fix = { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<n>'], consent: ['paid' as const], actor: 'user' as const, why: 'cap', requires_exclusive: false };+ const stub = stubKind(3, { onApply: () => ({ stop: { reason: 'budget_exhausted', message: 'The daily fence repair cap is spent.', fix } }) });+ const result = await runFenceRepairPhase(engine, { dryRun: false, registry: [stub.spec] });+ expect(result.status).toBe('warn');+ expect(result.details).toMatchObject({ stopped_reason: 'budget_exhausted', fix });+ expect(result.summary).toContain('Stopped (budget_exhausted): The daily fence repair cap is spent.');+ expect(stub.applied).toHaveLength(1);+ });++ test('an internal error is contained as warn without its message; an aborted cycle still propagates', async () => {+ const failing = stubKind(1, { plan: () => { throw new OperationError('database_error' as never, 'boom SENTINEL-CELL-VALUE'); } });+ const result = await runFenceRepairPhase(engine, { dryRun: false, registry: [failing.spec] });+ expect(result).toMatchObject({ status: 'warn', details: { reason: 'error', code: 'database_error' } });+ expect(JSON.stringify(result)).not.toContain('SENTINEL-CELL-VALUE');+ expect(result.summary).toContain('gbrain repair fences');++ const controller = new AbortController();+ controller.abort();+ await expect(runFenceRepairPhase(engine, { dryRun: false, registry: [failing.spec], signal: controller.signal })).rejects.toThrow('SENTINEL-CELL-VALUE');+ });+});++describe('fence_repair scheduling lanes', () => {+ test('brain-global, right after sync, classified writes, never a source or freshness phase', () => {+ expect(PHASE_SCOPE.fence_repair).toBe('global');+ expect(ALL_PHASES.indexOf('fence_repair')).toBe(ALL_PHASES.indexOf('sync') + 1);+ expect(GLOBAL_PHASES).toContain('fence_repair');+ expect(MAINTENANCE_PHASES).toContain('fence_repair');+ expect(SOURCE_PHASES).not.toContain('fence_repair');+ expect(SOURCE_FRESHNESS_PHASES).not.toContain('fence_repair');+ expect(CONNECTOR_SOURCE_PHASES).not.toContain('fence_repair');+ expect(MANAGED_PHASE_TABLE.fence_repair.class).toBe('writes');+ expect(normalizeQueuedSourcePhases(['sync', 'fence_repair'], 'repo-a')).toEqual({ phases: ['sync'], rejected: ['fence_repair'] });+ });++ test('per-source payloads never carry fence_repair; the global maintenance payload does', async () => {+ const added: Array<{ name: string; data: { phases: string[] } }> = [];+ const fake = { kind: 'postgres' as const, listAllSources: async () => [{ id: 'repo-a', name: 'a', config: {} }, { id: 'repo-b', name: 'b', config: {} }],+ getConfig: async () => null, executeRaw: async () => [] } as unknown as BrainEngine;+ const queue = { add: async (name: string, data: { phases: string[] }) => { added.push({ name, data }); return { id: added.length }; } } as never;+ await dispatchPerSource(fake, queue, { repoPath: '/tmp', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true, emit: () => {}, log: () => {} });+ await dispatchGlobalMaintenance(fake, queue, { repoPath: '/tmp', slot: 's', timeoutMs: 1, jsonMode: true, emit: () => {}, log: () => {} });+ const perSource = added.filter(job => job.name === 'autopilot-cycle');+ expect(perSource).toHaveLength(2);+ for (const job of perSource) expect(job.data.phases).not.toContain('fence_repair');+ expect(added.find(job => job.name === 'autopilot-global-maintenance')?.data.phases).toContain('fence_repair');+ });++ test('the maintenance job hands its deadline to the phase; a queued per-source payload drops it', async () => {+ const handlers = new Map<string, (job: unknown) => Promise<any>>();+ await registerBuiltinHandlers({ register(name: string, fn: (job: unknown) => Promise<any>) { handlers.set(name, fn); } } as never, engine);+ const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-fence-repair-maintenance-'));+ const startedAt = Date.now();+ const maintenance = await handlers.get('autopilot-global-maintenance')!({ id: 6188, data: { phases: ['fence_repair'], repoPath }, signal: undefined,+ deadlineAtMs: startedAt + 600_000 });+ const phase = maintenance.report.phases.find((p: { phase: string }) => p.phase === 'fence_repair');+ expect(phase?.status).toBe('ok');+ expect(phase?.details.mode).toBe('apply');+ expect(phase?.details.time_budget_ms).toBeGreaterThan(190_000);+ expect(phase?.details.time_budget_ms).toBeLessThanOrEqual(200_000);++ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, NULL)', ['repo-a']);+ const perSource = await handlers.get('autopilot-cycle')!({ data: { source_id: 'repo-a', phases: ['sync', 'fence_repair'], pull: false }, signal: undefined });+ expect(perSource.phases_rejected_by_normalization).toEqual(['fence_repair']);+ expect(perSource.report.phases.map((p: { phase: string }) => p.phase)).not.toContain('fence_repair');+ });+});diff --git a/test/e2e/dream-cycle-phase-order-pglite.test.ts b/test/e2e/dream-cycle-phase-order-pglite.test.tsindex 958faba66d..c94f873953 100644--- a/test/e2e/dream-cycle-phase-order-pglite.test.ts+++ b/test/e2e/dream-cycle-phase-order-pglite.test.ts@@ -130,6 +130,7 @@ const EXPECTED_PHASES: CyclePhase[] = ['lint','backlinks','sync',+ 'fence_repair', // #6188 — fence repair (global maintenance lane)'synthesize','extract','extract_facts', // v0.32.2 — reconcile fence → DB facts indexdiff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 88c2bb97dd..3f3e6f5102 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1846,7 +1846,7 @@"category": "meta","details": {"counts": {- "global": 12,+ "global": 13,"mixed": 2,"source": 12},@@ -1864,6 +1864,7 @@"extract_atoms": "source","extract_facts": "source","facts_drain": "global",+ "fence_repair": "global","grade_takes": "global","lint": "source","orphans": "global",@@ -1879,7 +1880,7 @@"synthesize_concepts": "global"}},- "message": "Phase taxonomy: 12 source-scoped, 12 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 13 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex f283cc0f39..d4c5007df1 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1922,7 +1922,7 @@"category": "meta","details": {"counts": {- "global": 12,+ "global": 13,"mixed": 2,"source": 12},@@ -1940,6 +1940,7 @@"extract_atoms": "source","extract_facts": "source","facts_drain": "global",+ "fence_repair": "global","grade_takes": "global","lint": "source","orphans": "global",@@ -1955,7 +1956,7 @@"synthesize_concepts": "global"}},- "message": "Phase taxonomy: 12 source-scoped, 12 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 13 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 339d4a75fe..b7cf652d0a 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1912,7 +1912,7 @@"category": "meta","details": {"counts": {- "global": 12,+ "global": 13,"mixed": 2,"source": 12},@@ -1930,6 +1930,7 @@"extract_atoms": "source","extract_facts": "source","facts_drain": "global",+ "fence_repair": "global","grade_takes": "global","lint": "source","orphans": "global",@@ -1945,7 +1946,7 @@"synthesize_concepts": "global"}},- "message": "Phase taxonomy: 12 source-scoped, 12 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 13 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex 2061aa6796..a2f4b7970a 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -136,6 +136,15 @@ const MATRIX: Record<CyclePhase, Entry> = {expect((await engine.getPage('notes/sync-example', { sourceId }))?.compiled_truth).toContain('A synced observation.');},},+ fence_repair: {+ // The phase runs the registered `fences` kind as a trusted apply on the managed brain; with no malformed+ // fence seeded it must finish without a refusal or a stop and report the kind's (empty) result.+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'people/alice-example', page('person', 'Alice', 'A person with no fences.')),+ assert: async ({ result }) => {+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({ mode: 'apply', repaired: 0, stopped_reason: null, llm_usd: 0 });+ },+ },synthesize: {seed: async ({ engine, sourceId, root }) => {await put(engine, sourceId, 'people/example', page('note', 'Example', 'Example evidence.'));diff --git a/test/phase-scope-coverage.test.ts b/test/phase-scope-coverage.test.tsindex bfeadaedef..38b3a33e3a 100644--- a/test/phase-scope-coverage.test.ts+++ b/test/phase-scope-coverage.test.ts@@ -41,7 +41,7 @@ describe('PHASE_SCOPE coverage', () => {expect(invalid).toEqual([]);});- test('all 26 phases covered (regression on accidental omission)', () => {+ test('all 27 phases covered (regression on accidental omission)', () => {// Pin the count so a future PR that adds a phase to ALL_PHASES// without updating PHASE_SCOPE notices here too. The v0.39.1.0// master merge brought in the 17th phase (`schema-suggest`); v0.41@@ -51,8 +51,9 @@ describe('PHASE_SCOPE coverage', () => {// #2653 adds 'drift' for 23; #5876 adds 'chronicle' for 24; GBRA-40 Lane D// adds 'facts_drain' for 25.// Temporal typed edges adds 'edge_contradictions' for 26.- expect(ALL_PHASES.length).toBe(26);- expect(Object.keys(PHASE_SCOPE).length).toBe(26);+ // #6188 adds 'fence_repair' for 27.+ expect(ALL_PHASES.length).toBe(27);+ expect(Object.keys(PHASE_SCOPE).length).toBe(27);});test('embed remains global (the headline brain-wide phase)', () => {