Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

lint: a diverged file on a managed brain is a pending issue, not a failed run (W-B1)

garrytan082633e9e14f
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 3a1cb3f378..a18e979352 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -37,6 +37,13 @@ import { safeCliToken, sanitizeTypeForDisplay, storedTypeMissesPack, type TypeUs
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';
+import { fileMatchesSnapshot, prepareFileTarget } from '../core/persistence/page-prepare.ts';
+import { heldFileDiagnostic, writeFailureDiagnostic } from '../core/persistence/verb-errors.ts';
+import { loadActivePackForEngine } from '../core/schema-pack/engine-resolution.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
+import { cliRenderContext, docsUrl, toAgentError, type RenderedAction } from '../core/agent-output.ts';
+import type { ParseOpts } from '../core/markdown.ts';
export interface LintIssue {
file: string;
@@ -44,6 +51,13 @@ export interface LintIssue {
rule: string;
message: string;
fixable: boolean;
+ /** A managed-brain repair that waits (`managed-write-pending`): the stable machine code. */
+ code?: 'managed_write_pending';
+ /** Why it waits: the coordinator refusal's reason (`file_database_drift`, `held_file`, `canonical_file_missing`, ...), `revision_changed` or `not_indexed`. */
+ reason?: string;
+ /** The coordinator refusal's own next step, rendered for the CLI; lint never adds one of its own. */
+ fix?: RenderedAction;
+ docs?: string;
}
/** Map of frontmatter validation codes to lint rule names. Stable across
@@ -576,35 +590,79 @@ export interface LintResult {
* 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;
+ /** The first MAX_PENDING_ISSUES of those issues with their code, reason and fix. */
+ pending_issues: LintIssue[];
+}
+
+const MAX_PENDING_ISSUES = 50;
+const MANAGED_LINT_DOCS = 'docs/guides/concurrent-writes.md#lint-repairs-waiting-on-a-managed-brain';
+
+function pendingIssue(file: string, slug: string, reason: string, error: OperationError | null, message?: string): LintIssue {
+ const envelope = error ? toAgentError(error, { transport: 'cli', command: 'lint', render: cliRenderContext() }) : null;
+ return { file, line: 1, rule: 'managed-write-pending', fixable: false, code: 'managed_write_pending', reason,
+ message: message ?? `fix not applied: ${slug}: ${envelope!.message}`,
+ ...(envelope?.fix ? { fix: envelope.fix } : {}), docs: docsUrl(MANAGED_LINT_DOCS) };
+}
+
+function refusalReason(error: OperationError): string {
+ if (error.code === 'revision_conflict') return 'revision_changed';
+ if (heldFileDiagnostic(error.message)) return 'held_file';
+ return error.detail ?? writeFailureDiagnostic(error.code, error.message).reason;
+}
+
+function changedWhileLinting(sourceId: string, slug: string): OperationError {
+ return opError('revision_conflict', 'The page changed while lint ran.',
+ `Page ${slug} in '${sourceId}' changed after lint read it, so its repair was not submitted; the next cycle lints the current revision.`,
+ { fix: readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });
}
/**
* #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.
+ * the way sync does and reads its revision BEFORE the bytes the repair is
+ * built from, so the repair only ever replaces what it read: the file must
+ * hold that revision (the coordinator's own canonical comparison) and the
+ * repair is admitted against it. Returns 'published' once the coordinator
+ * committed it (DB row and file in one guarded write), null when the file
+ * no longer needs a repair, or a non-fixable issue when the repair must
+ * wait: the file is not an indexed page of the source, the file diverged
+ * from the database (the coordinator's refusal travels unchanged: its reason
+ * and its fix), 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> {
+async function publishLintFix(engine: BrainEngine, authority: MaintenanceAuthority, root: string, page: string,
+ activePack: ParseOpts['activePack']): Promise<LintIssue | 'published' | 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)` };
+ return pendingIssue(relPath, slug, 'not_indexed', null,
+ `fix not applied: ${slug} is not an indexed page of source ${sourceId} (a managed brain only rewrites indexed pages)`);
+ }
+ const scanned = existsSync(page) ? readSourceFileSync(page, 'utf-8') : null;
+ const fixed = scanned === null ? null : fixContent(scanned);
+ if (scanned === null ? !authority.binding : fixed === scanned) return null;
+ if (authority.binding && (scanned === null || !await fileMatchesSnapshot(engine, slug, scanned, snapshot, activePack))) {
+ const current = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if (current?.revision !== snapshot.revision) return pendingIssue(relPath, slug, 'revision_changed', changedWhileLinting(sourceId, slug));
+ try {
+ await prepareFileTarget(engine, { source_id: sourceId, worktree_id: authority.binding.worktree_id, slug }, snapshot, fixed, undefined, { activePack });
+ } catch (e) {
+ if (e instanceof OperationError) return pendingIssue(relPath, slug, refusalReason(e), e);
+ throw e;
+ }
+ // No refusal: the file now holds the scanned revision again (or the page has no file to repair).
+ return scanned === null ? null : pendingIssue(relPath, slug, 'revision_changed', changedWhileLinting(sourceId, slug));
}
try {
- await publishMaintenancePage(engine, authority, slug, fixed, { expectedRevision: snapshot.revision });
- return null;
+ await publishMaintenancePage(engine, authority, slug, fixed!, { expectedRevision: snapshot.revision });
+ return 'published';
} 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` };
+ // An admitted request the coordinator refused at its own file or revision check; a source-level
+ // refusal before admission (no receipt) still fails the run.
+ if (e instanceof OperationError && (e.code === 'revision_conflict' || e.code === 'source_changed' && e.writeRequest)) {
+ return pendingIssue(relPath, slug, refusalReason(e), e);
}
throw e;
}
@@ -679,6 +737,11 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
let totalFixed = 0;
let pagesWithIssues = 0;
let fixPending = 0;
+ const pendingIssues: LintIssue[] = [];
+ // The coordinator parses files with the source's active pack; the divergence check must too.
+ const activePack = maintenance?.binding
+ ? (await loadActivePackForEngine(opts.engine!, { remote: false, sourceId: maintenance.writer.sourceId }).catch(() => null))?.manifest
+ : undefined;
for (let idx = 0; idx < pages.length; idx++) {
assertSourceFilesystemActive();
@@ -710,13 +773,14 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
} 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);
+ const outcome = await publishLintFix(opts.engine!, maintenance, managedRoot, page, activePack);
+ if (outcome === 'published') {
+ fixCount = fixable;
+ } else if (outcome) {
+ issues.push(outcome);
totalIssues++;
fixPending++;
- } else {
- fixCount = fixable;
+ if (pendingIssues.length < MAX_PENDING_ISSUES) pendingIssues.push(outcome);
}
} else {
assertSourceFilesystemActive();
@@ -742,6 +806,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
applied_fix: !!opts.fix,
write_path: !applyFixes ? 'none' : maintenance ? 'coordinator' : 'filesystem',
fix_pending: fixPending,
+ pending_issues: pendingIssues,
};
}
diff --git a/src/core/config.ts b/src/core/config.ts
index 10c5140a1b..81e017fb4b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1524,6 +1524,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #4102: off switch for the propose_takes LLM phase (default ON; the
// phase ships in the default list). Read by src/core/cycle/propose-takes.ts.
'cycle.propose_takes.enabled',
+ // Off switch for the cycle lint phase's repairs (default ON; false = report-only). Read by src/core/cycle.ts runPhaseLint.
+ 'cycle.lint_fix',
// Content sanity (v0.41)
'content_sanity.bytes_warn',
'content_sanity.bytes_block',
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index ae580fff95..987fc7f656 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1029,24 +1029,30 @@ 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: true, dryRun, engine: engine ?? undefined, signal, sourceId }); // #5180: sourceId scopes the managed-brain coordinator write path
+ // `cycle.lint_fix` (default on): only an explicit falsy value makes the phase report-only; a config
+ // read failure keeps the default. `gbrain lint --fix` is unaffected.
+ const lintFix = !/^\s*(false|0|off|no)\s*$/i.test(await engine?.getConfig('cycle.lint_fix').catch(() => null) ?? '');
+ const result = await runLintCore({ target: brainDir, fix: lintFix, 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);
// 'ok' when nothing noteworthy remains:
// - no issues at all, or
// - non-dry-run and everything fixable was fixed.
- // 'warn' when issues remain after the run.
+ // 'warn' when issues remain after the run (a managed repair left pending counts as remaining).
const status: PhaseStatus =
- issues === 0 || (!dryRun && remaining === 0) ? 'ok' : 'warn';
+ issues === 0 || (!dryRun && lintFix && remaining === 0) ? 'ok' : 'warn';
return {
phase: 'lint',
status,
duration_ms: 0, // set by caller
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, write_path: result.write_path, fix_pending: result.fix_pending },
+ : !lintFix
+ ? `${issues} issue(s) found (report-only: cycle.lint_fix=false)`
+ : `${fixed} fix(es) applied, ${remaining} remaining`,
+ 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 } : {}) },
};
} catch (e) {
return {
diff --git a/test/managed-lint.test.ts b/test/managed-lint.test.ts
index d229b3a822..b5289b9f7f 100644
--- a/test/managed-lint.test.ts
+++ b/test/managed-lint.test.ts
@@ -7,15 +7,16 @@
// 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, 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 { runLintCore, type LintIssue } 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 { writeGitHold } from '../src/core/persistence/sync-holds.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';
@@ -67,10 +68,12 @@ async function fixture(run: (engine: BrainEngine, sourceId: string, root: string
}
}
-async function seed(engine: BrainEngine, sourceId: string, slug = 'people/jane-doe') {
+async function seed(engine: BrainEngine, sourceId: string, slug = 'people/jane-doe', content = PAGE) {
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() } });
+ const current = await engine.readPageSnapshot(slug, { sourceId });
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(),
+ ...(current ? { expected_revision: current.revision } : {}) } });
}
async function requests(engine: BrainEngine, sourceId: string): Promise<number> {
@@ -181,3 +184,217 @@ test('unmanaged lint keeps the legacy filesystem write path', async () => {
}
}
}, 30_000);
+
+// ── Diverged files (P1-1): the coordinator's source_changed refusal is a pending issue, never a failed run ──
+
+const JANE = 'people/jane-doe';
+const BOB = 'people/bob-example';
+
+async function body(engine: BrainEngine, sourceId: string, slug: string): Promise<string> {
+ return (await engine.readPageSnapshot(slug, { sourceId }))!.page.compiled_truth;
+}
+
+async function lintCollecting(engine: BrainEngine, sourceId: string, root: string) {
+ const byFile = new Map<string, LintIssue[]>();
+ const result = await runLintCore({ target: root, fix: true, engine, sourceId, onPageIssues: (rel, issues) => byFile.set(rel, issues) });
+ const pending = (rel: string) => byFile.get(rel)?.find(i => i.rule === 'managed-write-pending');
+ return { result, pending };
+}
+
+/** Every pending issue carries the stable code, the guide link and never prescribes a sync. */
+function expectPendingContract(issue: LintIssue | undefined, reason: string): LintIssue {
+ expect(issue).toBeDefined();
+ expect(issue).toMatchObject({ rule: 'managed-write-pending', fixable: false, code: 'managed_write_pending', reason });
+ expect(issue!.docs).toContain('docs/guides/concurrent-writes.md#lint-repairs-waiting-on-a-managed-brain');
+ expect(issue!.fix?.argv ?? []).not.toContain('sync');
+ return issue!;
+}
+
+test('probe A: an unsynced hand edit leaves its page pending with the coordinator reconcile fix; the run fixes the other page', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ await seed(engine, sourceId, BOB, PAGE.replace('Jane Doe', 'Bob Example'));
+ const file = join(root, `${JANE}.md`);
+ const edited = `${readFileSync(file, 'utf8')}\nA hand edit not yet synced.\n`;
+ writeFileSync(file, edited);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const before = await requests(engine, sourceId);
+
+ const { result, pending } = await lintCollecting(engine, sourceId, root);
+ expect(result).toMatchObject({ pages_scanned: 2, total_fixed: FIXABLE_ON_INDEXED_PAGE, fix_pending: 1, write_path: 'coordinator' });
+ const issue = expectPendingContract(pending(`${JANE}.md`), 'file_database_drift');
+ expect(issue.fix).toMatchObject({ argv: ['gbrain', 'sources', 'reconcile', sourceId, JANE, '--brain', 'host', '--preview'], next: 'run' });
+ expect(result.pending_issues).toEqual([issue]);
+ // Neither copy of the diverged page changed, and no request was journaled for it.
+ expect(readFileSync(file, 'utf8')).toBe(edited);
+ expect(await body(engine, sourceId, JANE)).toContain('Of course');
+ expect(await body(engine, sourceId, JANE)).not.toContain('hand edit');
+ expect(await requests(engine, sourceId)).toBe(before + 1);
+ // The other page was repaired in the same run.
+ expect(await body(engine, sourceId, BOB)).not.toContain('Of course');
+ expect(readFileSync(join(root, `${BOB}.md`), 'utf8')).not.toContain('Of course');
+ });
+}, 60_000);
+
+test('probe B: a file older than the database stays pending and the newer database content survives', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ const older = readFileSync(file, 'utf8');
+ await seed(engine, sourceId, JANE, PAGE.replace('Content that stays.', 'Content that stays.\n\nA newer database line.'));
+ writeFileSync(file, older);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const { result, pending } = await lintCollecting(engine, sourceId, root);
+ expect(result).toMatchObject({ total_fixed: 0, fix_pending: 1 });
+ const issue = expectPendingContract(pending(`${JANE}.md`), 'file_database_drift');
+ expect(issue.fix?.argv).toEqual(['gbrain', 'sources', 'reconcile', sourceId, JANE, '--brain', 'host', '--preview']);
+ expect(await body(engine, sourceId, JANE)).toContain('A newer database line.');
+ expect(readFileSync(file, 'utf8')).toBe(older);
+ });
+}, 60_000);
+
+test('a file sync holds keeps the hold repair as its fix', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ writeFileSync(file, `${readFileSync(file, 'utf8')}\nHeld edit.\n`);
+ const snapshot = (await engine.readPageSnapshot(JANE, { sourceId }))!;
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ await writeGitHold(engine, { source_id: sourceId, incarnation, path: `${JANE}.md`, source_path: `${JANE}.md`, slug: JANE,
+ page_id: Number(snapshot.page.id), code: 'invalid_frontmatter', message: 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.',
+ upstream_version: 'sha-fixture', observed_at: new Date().toISOString(), run_id: 'run-1', mode: 'managed',
+ meta: { reason: 'needs_interpretation', key: 'title', line: 2, recovery_version: 1 } });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const { result, pending } = await lintCollecting(engine, sourceId, root);
+ expect(result.fix_pending).toBe(1);
+ const issue = expectPendingContract(pending(`${JANE}.md`), 'held_file');
+ expect(issue.fix?.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', sourceId, '--include-ambiguous']);
+ });
+}, 60_000);
+
+test('a canonical file removed between scan and repair is pending as canonical_file_missing', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const restore = interceptSnapshot(engine, JANE, 'before', async () => { unlinkSync(file); });
+ try {
+ const { result, pending } = await lintCollecting(engine, sourceId, root);
+ expect(result.fix_pending).toBe(1);
+ expectPendingContract(pending(`${JANE}.md`), 'canonical_file_missing');
+ expect(await body(engine, sourceId, JANE)).toContain('Of course');
+ } finally { restore(); }
+ });
+}, 60_000);
+
+/** Runs `effect` once, around lint's first revision read of `slug`: before it (the read sees the effect) or after it. */
+function interceptSnapshot(engine: BrainEngine, slug: string, when: 'before' | 'after', effect: () => Promise<void>): () => void {
+ const original = engine.readPageSnapshot;
+ let fired = false;
+ // A transaction handle inherits this property, so the read keeps its own receiver.
+ engine.readPageSnapshot = async function (this: BrainEngine, s: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {
+ if (fired || s !== slug) return original.call(this, s, opts);
+ fired = true;
+ if (when === 'before') await effect();
+ const snapshot = await original.call(this, s, opts);
+ if (when === 'after') await effect();
+ return snapshot;
+ } as BrainEngine['readPageSnapshot'];
+ return () => { engine.readPageSnapshot = original; };
+}
+
+const NEWER = PAGE.replace('Content that stays.', 'Content that stays.\n\nA concurrent publication.');
+
+test('a publication after the scan but before lint reads the revision is repaired as published, never overwritten', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const restore = interceptSnapshot(engine, JANE, 'before', () => seed(engine, sourceId, JANE, NEWER));
+ try {
+ const { result } = await lintCollecting(engine, sourceId, root);
+ expect(result.fix_pending).toBe(0);
+ } finally { restore(); }
+ const stored = await body(engine, sourceId, JANE);
+ expect(stored).toContain('A concurrent publication.');
+ expect(stored).not.toContain('Of course');
+ expect(readFileSync(join(root, `${JANE}.md`), 'utf8')).toContain('A concurrent publication.');
+ });
+}, 60_000);
+
+test('a publication between the revision read and the submission is refused as revision_changed', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const restore = interceptSnapshot(engine, JANE, 'after', () => seed(engine, sourceId, JANE, NEWER));
+ try {
+ const { result, pending } = await lintCollecting(engine, sourceId, root);
+ expect(result.fix_pending).toBe(1);
+ const issue = expectPendingContract(pending(`${JANE}.md`), 'revision_changed');
+ expect(issue.fix?.argv).toEqual(['gbrain', 'get', '--source', sourceId, '--', JANE]);
+ } finally { restore(); }
+ const stored = await body(engine, sourceId, JANE);
+ expect(stored).toContain('A concurrent publication.');
+ expect(stored).toContain('Of course');
+ });
+}, 60_000);
+
+test('fixable formatting differences are repaired, not mistaken for divergence', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ const original = readFileSync(file, 'utf8');
+ const [, frontmatter, rest] = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(original)!;
+ // Same page, other bytes: frontmatter keys reversed and the title quoted.
+ const reformatted = `---\n${frontmatter.split('\n').reverse().join('\n').replace(/^title: (.*)$/m, 'title: "$1"')}\n---\n${rest}`;
+ expect(reformatted).not.toBe(original);
+ writeFileSync(file, reformatted);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const { result } = await lintCollecting(engine, sourceId, root);
+ expect(result).toMatchObject({ total_fixed: FIXABLE_ON_INDEXED_PAGE, fix_pending: 0 });
+ expect(await body(engine, sourceId, JANE)).not.toContain('Of course');
+ });
+}, 60_000);
+
+test('a cycle with a fresh hand edit ends its lint phase at warn with one pending issue instead of failing', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ writeFileSync(file, `${readFileSync(file, 'utf8')}\nFresh hand edit.\n`);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const phase = await runPhaseLint(root, false, engine, undefined, sourceId);
+ expect(phase.status).toBe('warn');
+ expect(phase.error).toBeUndefined();
+ expect(phase.details).toMatchObject({ fixed: 0, fix_pending: 1, lint_fix: true, write_path: 'coordinator' });
+ expect((phase.details.pending as LintIssue[]).map(i => [i.code, i.reason])).toEqual([['managed_write_pending', 'file_database_drift']]);
+ });
+}, 60_000);
+
+test('cycle.lint_fix=false makes the cycle lint phase report-only; true (the default) repairs', async () => {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId);
+ const file = join(root, `${JANE}.md`);
+ const bytes = readFileSync(file, 'utf8');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const before = await requests(engine, sourceId);
+ try {
+ await engine.setConfig('cycle.lint_fix', 'false');
+ const off = await runPhaseLint(root, false, engine, undefined, sourceId);
+ expect(off.status).toBe('warn');
+ expect(off.summary).toContain('cycle.lint_fix=false');
+ expect(off.details).toMatchObject({ issues: FIXABLE_ON_INDEXED_PAGE, fixed: 0, lint_fix: false, write_path: 'none', fix_pending: 0 });
+ expect(readFileSync(file, 'utf8')).toBe(bytes);
+ expect(await requests(engine, sourceId)).toBe(before);
+
+ await engine.setConfig('cycle.lint_fix', 'true');
+ const on = await runPhaseLint(root, false, engine, undefined, sourceId);
+ expect(on.status).toBe('ok');
+ expect(on.details).toMatchObject({ fixed: FIXABLE_ON_INDEXED_PAGE, lint_fix: true, write_path: 'coordinator' });
+ expect(readFileSync(file, 'utf8')).not.toContain('Of course');
+ } finally {
+ await engine.unsetConfig('cycle.lint_fix');
+ }
+ });
+}, 60_000);