Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

lint: a listed file removed before its scan read no longer aborts the run

garrytan4425590da46f
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index a18e979352..2f41aa98c7 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -42,7 +42,8 @@ import { heldFileDiagnostic, writeFailureDiagnostic } from '../core/persistence/
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 { ERROR_CATALOGUE } from '../core/error-catalogue.ts';
+import { cliRenderContext, docsUrl, renderAction, toAgentError, type RenderedAction } from '../core/agent-output.ts';
import type { ParseOpts } from '../core/markdown.ts';
export interface LintIssue {
@@ -51,8 +52,8 @@ 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';
+ /** The stable machine code: a managed-brain repair that waits, or a listed file removed before lint read it. */
+ code?: 'managed_write_pending' | 'file_removed_during_scan';
/** 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. */
@@ -604,6 +605,15 @@ function pendingIssue(file: string, slug: string, reason: string, error: Operati
...(envelope?.fix ? { fix: envelope.fix } : {}), docs: docsUrl(MANAGED_LINT_DOCS) };
}
+/** A file the scan listed was gone by its scan read (deleted or renamed concurrently); the rest of the run continues. */
+function removedDuringScanIssue(file: string, target: string): LintIssue {
+ return { file, line: 1, rule: 'file-removed-during-scan', fixable: false, code: 'file_removed_during_scan',
+ message: `${file} was removed after lint listed it and before lint read it, so it was not linted. Re-run lint to check the files that exist now.`,
+ fix: renderAction({ argv: ['gbrain', 'lint', target], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Lists the tree again and lints the files present now.' }, cliRenderContext()),
+ docs: docsUrl(ERROR_CATALOGUE.file_removed_during_scan.docs) };
+}
+
function refusalReason(error: OperationError): string {
if (error.code === 'revision_conflict') return 'revision_changed';
if (heldFileDiagnostic(error.message)) return 'held_file';
@@ -754,8 +764,25 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
if (isAborted(opts.signal)) break;
await new Promise<void>((resolve) => setImmediate(resolve));
}
- const content = readSourceFileSync(page, 'utf-8');
const relPath = isSingleFile ? page : relative(opts.target, page);
+ let content: string;
+ try {
+ content = readSourceFileSync(page, 'utf-8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ // #5180: a managed --fix run asks the coordinator, which reports the page's missing canonical file as pending.
+ const pending = maintenance ? await publishLintFix(opts.engine!, maintenance, managedRoot, page, activePack) : null;
+ const issue = pending && pending !== 'published' ? pending : removedDuringScanIssue(relPath, opts.target);
+ opts.onPageScanned?.();
+ pagesWithIssues++;
+ totalIssues++;
+ if (issue.code === 'managed_write_pending') {
+ fixPending++;
+ if (pendingIssues.length < MAX_PENDING_ISSUES) pendingIssues.push(issue);
+ }
+ opts.onPageIssues?.(relPath, [issue], 0);
+ continue;
+ }
const issues = lintContent(content, relPath, lintOpts);
opts.onPageScanned?.();
if (issues.length === 0) continue;
@@ -867,6 +894,8 @@ export async function runLint(args: string[]) {
for (const issue of issues) {
const fixLabel = issue.fixable ? ' [fixable]' : '';
console.log(` L${issue.line} ${issue.rule}: ${issue.message}${fixLabel}`);
+ if (issue.fix?.command) console.log(` Fix: ${issue.fix.command}`);
+ if (issue.docs) console.log(` Docs: ${issue.docs}`);
}
if (fixedCount > 0) {
console.log(` ${dryRun ? '(dry run) ' : ''}Fixed ${fixedCount} issue(s)`);
diff --git a/test/lint-file-removed-during-scan.test.ts b/test/lint-file-removed-during-scan.test.ts
new file mode 100644
index 0000000000..5ba1f9bb4f
--- /dev/null
+++ b/test/lint-file-removed-during-scan.test.ts
@@ -0,0 +1,64 @@
+// A file lint listed can be deleted or renamed before lint reads it (a concurrent sync, an editor's
+// atomic save). Lint reports `file_removed_during_scan` for that file and lints the rest; any other
+// read error still fails the run. Managed `--fix` runs report the coordinator's
+// `canonical_file_missing` instead (test/managed-lint.test.ts).
+import { afterEach, beforeEach, expect, test } from 'bun:test';
+import { chmodSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runLint, runLintCore, type LintIssue } from '../src/commands/lint.ts';
+
+const SANITY_OFF = { disabled: true } as never;
+const PREAMBLE_PAGE = (title: string) => `---\ntitle: ${title}\ntype: note\ncreated: 2026-01-05\n---\nOf course. Here is a detailed brain page for ${title}.\n\n# ${title}\n\nBody.\n`;
+let dir: string;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-lint-vanish-'));
+ writeFileSync(join(dir, 'a-first.md'), PREAMBLE_PAGE('First'));
+ writeFileSync(join(dir, 'b-vanishing.md'), PREAMBLE_PAGE('Vanishing'));
+ writeFileSync(join(dir, 'c-last.md'), PREAMBLE_PAGE('Last'));
+});
+afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+for (const fix of [false, true]) {
+ test(`unmanaged lint${fix ? ' --fix' : ''}: a listed file removed before its scan read is reported and the run continues`, async () => {
+ const byFile = new Map<string, LintIssue[]>();
+ let scanned = 0;
+ const result = await runLintCore({ target: dir, fix, contentSanity: SANITY_OFF, typePack: null,
+ onPageScanned: () => { if (scanned++ === 0) unlinkSync(join(dir, 'b-vanishing.md')); },
+ onPageIssues: (rel, issues) => byFile.set(rel, issues) });
+ expect(byFile.get('b-vanishing.md')).toEqual([{
+ file: 'b-vanishing.md', line: 1, rule: 'file-removed-during-scan', fixable: false, code: 'file_removed_during_scan',
+ message: 'b-vanishing.md was removed after lint listed it and before lint read it, so it was not linted. Re-run lint to check the files that exist now.',
+ fix: expect.objectContaining({ argv: ['gbrain', 'lint', dir], command: `gbrain lint ${dir}`, next: 'run' }),
+ docs: expect.stringContaining('docs/guides/repair.md#file-removed-during-scan'),
+ }]);
+ expect(byFile.has('c-last.md')).toBe(true);
+ expect(result.pages_scanned).toBe(3);
+ expect(result.fix_pending).toBe(0);
+ if (fix) expect(result.total_fixed).toBeGreaterThan(0);
+ });
+}
+
+test('the lint CLI prints the vanished file with its fix command and guide', async () => {
+ const logged: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => {
+ const line = a.join(' ');
+ if (line.includes('a-first.md:')) unlinkSync(join(dir, 'b-vanishing.md'));
+ logged.push(line);
+ };
+ try { await runLint([dir]); } finally { console.log = orig; }
+ const out = logged.join('\n');
+ expect(out).toContain('\nb-vanishing.md:\n L1 file-removed-during-scan: b-vanishing.md was removed after lint listed it and before lint read it, so it was not linted. Re-run lint to check the files that exist now.\n'
+ + ` Fix: gbrain lint ${dir}\n Docs: `);
+ expect(out).toContain('docs/guides/repair.md#file-removed-during-scan');
+ expect(out).toContain('3 pages scanned.');
+});
+
+test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('an unreadable file still fails the run (only ENOENT is a vanished file)', async () => {
+ chmodSync(join(dir, 'b-vanishing.md'), 0o000);
+ try {
+ await expect(runLintCore({ target: dir, contentSanity: SANITY_OFF, typePack: null })).rejects.toMatchObject({ code: 'EACCES' });
+ } finally { chmodSync(join(dir, 'b-vanishing.md'), 0o644); }
+});
diff --git a/test/managed-lint.test.ts b/test/managed-lint.test.ts
index b5289b9f7f..284defcf38 100644
--- a/test/managed-lint.test.ts
+++ b/test/managed-lint.test.ts
@@ -289,13 +289,43 @@ test('a canonical file removed between scan and repair is pending as canonical_f
});
}, 60_000);
-/** Runs `effect` once, around lint's first revision read of `slug`: before it (the read sees the effect) or after it. */
+test('a listed canonical file removed before its scan read: managed --fix reports canonical_file_missing, report-only reports file_removed_during_scan', async () => {
+ for (const fix of [true, false]) {
+ await fixture(async (engine, sourceId, root) => {
+ await seed(engine, sourceId, BOB, PAGE.replace(/Jane Doe/g, 'Bob Example'));
+ await seed(engine, sourceId);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const byFile = new Map<string, LintIssue[]>();
+ let scanned = 0;
+ const result = await runLintCore({ target: root, fix, engine, sourceId, onPageIssues: (rel, issues) => byFile.set(rel, issues),
+ onPageScanned: () => { if (scanned++ === 0) unlinkSync(join(root, `${JANE}.md`)); } });
+ expect(result.pages_scanned).toBe(2);
+ if (fix) {
+ expect(result.fix_pending).toBe(1);
+ expect(result.pending_issues).toEqual([expectPendingContract(byFile.get(`${JANE}.md`)?.[0], 'canonical_file_missing')]);
+ expect(await body(engine, sourceId, JANE)).toContain('Of course');
+ expect(await body(engine, sourceId, BOB)).not.toContain('Of course');
+ } else {
+ expect(result.fix_pending).toBe(0);
+ expect(byFile.get(`${JANE}.md`)).toEqual([expect.objectContaining({ rule: 'file-removed-during-scan', code: 'file_removed_during_scan', fixable: false,
+ fix: expect.objectContaining({ argv: ['gbrain', 'lint', root] }) })]);
+ }
+ });
+ }
+}, 60_000);
+
+/**
+ * Runs `effect` once, around lint's first revision read of `slug` (in publishLintFix, after the scan read):
+ * before it (the read sees the effect) or after it. The persistence consumer that lint's preflight starts
+ * reads page snapshots through the same engine (the seeded page's embedding effect), so only lint's own
+ * read counts; a background read must never fire the effect before the scan.
+ */
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);
+ if (fired || s !== slug || !new Error().stack?.includes('publishLintFix')) return original.call(this, s, opts);
fired = true;
if (when === 'before') await effect();
const snapshot = await original.call(this, s, opts);