Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cycle): cycle.lint_exclude for the lint phase and minion lint handlers (#6134)

garrytan3fc5dd485e2b
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index b28c1bc5c5..76ca495d4f 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 (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); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). 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/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 83aedeb6cd..8df59c6fd9 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -284,6 +284,20 @@ makes it report-only on any brain (`details.lint_fix: false`, phase `warn`
while issues remain); `gbrain config set cycle.lint_fix true` turns repairs
back on. An explicit `gbrain lint <dir> --fix` is not affected.
+**Skip files the cycle should not lint:** `cycle.lint_exclude` (string, default
+unset = exclude nothing) is a comma-separated list of directory or file
+basenames that the cycle's lint phase and the `lint`/`lint-fix` minion jobs
+skip, matched like `gbrain lint --exclude`: whitespace is trimmed, blank entries
+are dropped, and each entry is the last part of a path (no slash).
+
+```bash
+gbrain config set cycle.lint_exclude attachments,drafts.md
+gbrain config unset cycle.lint_exclude # lint everything again
+```
+
+The phase reports the list in `details.excluded`. `config set` refuses an entry
+with a slash (`invalid_params`), because a basename match would never apply it.
+
### Roll back safely
Stop submitting new reconciliation requests first. Keep a compatible upgraded
diff --git a/src/commands/config.ts b/src/commands/config.ts
index dc61c9b86c..47f5d72415 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1204,6 +1204,12 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
}
+ // #6134: a path in cycle.lint_exclude would never match a basename.
+ if (key === 'cycle.lint_exclude') {
+ try { (await import('../core/cycle/lint-fix-setting.ts')).parseCycleLintExclude(value); }
+ catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
+ }
+
// #5254: an unknown value would silently keep refusing unbound writes.
const { UNBOUND_WRITE_KEY, parseUnboundWriteValue } = await import('../core/persistence/unbound-source.ts');
if (key === UNBOUND_WRITE_KEY) {
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 26b82b7768..dbc2631655 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -662,7 +662,7 @@ function writeLintFixOrRefusal(page: string, relPath: string, fixed: string): Li
const errno = (e as NodeJS.ErrnoException | null)?.code;
if (typeof errno !== 'string' || !UNWRITABLE_CODES.has(errno)) throw e;
const envelope = toAgentError(opError('fix_not_writable', `fix not applied: ${relPath} is not writable (${errno}); the file was left unchanged.`,
- 'Make the file writable by the user running gbrain, or pass its directory or file name to `gbrain lint --exclude`, then lint again.', {
+ 'Make the file writable by the user running gbrain, or pass its directory or file name to `gbrain lint --exclude` (for the cycle: `gbrain config set cycle.lint_exclude <name>`), then lint again.', {
why: 'Lint repairs files in place, and this file refused the write (its permissions or a read-only mount).',
fix: { consent: [], actor: 'user', requires_exclusive: false, why: 'Only the file owner can change its permissions or mount.',
user_message: `Make ${relPath} writable for gbrain, or exclude it from lint.` },
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 3b23867ac6..cfdf257000 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1023,14 +1023,14 @@ function checkAborted(signal?: AbortSignal): void {
// going through runCycle's full setup cost.
export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: BrainEngine | null, signal?: AbortSignal, sourceId?: string): Promise<PhaseResult> {
try {
- const [{ runLintCore }, { cycleLintFixEnabled }] = await Promise.all([import('../commands/lint.ts'), import('./cycle/lint-fix-setting.ts')]);
+ const [{ runLintCore }, { cycleLintFixEnabled, cycleLintExcludes }] = await Promise.all([import('../commands/lint.ts'), import('./cycle/lint-fix-setting.ts')]);
// issue #1678: pass the cycle's live engine so lint's content-sanity
// DB-plane lift REUSES it instead of creating + disconnecting a
// competing module-style engine that nulls the shared db singleton
// mid-cycle (which broke every phase after lint with a misleading
// "connect() has not been called").
- const lintFix = await cycleLintFixEnabled(engine); // `cycle.lint_fix=false`: report-only (CLI `gbrain lint --fix` unaffected)
- const result = await runLintCore({ target: brainDir, fix: lintFix, dryRun, engine: engine ?? undefined, signal, sourceId }); // #5180: sourceId scopes the managed-brain coordinator write path
+ const [lintFix, exclude] = await Promise.all([cycleLintFixEnabled(engine), cycleLintExcludes(engine)]); // `cycle.lint_fix=false`: report-only; #6134 `cycle.lint_exclude`
+ const result = await runLintCore({ target: brainDir, fix: lintFix, dryRun, engine: engine ?? undefined, signal, sourceId, exclude }); // #5180: sourceId scopes the managed-brain coordinator write path
const issues = result.total_issues ?? 0;
const fixed = result.total_fixed ?? 0;
const remaining = Math.max(0, issues - fixed);
@@ -1046,7 +1046,7 @@ export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: B
summary: dryRun
? `${issues} issue(s) found (dry-run, no writes)`
: lintFix ? `${fixed} fix(es) applied, ${remaining} remaining` : `${issues} issue(s) found (report-only: cycle.lint_fix=false)`,
- details: { issues, fixed, pages_scanned: result.pages_scanned, dryRun, lint_fix: lintFix, write_path: result.write_path, fix_pending: result.fix_pending, ...(result.pending_issues?.length ? { pending: result.pending_issues } : {}) },
+ details: { issues, fixed, pages_scanned: result.pages_scanned, dryRun, lint_fix: lintFix, excluded: exclude, write_path: result.write_path, fix_pending: result.fix_pending, ...(result.pending_issues?.length ? { pending: result.pending_issues } : {}) },
};
} catch (e) {
return {
diff --git a/src/core/cycle/lint-fix-setting.ts b/src/core/cycle/lint-fix-setting.ts
index 863d17a5de..1c8f05d142 100644
--- a/src/core/cycle/lint-fix-setting.ts
+++ b/src/core/cycle/lint-fix-setting.ts
@@ -1,4 +1,5 @@
import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
/**
* `cycle.lint_fix` (default on): only an explicit falsy value makes the
@@ -9,3 +10,34 @@ import type { BrainEngine } from '../engine.ts';
export async function cycleLintFixEnabled(engine?: BrainEngine | null): Promise<boolean> {
return !/^\s*(false|0|off|no)\s*$/i.test(await engine?.getConfig('cycle.lint_fix').catch(() => null) ?? '');
}
+
+export const CYCLE_LINT_EXCLUDE_KEY = 'cycle.lint_exclude';
+
+/**
+ * #6134: `cycle.lint_exclude` is a comma-separated list of directory or file
+ * basenames the cycle's lint phase and the minion lint handlers skip, matched
+ * like `gbrain lint --exclude`. Whitespace is trimmed and blank entries are
+ * dropped; unset excludes nothing. `config set` refuses a path, which a
+ * basename match would never apply.
+ */
+export function parseCycleLintExclude(raw: string): string[] {
+ const names = raw.split(',').map(s => s.trim()).filter(Boolean);
+ if (!names.some(name => /[\\/]/.test(name))) return names;
+ throw opError('invalid_params', `Invalid ${CYCLE_LINT_EXCLUDE_KEY}: expected comma-separated basenames, not paths.`,
+ `Set ${CYCLE_LINT_EXCLUDE_KEY} to directory or file names without a slash, for example: gbrain config set ${CYCLE_LINT_EXCLUDE_KEY} attachments,drafts.md`, {
+ why: 'Lint matches each entry against one directory or file name at a time, so an entry with a slash would never apply. Nothing was written.',
+ fix: {
+ argv: ['gbrain', 'config', 'set', CYCLE_LINT_EXCLUDE_KEY, '<NAMES>'],
+ inputs: [{ name: 'NAMES', how: 'Comma-separated directory or file basenames to skip (the last part of each path); ask the user when unclear.' }],
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The next lint phase skips the named directories and files.',
+ verify: { argv: ['gbrain', 'config', 'get', CYCLE_LINT_EXCLUDE_KEY] },
+ },
+ });
+}
+
+/** The cycle's lint excludes; an unreadable setting or an entry with a slash (written with --force) contributes nothing. */
+export async function cycleLintExcludes(engine?: BrainEngine | null): Promise<string[]> {
+ const raw = await engine?.getConfig(CYCLE_LINT_EXCLUDE_KEY).catch(() => null) ?? '';
+ return raw.split(',').map(s => s.trim()).filter(name => name && !/[\\/]/.test(name));
+}
diff --git a/src/core/minions/handlers/lint-fix.ts b/src/core/minions/handlers/lint-fix.ts
index 34c897c087..32a22a9a98 100644
--- a/src/core/minions/handlers/lint-fix.ts
+++ b/src/core/minions/handlers/lint-fix.ts
@@ -13,8 +13,9 @@ import type { MinionHandler } from '../types.ts';
export function makeLintFixHandler(engine: BrainEngine): MinionHandler {
return async (job) => {
const { runLintCore } = await import('../../../commands/lint.ts');
+ const { cycleLintExcludes } = await import('../../cycle/lint-fix-setting.ts');
const target = typeof job.data.dir === 'string' ? job.data.dir : '.';
- // issue #1678: reuse the worker's live engine (see 'lint' handler).
- return await runLintCore({ target, fix: true, dryRun: false, engine, signal: job.signal });
+ // issue #1678: reuse the worker's live engine (see 'lint' handler). #6134: honors cycle.lint_exclude.
+ return await runLintCore({ target, fix: true, dryRun: false, engine, signal: job.signal, exclude: await cycleLintExcludes(engine) });
};
}
diff --git a/src/core/minions/handlers/lint.ts b/src/core/minions/handlers/lint.ts
index 1a9c14dfb7..4e32158afb 100644
--- a/src/core/minions/handlers/lint.ts
+++ b/src/core/minions/handlers/lint.ts
@@ -7,10 +7,12 @@ import type { MinionHandler } from '../types.ts';
export function makeLintHandler(engine: BrainEngine): MinionHandler {
return async (job) => {
const { runLintCore } = await import('../../../commands/lint.ts');
+ const { cycleLintExcludes } = await import('../../cycle/lint-fix-setting.ts');
const target = typeof job.data.dir === 'string' ? job.data.dir : '.';
// issue #1678: reuse the worker's live engine for lint's content-sanity
// DB lift so it doesn't create + disconnect a competing engine.
- const result = await runLintCore({ target, fix: !!job.data.fix, dryRun: !!job.data.dryRun, engine, signal: job.signal });
+ // #6134: honors cycle.lint_exclude like the cycle's lint phase.
+ const result = await runLintCore({ target, fix: !!job.data.fix, dryRun: !!job.data.dryRun, engine, signal: job.signal, exclude: await cycleLintExcludes(engine) });
return result;
};
}
diff --git a/test/cycle-legacy-phases.test.ts b/test/cycle-legacy-phases.test.ts
index cd15fd3039..3beff07ae9 100644
--- a/test/cycle-legacy-phases.test.ts
+++ b/test/cycle-legacy-phases.test.ts
@@ -17,12 +17,15 @@
* describes here rather than 7 nearly-identical files.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { runPhaseLint, runPhaseBacklinks } from '../src/core/cycle.ts';
+import { makeLintHandler } from '../src/core/minions/handlers/lint.ts';
+import { makeLintFixHandler } from '../src/core/minions/handlers/lint-fix.ts';
+import { parseCycleLintExclude } from '../src/core/cycle/lint-fix-setting.ts';
let engine: PGLiteEngine;
let brainDir: string;
@@ -111,6 +114,62 @@ describe('runPhaseLint — result-mapping', () => {
});
});
+// #6134: the cycle and the minion lint handlers honor cycle.lint_exclude (basenames, like `gbrain lint --exclude`).
+describe('cycle.lint_exclude (#6134)', () => {
+ const README = 'Attachments for the deck, not a brain page.\n';
+ function seedAttachments(): void {
+ mkdirSync(join(brainDir, 'attachments'), { recursive: true });
+ writeFileSync(join(brainDir, 'attachments', 'README.md'), README);
+ }
+
+ test('an excluded directory is neither reported nor rewritten by the lint phase', async () => {
+ try {
+ seedAttachments();
+ await engine.setConfig('cycle.lint_exclude', ' attachments , ');
+ const result = await runPhaseLint(brainDir, false, engine);
+ expect(result.status).toBe('ok');
+ expect(result.details).toMatchObject({ issues: 0, excluded: ['attachments'] });
+ expect(readFileSync(join(brainDir, 'attachments', 'README.md'), 'utf8')).toBe(README);
+ } finally {
+ cleanupBrain();
+ }
+ });
+
+ test('a blank value excludes nothing', async () => {
+ try {
+ seedAttachments();
+ await engine.setConfig('cycle.lint_exclude', ' , ');
+ const result = await runPhaseLint(brainDir, true, engine);
+ expect((result.details as { issues: number }).issues).toBeGreaterThan(0);
+ expect(result.details).toMatchObject({ excluded: [] });
+ } finally {
+ cleanupBrain();
+ }
+ });
+
+ test('the minion lint and lint-fix handlers read the same setting', async () => {
+ try {
+ seedAttachments();
+ await engine.setConfig('cycle.lint_exclude', 'attachments');
+ const job = { data: { dir: brainDir }, signal: new AbortController().signal } as unknown as Parameters<ReturnType<typeof makeLintHandler>>[0];
+ const linted = await makeLintHandler(engine)(job) as { total_issues: number };
+ expect(linted.total_issues).toBe(0);
+ await makeLintFixHandler(engine)(job);
+ expect(readFileSync(join(brainDir, 'attachments', 'README.md'), 'utf8')).toBe(README);
+ } finally {
+ cleanupBrain();
+ }
+ });
+
+ test('config set refuses a path where a basename belongs', () => {
+ expect(parseCycleLintExclude(' attachments , drafts ,')).toEqual(['attachments', 'drafts']);
+ let err: unknown;
+ try { parseCycleLintExclude('wiki/attachments'); } catch (e) { err = e; }
+ expect((err as { code?: string }).code).toBe('invalid_params');
+ expect((err as { fix?: { argv?: string[] } }).fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'config', 'set', 'cycle.lint_exclude']);
+ });
+});
+
describe('runPhaseBacklinks — result-mapping', () => {
test('clean brain (no markdown files) → status="ok" with "no missing" summary', async () => {
try {