Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep size-ratcheted modules flat: cycle.lint_fix read lives in lint.ts, the put_page source hint in its own module
garrytan69d9cc6d0ad3
diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex a18e979352..c0ccc7d88e 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -616,6 +616,11 @@ function changedWhileLinting(sourceId: string, slug: string): OperationError {{ fix: readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });}+/** `cycle.lint_fix` (default on): only an explicit falsy value makes the cycle's lint phase report-only; a config read failure keeps the default. */+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) ?? '');+}+/*** #5180: publish one lint repair through the persistence coordinator, the* only writer a managed brain's worktree accepts. Resolves the page's slugdiff --git a/src/core/config.ts b/src/core/config.tsindex 81e017fb4b..10c5140a1b 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1524,8 +1524,6 @@ 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.tsindex 987fc7f656..c5ec9f0c25 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1023,15 +1023,13 @@ 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 } = await import('../commands/lint.ts');+ const { runLintCore, cycleLintFixEnabled } = await import('../commands/lint.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").- // `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 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 pathconst issues = result.total_issues ?? 0;const fixed = result.total_fixed ?? 0;@@ -1039,20 +1037,16 @@ export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: B// '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 (a managed repair left pending counts as remaining).- const status: PhaseStatus =- issues === 0 || (!dryRun && lintFix && remaining === 0) ? 'ok' : 'warn';+ // 'warn' when issues remain after the run (a managed repair left pending, or a report-only run, counts as remaining).+ const status: PhaseStatus = issues === 0 || (!dryRun && remaining === 0) ? 'ok' : 'warn';return {phase: 'lint',status,duration_ms: 0, // set by callersummary: dryRun? `${issues} issue(s) found (dry-run, no writes)`- : !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 } : {}) },+ : 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 } : {}) },};} catch (e) {return {diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex eaf19b6f6d..10f9918e56 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -25,7 +25,8 @@ import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } fromimport { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagination.ts';import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';-import { invalidParam, readFix } from './op-fix.ts';+import { invalidParam } from './op-fix.ts';+import { rethrowNamingRevisionSource } from './put-page-revision-source.ts';import {assertExplicitSourceLive,enforceSubagentSlugFence,@@ -317,48 +318,11 @@ const put_page: Operation = {}return { dry_run: true, action: 'put_page', slug: p.slug };}- try {- return await submitPageMutation(ctx, { operation: 'put_page', params: p });- } catch (error) {- if (error instanceof OperationError && error.code === 'revision_conflict') await nameRevisionSource(ctx, sourceId, p, error);- throw error;- }+ return submitPageMutation(ctx, { operation: 'put_page', params: p }).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error));},cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },};-/**- * A put_page refused as revision_conflict whose expected_revision is the- * current revision of the same slug in another source was almost certainly- * read there and written back without its source_id. The refusal then names- * that source, and its fix re-reads the page there. Only a source and page- * the caller may read are named (grant and page visibility, as get_page- * applies them); otherwise the refusal is left exactly as it was.- */-async function nameRevisionSource(ctx: OperationContext, writeSource: string, p: Record<string, unknown>, error: OperationError): Promise<void> {- if (typeof p.slug !== 'string' || typeof p.expected_revision !== 'string') return;- const slug = p.slug.toLowerCase();- const expected = p.expected_revision.toLowerCase();- try {- const candidates = await ctx.engine.executeRaw<{ source_id: string }>(- `SELECT p.source_id FROM pages p JOIN sources s ON s.id = p.source_id- WHERE p.slug = $1 AND p.source_id <> $2 AND p.deleted_at IS NULL AND s.archived IS NOT TRUE ORDER BY p.source_id`, [slug, writeSource]);- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- for (const { source_id: other } of candidates) {- try { federatedSearchScope(ctx, other); } catch { continue; }- const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId: other, excludePrivate });- if (!snapshot || snapshot.revision !== expected || (excludePrivate && isPrivatePage(snapshot.page))) continue;- error.suggestion = `Page ${slug} is at exactly this expected_revision in source ${other}, so it was probably read there; this write went to source ${writeSource}. `- + `Re-read it with source_id ${other}; a write to that page must carry source_id ${other} and the revision get_page returns.`;- error.fix = readFix(`Reads page ${slug} from source ${other}, where its revision matches the one this write sent.`,- { argv: ['gbrain', 'get', '--source', other, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: other, include_content: true } } });- return;- }- } catch {- // The hint is advisory: a failed lookup leaves the refusal unchanged.- }-}-// v0.31.2: isFactsBackstopEligible moved to src/core/facts/eligibility.ts// so sync.ts, file_upload, code_import, and runFactsBackstop all share one// predicate. Imported above.diff --git a/src/core/ops/put-page-revision-source.ts b/src/core/ops/put-page-revision-source.tsnew file mode 100644index 0000000000..bc1c3d67e1--- /dev/null+++ b/src/core/ops/put-page-revision-source.ts@@ -0,0 +1,37 @@+import { OperationError, type OperationContext } from './contract.ts';+import { federatedSearchScope } from './context.ts';+import { readFix } from './op-fix.ts';+import { isPrivatePage, resolveExcludePrivatePages } from '../search/private-visibility.ts';++/**+ * Rethrows a put_page failure. A revision_conflict whose expected_revision is+ * the current revision of the same slug in another source was almost certainly+ * read there and written back without its source_id, so the refusal names that+ * source and its fix re-reads the page there. Only a source and page the caller+ * may read are named (grant and page visibility, as get_page applies them);+ * otherwise the refusal is rethrown exactly as it was.+ */+export async function rethrowNamingRevisionSource(ctx: OperationContext, writeSource: string, p: Record<string, unknown>, error: unknown): Promise<never> {+ if (!(error instanceof OperationError) || error.code !== 'revision_conflict' || typeof p.slug !== 'string' || typeof p.expected_revision !== 'string') throw error;+ const slug = p.slug.toLowerCase();+ const expected = p.expected_revision.toLowerCase();+ try {+ const candidates = await ctx.engine.executeRaw<{ source_id: string }>(+ `SELECT p.source_id FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.slug = $1 AND p.source_id <> $2 AND p.deleted_at IS NULL AND s.archived IS NOT TRUE ORDER BY p.source_id`, [slug, writeSource]);+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);+ for (const { source_id: other } of candidates) {+ try { federatedSearchScope(ctx, other); } catch { continue; }+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId: other, excludePrivate });+ if (!snapshot || snapshot.revision !== expected || (excludePrivate && isPrivatePage(snapshot.page))) continue;+ error.suggestion = `Page ${slug} is at exactly this expected_revision in source ${other}, so it was probably read there; this write went to source ${writeSource}. `+ + `Re-read it with source_id ${other}; a write to that page must carry source_id ${other} and the revision get_page returns.`;+ error.fix = readFix(`Reads page ${slug} from source ${other}, where its revision matches the one this write sent.`,+ { argv: ['gbrain', 'get', '--source', other, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: other, include_content: true } } });+ break;+ }+ } catch {+ // The hint is advisory: a failed lookup leaves the refusal unchanged.+ }+ throw error;+}