Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(lint): managed brains publish lint repairs through the persistence coordinator (#5180)

Howard Park5b417d922f78
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 6860ca5651..08603650fe 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -20,7 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
-- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.
+- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file; a file with no indexed page, or a page that changed mid-scan, is reported as a non-fixable `managed-write-pending` issue and retried next cycle (`LintResult.write_path` / `fix_pending`; #5180).
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index a13f08269b..ce20488672 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -14,7 +14,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.
+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. `__setMaintenanceWriteWaitForTests` replaces the base wait. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
Atom completion admits replacement and revision-pinned stale-atom deletion children together.
Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 3229466bf9..3a1cb3f378 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -34,6 +34,9 @@ import type { BrainEngine } from '../core/engine.ts';
import { loadActivePack } from '../core/schema-pack/load-active.ts';
import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';
import { safeCliToken, sanitizeTypeForDisplay, storedTypeMissesPack, type TypeUsagePack } from '../core/schema-pack/type-usage.ts';
+import { pathToSlug } from '../core/sync.ts';
+import { isManagedBrain } from '../core/cycle/phase-table.ts';
+import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';
export interface LintIssue {
file: string;
@@ -514,6 +517,13 @@ export interface LintOpts {
* create + disconnect a competing module-style engine that nulls the
* shared db singleton mid-cycle. */
engine?: BrainEngine;
+ /**
+ * #5180: source id for the coordinator write path. On a managed brain
+ * (persistence enabled) fixes are published through the persistence
+ * coordinator for this source instead of written to the worktree, which
+ * the managed filesystem guard refuses. Defaults to 'default'.
+ */
+ sourceId?: string;
/**
* #1972: cooperative-abort signal. lint's per-page work is synchronous, so
* without a periodic yield the event loop can't deliver an abort and a
@@ -559,6 +569,45 @@ export interface LintResult {
total_fixed: number;
dryRun: boolean;
applied_fix: boolean;
+ /** #5180: where fixes went — the worktree (legacy), the persistence
+ * coordinator (managed brain), or nowhere (report-only / dry-run). */
+ write_path: 'filesystem' | 'coordinator' | 'none';
+ /** #5180: fixes a managed brain could not publish this run (the file has
+ * no indexed page, or the page changed mid-scan); each is reported as a
+ * non-fixable `managed-write-pending` issue and retried next cycle. */
+ fix_pending: number;
+}
+
+/**
+ * #5180: publish one lint repair through the persistence coordinator, the
+ * only writer a managed brain's worktree accepts. Resolves the page's slug
+ * the way sync does, admits the repaired markdown against the page's current
+ * revision, and returns null once the coordinator has committed it (DB row
+ * and file in one guarded write). Returns a non-fixable issue instead of
+ * throwing when the repair must wait: the file is not an indexed page of the
+ * source (README/RESOLVER and other sync-skipped files, or a stray file the
+ * coordinator never wrote), or the page changed between scan and admission.
+ * Any other failure propagates and fails the run.
+ */
+async function publishLintFix(engine: BrainEngine, authority: MaintenanceAuthority, root: string, page: string, fixed: string): Promise<LintIssue | null> {
+ const relPath = relative(root, page);
+ const slug = pathToSlug(relPath);
+ const sourceId = authority.writer.sourceId;
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if (!snapshot || snapshot.page.deleted_at) {
+ return { file: relPath, line: 1, rule: 'managed-write-pending', fixable: false,
+ message: `fix not applied: ${slug} is not an indexed page of source ${sourceId} (a managed brain only rewrites indexed pages)` };
+ }
+ try {
+ await publishMaintenancePage(engine, authority, slug, fixed, { expectedRevision: snapshot.revision });
+ return null;
+ } catch (e) {
+ if ((e as { code?: unknown } | null)?.code === 'revision_conflict') {
+ return { file: relPath, line: 1, rule: 'managed-write-pending', fixable: false,
+ message: `fix not applied: ${slug} changed while lint ran; the next cycle retries` };
+ }
+ throw e;
+ }
}
/**
@@ -575,7 +624,12 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
throw new Error(`Not found: ${opts.target}`);
}
- if (opts.engine && opts.fix && !opts.dryRun && !hasSourceFilesystemLock(opts.target)) {
+ // #5180: a managed brain's worktree belongs to the persistence coordinator —
+ // the legacy filesystem lock (and its writer guard) would refuse the whole
+ // run, so lint reads the tree lock-free there and publishes fixes through
+ // the coordinator below. Unmanaged brains keep the lock + direct writes.
+ const managed = !!opts.engine && await isManagedBrain(opts.engine);
+ if (!managed && opts.engine && opts.fix && !opts.dryRun && !hasSourceFilesystemLock(opts.target)) {
return withSourceFilesystemLock(opts.engine, opts.target, () => runLintCore(opts), { signal: opts.signal });
}
@@ -605,12 +659,26 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
// line even though the later push landed) — a single end-of-run
// multi-path commit would need a new helper.
const repoProbe = isSingleFile ? dirname(opts.target) : opts.target;
- const commitFixes = !!opts.fix && !opts.dryRun && isDurabilityHardened(repoProbe);
+ const applyFixes = !!opts.fix && !opts.dryRun;
+ // #5180: on a managed brain the coordinator commits what it publishes, so
+ // the durability commit stays on the legacy path only.
+ const commitFixes = applyFixes && !managed && isDurabilityHardened(repoProbe);
+ // #5180: the maintenance authority for coordinator writes, resolved once per
+ // run like the synthesize/patterns phases. Throws `owner_unavailable` when
+ // the managed source has no active canonical owner, which the cycle reports
+ // as the phase's failure instead of a per-page filesystem refusal.
+ const maintenance: MaintenanceAuthority | null = applyFixes && managed
+ ? await maintenancePreflight(opts.engine!, opts.sourceId ?? 'default', isSingleFile ? undefined : opts.target)
+ : null;
+ // #5180: a single-file target on a managed brain derives its slug from the owned worktree root.
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- local_path/relative_path are the operator's own worktree binding rows (persistence_host_bindings / persistence_source_bindings) that maintenancePreflight just validated with assertPhysicalRoot; the join reproduces the binding root the coordinator itself uses (prepared-maintenance.ts) and only feeds relative() for slug derivation — no filesystem operation
+ const managedRoot = !isSingleFile ? opts.target : maintenance?.binding?.local_path ? join(maintenance.binding.local_path, maintenance.binding.relative_path) : dirname(opts.target);
let totalIssues = 0;
let totalFixable = 0;
let totalFixed = 0;
let pagesWithIssues = 0;
+ let fixPending = 0;
for (let idx = 0; idx < pages.length; idx++) {
assertSourceFilesystemActive();
@@ -636,15 +704,29 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
if (opts.fix && issues.some(i => i.fixable)) {
const fixed = fixContent(content);
if (fixed !== content) {
- fixCount = issues.filter(i => i.fixable).length;
- totalFixed += fixCount;
- if (!opts.dryRun) {
+ const fixable = issues.filter(i => i.fixable).length;
+ if (!applyFixes) {
+ fixCount = fixable;
+ } else if (maintenance) {
+ // #5180: managed brain — the coordinator rewrites the page (DB row
+ // and worktree file together) or says why the repair must wait.
+ const pending = await publishLintFix(opts.engine!, maintenance, managedRoot, page, fixed);
+ if (pending) {
+ issues.push(pending);
+ totalIssues++;
+ fixPending++;
+ } else {
+ fixCount = fixable;
+ }
+ } else {
assertSourceFilesystemActive();
writeSourceFileSync(page, fixed);
if (commitFixes) {
commitWriteThroughFile(repoProbe, page, relative(repoProbe, page).replace(/\.md$/u, ''));
}
+ fixCount = fixable;
}
+ totalFixed += fixCount;
}
}
opts.onPageIssues?.(relPath, issues, fixCount);
@@ -658,6 +740,8 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
total_fixed: totalFixed,
dryRun: !!opts.dryRun,
applied_fix: !!opts.fix,
+ write_path: !applyFixes ? 'none' : maintenance ? 'coordinator' : 'filesystem',
+ fix_pending: fixPending,
};
}
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 4ae8dad37a..26bee0368e 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1012,7 +1012,7 @@ function checkAborted(signal?: AbortSignal): void {
// keyword is the minimal seam that lets behavioral tests drive the
// wrapper's result-mapping (counter → status enum + summary) without
// going through runCycle's full setup cost.
-export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: BrainEngine | null, signal?: AbortSignal): Promise<PhaseResult> {
+export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: BrainEngine | null, signal?: AbortSignal, sourceId?: string): Promise<PhaseResult> {
try {
const { runLintCore } = await import('../commands/lint.ts');
// issue #1678: pass the cycle's live engine so lint's content-sanity
@@ -1020,7 +1020,7 @@ export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: B
// 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 result = await runLintCore({ target: brainDir, fix: !(engine && await isManagedBrain(engine)), dryRun, engine: engine ?? undefined, signal });
+ const result = await runLintCore({ target: brainDir, fix: true, dryRun, engine: engine ?? undefined, signal, sourceId }); // #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);
@@ -1037,7 +1037,7 @@ export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: B
summary: dryRun
? `${issues} issue(s) found (dry-run, no writes)`
: `${fixed} fix(es) applied, ${remaining} remaining`,
- details: { issues, fixed, pages_scanned: result.pages_scanned, dryRun },
+ details: { issues, fixed, pages_scanned: result.pages_scanned, dryRun, write_path: result.write_path, fix_pending: result.fix_pending },
};
} catch (e) {
return {
@@ -2146,7 +2146,7 @@ export async function runCycle(
phaseResults.push(skipNoBrainDir('lint'));
} else {
progress.start('cycle.lint');
- const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, cycleSignal), 'lint');
+ const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, cycleSignal, cycleSourceId), 'lint');
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.ts
index 65ed1f87b6..db3e3e29d6 100644
--- a/src/core/cycle/phase-table.ts
+++ b/src/core/cycle/phase-table.ts
@@ -20,7 +20,7 @@ export type ManagedPhaseClass = 'writes' | 'no_coordinated_write' | 'managed_ski
export interface ManagedPhaseEntry { class: ManagedPhaseClass; reason: string }
export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>> = {
- lint: { class: 'no_coordinated_write', reason: 'On a managed brain lint reports issues and skips its file fixes; canonical markdown changes go through page mutations.' },
+ 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.' },
synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },
diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.ts
index 29da931867..f705daab09 100644
--- a/test/cycle-abort.test.ts
+++ b/test/cycle-abort.test.ts
@@ -180,7 +180,7 @@ describe('#1972 — complete cooperative-abort coverage', () => {
expect(body).toContain('runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, cycleSignal, cycleSourceId)');
expect(body).toMatch(/runPhaseExtractFacts\([^)]*cycleSignal\)/);
expect(body).toContain('signal: cycleSignal'); // consolidate opts
- expect(body).toContain('runPhaseLint(brainDir, dryRun, engine, cycleSignal)');
+ expect(body).toContain('runPhaseLint(brainDir, dryRun, engine, cycleSignal, cycleSourceId)'); // #5180 threads the source id after the signal
// Reaper runs at cycle start.
expect(body).toContain('reapDeadHolderLocks(engine)');
// Terminal guard: the success stamp is gated on !aborted, and the report
diff --git a/test/managed-lint.test.ts b/test/managed-lint.test.ts
new file mode 100644
index 0000000000..d229b3a822
--- /dev/null
+++ b/test/managed-lint.test.ts
@@ -0,0 +1,183 @@
+// #5180: the cycle's lint phase on a managed brain. Legacy lint writes fixed
+// files straight into the worktree, which the managed filesystem guard
+// refuses (`writer_coordinator_required`), so every per-source cycle ended
+// `partial`. On a managed brain lint now publishes each repair through the
+// persistence coordinator (DB row + worktree file in one guarded write),
+// leaves files it cannot rewrite pending instead of failing, and keeps the
+// legacy filesystem path for unmanaged brains.
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runLintCore } from '../src/commands/lint.ts';
+import { runPhaseLint } from '../src/core/cycle.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const PREAMBLE = 'Of course. Here is a detailed brain page for Jane Doe.\n\n';
+const BODY = '# Jane Doe\n\nContent that stays.\n';
+const PAGE = `---\ntitle: Jane Doe\ntype: person\n---\n${PREAMBLE}${BODY}`;
+// A page the coordinator wrote carries `ingested_at`, so lint sees TWO fixable
+// issues on it: the LLM preamble and `missing-created` (promotable from
+// `ingested_at`, #3958). A hand-written file has only the preamble to fix.
+const FIXABLE_ON_INDEXED_PAGE = 2;
+
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-managed-lint-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+async function fixture(run: (engine: BrainEngine, sourceId: string, root: string) => Promise<void>, owner = true) {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-lint-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `lint-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ if (owner) await claimWorktree(engine, sourceId, root);
+ await run(engine, sourceId, root);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+async function seed(engine: BrainEngine, sourceId: string, slug = 'people/jane-doe') {
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: PAGE, request_id: randomUUID() } });
+}
+
+async function requests(engine: BrainEngine, sourceId: string): Promise<number> {
+ return (await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).length;
+}
+
+test('managed lint publishes a repair through the coordinator: DB row and worktree file change together', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, 'people/jane-doe.md');
+ expect(readFileSync(file, 'utf8')).toContain(PREAMBLE.trim());
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const before = await requests(engine, sourceId);
+
+ const result = await runLintCore({ target: root, fix: true, engine, sourceId });
+ expect(result).toMatchObject({ pages_scanned: 1, total_fixable: FIXABLE_ON_INDEXED_PAGE, total_fixed: FIXABLE_ON_INDEXED_PAGE, fix_pending: 0, write_path: 'coordinator' });
+
+ const snapshot = (await engine.readPageSnapshot('people/jane-doe', { sourceId }))!;
+ expect(snapshot.page.compiled_truth).not.toContain('Of course');
+ expect(snapshot.page.compiled_truth).toContain('Content that stays.');
+ const onDisk = readFileSync(file, 'utf8');
+ expect(onDisk).not.toContain('Of course');
+ expect(onDisk).toContain('Content that stays.');
+ expect(await requests(engine, sourceId)).toBe(before + 1);
+
+ // A second pass finds nothing to fix and admits nothing.
+ const again = await runLintCore({ target: root, fix: true, engine, sourceId });
+ expect(again).toMatchObject({ total_fixable: 0, total_fixed: 0, fix_pending: 0 });
+ expect(await requests(engine, sourceId)).toBe(before + 1);
+ });
+}, 30_000);
+
+test('managed lint dry-run reports the fixable issue and admits nothing', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const file = join(root, 'people/jane-doe.md');
+ const bytes = readFileSync(file, 'utf8');
+ const before = await requests(engine, sourceId);
+ const result = await runLintCore({ target: root, fix: true, dryRun: true, engine, sourceId });
+ expect(result).toMatchObject({ total_fixable: FIXABLE_ON_INDEXED_PAGE, dryRun: true, write_path: 'none', fix_pending: 0 });
+ expect(readFileSync(file, 'utf8')).toBe(bytes);
+ expect(await requests(engine, sourceId)).toBe(before);
+ });
+}, 30_000);
+
+test('managed lint leaves a file with no indexed page pending instead of writing the worktree', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ mkdirSync(join(root, 'notes'));
+ const stray = join(root, 'notes/stray.md');
+ writeFileSync(stray, PAGE);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const before = await requests(engine, sourceId);
+
+ const seen: Array<{ rel: string; rules: string[] }> = [];
+ const result = await runLintCore({ target: root, fix: true, engine, sourceId,
+ onPageIssues: (rel, issues) => seen.push({ rel, rules: issues.map(i => i.rule) }) });
+ // jane-doe: 2 fixable, fixed. stray: preamble fixable but unpublishable (+1 pending issue), missing-created not promotable.
+ expect(result).toMatchObject({ pages_scanned: 2, total_fixable: FIXABLE_ON_INDEXED_PAGE + 1, total_fixed: FIXABLE_ON_INDEXED_PAGE, fix_pending: 1, write_path: 'coordinator' });
+ expect(readFileSync(stray, 'utf8')).toBe(PAGE);
+ expect(seen.find(s => s.rel === 'notes/stray.md')?.rules).toContain('managed-write-pending');
+ expect(readFileSync(join(root, 'people/jane-doe.md'), 'utf8')).not.toContain('Of course');
+ expect(await requests(engine, sourceId)).toBe(before + 1);
+ expect(await engine.readPageSnapshot('notes/stray', { sourceId })).toBeNull();
+ });
+}, 30_000);
+
+test('the cycle lint phase reports the coordinator write path and stays ok on a healthy managed brain', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const result = await runPhaseLint(root, false, engine, undefined, sourceId);
+ expect(result.status).toBe('ok');
+ expect(result.details).toMatchObject({ issues: FIXABLE_ON_INDEXED_PAGE, fixed: FIXABLE_ON_INDEXED_PAGE, write_path: 'coordinator', fix_pending: 0 });
+ expect(readFileSync(join(root, 'people/jane-doe.md'), 'utf8')).not.toContain('Of course');
+ });
+}, 30_000);
+
+test('the cycle lint phase fails without an active canonical owner and never touches the worktree', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ mkdirSync(join(root, 'people'));
+ const file = join(root, 'people/jane-doe.md');
+ writeFileSync(file, PAGE);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const result = await runPhaseLint(root, false, engine, undefined, sourceId);
+ expect(result.status).toBe('fail');
+ expect(result.error?.message).toContain('canonical owner');
+ expect(readFileSync(file, 'utf8')).toBe(PAGE);
+ expect(await requests(engine, sourceId)).toBe(0);
+ }, false);
+}, 30_000);
+
+test('unmanaged lint keeps the legacy filesystem write path', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-legacy-lint-'));
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ mkdirSync(join(dir, 'people'));
+ const file = join(dir, 'people/jane-doe.md');
+ writeFileSync(file, PAGE);
+ const result = await runLintCore({ target: dir, fix: true, engine });
+ expect(result).toMatchObject({ total_fixed: 1, fix_pending: 0, write_path: 'filesystem' });
+ expect(readFileSync(file, 'utf8')).not.toContain('Of course');
+ expect(existsSync(join(dir, '.gbrain-owner.json'))).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}, 30_000);
diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.ts
index c5f0b9ec8b..2d33838672 100644
--- a/test/managed-phase-matrix.test.ts
+++ b/test/managed-phase-matrix.test.ts
@@ -107,6 +107,12 @@ async function seedFacts(engine: BrainEngine, sourceId: string, slug: string) {
const MATRIX: Record<CyclePhase, Entry> = {
lint: {
seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/lint-example', page('note', 'Lint example', 'Body with a trailing space. \n\n\n\nToo many blank lines.')),
+ // #5180: the seeded page has a fixable issue (missing-created, promotable from its capture timestamp);
+ // the repair is admitted and committed by the coordinator, never written to the worktree by lint itself.
+ assert: async ({ engine, sourceId, result }) => {
+ expect(await committed(engine, sourceId, 'notes/lint-example')).not.toHaveLength(0);
+ expect(result.details).toMatchObject({ write_path: 'coordinator', fix_pending: 0 });
+ },
},
backlinks: {
seed: async ({ engine, sourceId }) => {