Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(lint): anchor llm-preamble to the page body start; contain unwritable fix targets (#5976)

time-attack3694e1caec21
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index a18e979352..b7f83c1cec 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -51,11 +51,11 @@ 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`. */
+ /** A repair that was not applied: `managed_write_pending` (a managed brain's coordinator) or `fix_not_writable` (the file refused the write). */
+ code?: 'managed_write_pending' | 'fix_not_writable';
+ /** Why: the coordinator refusal's reason (`file_database_drift`, `held_file`, `canonical_file_missing`, ...), `revision_changed`, `not_indexed`, or the lowercased errno (`eacces`, `eperm`, `erofs`). */
reason?: string;
- /** The coordinator refusal's own next step, rendered for the CLI; lint never adds one of its own. */
+ /** The next step, rendered for the CLI: the coordinator refusal's own fix, or the owner's permission fix. */
fix?: RenderedAction;
docs?: string;
}
@@ -82,15 +82,43 @@ const FRONTMATTER_FIXABLE: ReadonlySet<ParseValidationCode> = new Set<ParseValid
// ── LLM artifact patterns ──────────────────────────────────────────
+// Anchored to the start of the page body (no `g`/`m` flags): an LLM prepends
+// a preamble to its output, so a line further down that merely begins
+// "Sure! Here is..." (a quoted reply, a transcript turn) is real content.
const LLM_PREAMBLES = [
- /^Of course\.?\s*Here is (?:a |the )?(?:detailed |comprehensive |updated )?(?:brain )?page[^.\n]*\.?\s*\n*/gim,
- /^Certainly\.?\s*Here is[^.\n]*\.?\s*\n*/gim,
- /^Here is (?:a |the )?(?:detailed |comprehensive |updated )?(?:brain )?page[^.\n]*\.?\s*\n*/gim,
- /^I've (?:created|updated|written|prepared) (?:a |the )?(?:detailed |comprehensive )?(?:brain )?page[^.\n]*\.?\s*\n*/gim,
- /^Sure(?:!|,)?\s*Here (?:is|are)[^.\n]*\.?\s*\n*/gim,
- /^Absolutely\.?\s*Here[^.\n]*\.?\s*\n*/gim,
+ /^Of course\.?\s*Here is (?:a |the )?(?:detailed |comprehensive |updated )?(?:brain )?page[^.\n]*\.?\s*\n*/i,
+ /^Certainly\.?\s*Here is[^.\n]*\.?\s*\n*/i,
+ /^Here is (?:a |the )?(?:detailed |comprehensive |updated )?(?:brain )?page[^.\n]*\.?\s*\n*/i,
+ /^I've (?:created|updated|written|prepared) (?:a |the )?(?:detailed |comprehensive )?(?:brain )?page[^.\n]*\.?\s*\n*/i,
+ /^Sure(?:!|,)?\s*Here (?:is|are)[^.\n]*\.?\s*\n*/i,
+ /^Absolutely\.?\s*Here[^.\n]*\.?\s*\n*/i,
];
+const LEADING_FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
+const LEADING_MARKDOWN_FENCE = /^```(?:markdown|md)[ \t]*\r?\n/;
+
+/**
+ * The leading LLM preamble run (stacked preamble lines) at a body start: the
+ * top of the file, right after a leading frontmatter block, or right after a
+ * whole-page ```markdown wrapper, leading blank lines skipped. Returns the
+ * [start, end) span to remove, or null. Detection and repair both use it.
+ */
+function findLeadingPreamble(content: string): { start: number; end: number } | null {
+ const skipBlank = (i: number) => i + (/^\s*/.exec(content.slice(i))?.[0].length ?? 0);
+ const anchors = [0, LEADING_FRONTMATTER.exec(content)?.[0].length, LEADING_MARKDOWN_FENCE.exec(content)?.[0].length]
+ .filter((a): a is number => a !== undefined).map(skipBlank);
+ for (const start of anchors) {
+ let end = start;
+ for (let guard = 0; guard < 16; guard++) {
+ const hit = LLM_PREAMBLES.map(p => p.exec(content.slice(end))).find(m => m && m[0].length > 0);
+ if (!hit) break;
+ end += hit[0].length;
+ }
+ if (end > start) return { start, end };
+ }
+ return null;
+}
+
// ── Rules ──────────────────────────────────────────────────────────
/**
@@ -144,16 +172,14 @@ export function lintContent(content: string, filePath: string, opts: LintContent
});
}
- // Rule: LLM preamble artifacts
- for (const pattern of LLM_PREAMBLES) {
- pattern.lastIndex = 0;
- if (pattern.test(content)) {
- issues.push({
- file: filePath, line: 1, rule: 'llm-preamble',
- message: 'LLM preamble artifact detected (e.g., "Of course! Here is...")',
- fixable: true,
- });
- }
+ // Rule: LLM preamble artifacts (only a leading run; see findLeadingPreamble)
+ const preamble = findLeadingPreamble(content);
+ if (preamble) {
+ issues.push({
+ file: filePath, line: content.slice(0, preamble.start).split('\n').length, rule: 'llm-preamble',
+ message: 'LLM preamble artifact detected (e.g., "Of course! Here is...")',
+ fixable: true,
+ });
}
// Rule: Wrapping code fences (```markdown ... ```)
@@ -370,11 +396,9 @@ export function promoteCreatedFromCapture(content: string): string {
export function fixContent(content: string): string {
let fixed = content;
- // Fix LLM preambles
- for (const pattern of LLM_PREAMBLES) {
- pattern.lastIndex = 0;
- fixed = fixed.replace(pattern, '');
- }
+ // Fix LLM preambles: only the leading run at a body start.
+ const preamble = findLeadingPreamble(fixed);
+ if (preamble) fixed = fixed.slice(0, preamble.start) + fixed.slice(preamble.end);
// Fix wrapping code fences
fixed = fixed.replace(/^```(?:markdown|md)\s*\n/, '');
@@ -586,9 +610,10 @@ export interface LintResult {
/** #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. */
+ /** Fixes not applied this run: a managed brain could not publish them (#5180:
+ * no indexed page, or the page changed mid-scan; `managed-write-pending`),
+ * or the file refused the write (`fix-not-writable`). Each is a non-fixable
+ * issue and is retried on the next run. */
fix_pending: number;
/** The first MAX_PENDING_ISSUES of those issues with their code, reason and fix. */
pending_issues: LintIssue[];
@@ -604,6 +629,32 @@ function pendingIssue(file: string, slug: string, reason: string, error: Operati
...(envelope?.fix ? { fix: envelope.fix } : {}), docs: docsUrl(MANAGED_LINT_DOCS) };
}
+const UNWRITABLE_CODES: ReadonlySet<string> = new Set(['EACCES', 'EPERM', 'EROFS']);
+
+/**
+ * Write one filesystem lint fix. A file the process may not write (EACCES,
+ * EPERM, EROFS: permissions or a read-only mount) is left unchanged and
+ * returned as a non-fixable `fix-not-writable` issue so the rest of the tree
+ * is still linted; any other write error propagates.
+ */
+function writeLintFixOrRefusal(page: string, relPath: string, fixed: string): LintIssue | null {
+ try {
+ writeSourceFileSync(page, fixed);
+ return null;
+ } catch (e) {
+ const errno = (e as NodeJS.ErrnoException | null)?.code;
+ if (typeof errno !== 'string' || !UNWRITABLE_CODES.has(errno)) throw e;
+ const envelope = toAgentError(opError('storage_error', `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.', {
+ 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.` },
+ }), { transport: 'cli', command: 'lint', render: cliRenderContext() });
+ return { file: relPath, line: 1, rule: 'fix-not-writable', fixable: false, code: 'fix_not_writable', reason: errno.toLowerCase(),
+ message: envelope.message, ...(envelope.fix ? { fix: envelope.fix } : {}) };
+ }
+}
+
function refusalReason(error: OperationError): string {
if (error.code === 'revision_conflict') return 'revision_changed';
if (heldFileDiagnostic(error.message)) return 'held_file';
@@ -784,11 +835,16 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
}
} else {
assertSourceFilesystemActive();
- writeSourceFileSync(page, fixed);
- if (commitFixes) {
- commitWriteThroughFile(repoProbe, page, relative(repoProbe, page).replace(/\.md$/u, ''));
+ const unwritable = writeLintFixOrRefusal(page, relPath, fixed);
+ if (unwritable) {
+ issues.push(unwritable);
+ totalIssues++;
+ fixPending++;
+ if (pendingIssues.length < MAX_PENDING_ISSUES) pendingIssues.push(unwritable);
+ } else {
+ if (commitFixes) commitWriteThroughFile(repoProbe, page, relative(repoProbe, page).replace(/\.md$/u, ''));
+ fixCount = fixable;
}
- fixCount = fixable;
}
totalFixed += fixCount;
}
diff --git a/test/lint-preamble-anchor.test.ts b/test/lint-preamble-anchor.test.ts
new file mode 100644
index 0000000000..a943b1a88e
--- /dev/null
+++ b/test/lint-preamble-anchor.test.ts
@@ -0,0 +1,115 @@
+/**
+ * `llm-preamble` is anchored to the start of the page body, and a `lint --fix`
+ * write the file refuses (EACCES/EPERM/EROFS) is contained per file.
+ *
+ * Protects: `lint --fix` (and the cycle's lint phase) never deletes a real
+ * line further down a page that merely begins "Sure! Here is...", and one
+ * read-only page cannot fail the run or stop later pages from being fixed.
+ * Fails when the preamble patterns match at every line start again, or the
+ * write error propagates. Existing lint tests only cover a preamble at the top.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { fixContent, lintContent, runLintCore } from '../src/commands/lint.ts';
+import { runPhaseLint } from '../src/core/cycle.ts';
+import { permsEnforced } from './helpers/fs-perms.ts';
+
+const FM = '---\ntitle: Notes\ntype: note\ncreated: 2026-04-11\n---\n\n';
+
+function preambleIssues(content: string) {
+ return lintContent(content, 'p.md').filter(i => i.rule === 'llm-preamble');
+}
+
+describe('llm-preamble is anchored to the start of the page body', () => {
+ test('a mid-document line that starts like a preamble is neither flagged nor changed', () => {
+ const filler = Array.from({ length: 40 }, (_, i) => `Line ${i}.`).join('\n');
+ for (const line of [
+ "Absolutely. Here's the clean version I'd propose.",
+ 'Sure! Here are the three options we discussed.',
+ 'Certainly. Here is what changed.',
+ ]) {
+ const content = `${FM}# Notes\n\n${filler}\n${line}\n${filler}\n`;
+ expect(preambleIssues(content)).toHaveLength(0);
+ expect(fixContent(content)).toBe(content);
+ }
+ });
+
+ test('a preamble right after frontmatter is flagged at its own line and only it is stripped', () => {
+ const content = `${FM}Of course. Here is the page for alice-example.\n\n# Alice\n\nSure! Here are her notes.\n`;
+ const issues = preambleIssues(content);
+ expect(issues).toHaveLength(1);
+ expect(issues[0]!.line).toBe(7);
+ const fixed = fixContent(content);
+ expect(fixed).not.toContain('Of course');
+ expect(fixed).toContain('Sure! Here are her notes.');
+ expect(fixed.startsWith(FM)).toBe(true);
+ });
+
+ test('leading blank lines, a preamble above the frontmatter and a ```markdown wrapper are still body starts', () => {
+ const blank = '\n\nSure! Here is the page.\n# T\n\nBody.\n';
+ expect(preambleIssues(blank).map(i => i.line)).toEqual([3]);
+ expect(fixContent(blank)).not.toContain('Sure!');
+ const above = `Certainly. Here is the brain page.\n\n${FM}# Page\n\nBody.\n`;
+ expect(preambleIssues(above)).toHaveLength(1);
+ expect(fixContent(above).startsWith('---\n')).toBe(true);
+ const wrapped = '```markdown\nSure! Here is the page.\n# T\n\nBody.\n```';
+ expect(preambleIssues(wrapped)).toHaveLength(1);
+ expect(fixContent(wrapped)).not.toContain('Sure!');
+ });
+
+ test('CRLF frontmatter anchors the body start', () => {
+ const content = '---\r\ntitle: Notes\r\n---\r\nSure! Here is the page.\r\n# T\r\n\r\nSure! Here are the notes.\r\n';
+ expect(preambleIssues(content)).toHaveLength(1);
+ const fixed = fixContent(content);
+ expect(fixed).toContain('Sure! Here are the notes.');
+ expect(fixed).not.toContain('Sure! Here is the page.');
+ });
+
+ test('stacked leading preambles are all stripped', () => {
+ expect(fixContent('Sure! Here is the page.\nCertainly. Here is the brain page.\n\n# Title\n\nContent.')).toBe('# Title\n\nContent.\n');
+ });
+});
+
+describe('lint --fix contains a page it cannot write', () => {
+ const roots: string[] = [];
+ afterEach(() => {
+ for (const r of roots.splice(0)) {
+ try { chmodSync(join(r, 'readonly.md'), 0o644); } catch { /* absent */ }
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ function brainWithReadOnlyPage(): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-lint-ro-'));
+ roots.push(root);
+ writeFileSync(join(root, 'readonly.md'), `${FM}Of course. Here is the brain page.\n\n# RO\n\nBody.\n`);
+ chmodSync(join(root, 'readonly.md'), 0o444);
+ writeFileSync(join(root, 'writable.md'), `${FM}Of course. Here is the brain page.\n\n# RW\n\nBody.\n`);
+ return root;
+ }
+
+ test.skipIf(!permsEnforced())('the read-only page is reported with its code, reason and fix; the later page is still fixed', async () => {
+ const root = brainWithReadOnlyPage();
+ const result = await runLintCore({ target: root, fix: true, contentSanity: {}, typePack: null });
+ expect(result.total_fixed).toBe(1);
+ expect(result.fix_pending).toBe(1);
+ expect(result.pending_issues).toHaveLength(1);
+ const issue = result.pending_issues[0]!;
+ expect(issue).toMatchObject({ file: 'readonly.md', rule: 'fix-not-writable', fixable: false, code: 'fix_not_writable', reason: 'eacces' });
+ expect(issue.message).toBe('fix not applied: readonly.md is not writable (EACCES); the file was left unchanged.');
+ expect(issue.fix).toMatchObject({ actor: 'user', next: 'report', user_message: 'Make readonly.md writable for gbrain, or exclude it from lint.' });
+ expect(readFileSync(join(root, 'writable.md'), 'utf8')).not.toContain('Of course');
+ expect(readFileSync(join(root, 'readonly.md'), 'utf8')).toContain('Of course');
+ });
+
+ test.skipIf(!permsEnforced())('the cycle lint phase warns instead of failing and lists the pending page', async () => {
+ const root = brainWithReadOnlyPage();
+ const result = await runPhaseLint(root, false, null);
+ expect(result.status).toBe('warn');
+ expect(result.error).toBeUndefined();
+ expect(result.details).toMatchObject({ fixed: 1, fix_pending: 1 });
+ expect((result.details.pending as Array<{ rule: string }>)[0]!.rule).toBe('fix-not-writable');
+ });
+});