Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#!/usr/bin/env node
/**
* Core memory write-path guard coverage (docs/guides/core-memory.md).
*
* Always-loaded core pages are guarded in preparePageMutation
* (src/core/persistence/page-prepare.ts -> core-guard.ts): owner-only
* marking, the brain-wide budget, the remote-edit policy, and the ordered
* source lock the coordinator takes from `exclusiveSources`. This check
* fails when:
* 1. a module that builds a PreparedMutation neither routes through
* preparePageMutation / prepareMemoryMutation nor sits on the reviewed
* exemption list below (with its reason), or
* 2. a module wraps preparePageMutation but drops `exclusiveSources`
* (neither spreads the prepared result nor forwards the field), which
* would publish a core write without the ordered source lock.
*/
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
// Fixture root for scripts/guard-self-test.sh: argv[2] or GBRAIN_GUARD_ROOT.
const ROOT = process.argv[2] ?? process.env.GBRAIN_GUARD_ROOT ?? fileURLToPath(new URL('..', import.meta.url));
/** Reviewed: preparers that publish without the core guard, and why that is safe. */
const EXEMPT = {
'src/core/persistence/sync-prepare.ts': 'owner git edits (managed sync) pass by design; doctor core_memory reports any overage',
'src/core/persistence/group-publish.ts': 'bulk managed sync of owner git edits; groupable() excludes core-locked members',
'src/core/persistence/sync-pass-fold.ts': 'adds the pass checkpoint rows to the managed sync import sync-prepare.ts prepared (owner git edits); writes no page text of its own (test/sync-pass-fold-6712.test.ts, core guard)',
'src/core/persistence/reconcile-prepare.ts': 'reconciles the owner checkout into the database (owner edit)',
'src/core/persistence/forget-prepare.ts': 'a withdrawal strikes rows that already carry the claim (it adds no claim; a remote caller passes guardRemoteForget), as the withdrawal mirror it replaces rewrote those pages; doctor core_memory reports any overage',
'src/core/persistence/file-repair.ts': 'publishes bytes the owner approved with gbrain repair frontmatter --apply',
'src/core/persistence/grandfather.ts': 'adopts pages that already exist at activation; no content change',
'src/core/persistence/import-prepare.ts': 'owner-run local import (gbrain import); doctor reports any overage',
'src/core/persistence/sync-image.ts': 'owner git edits (managed sync image branch, prepared through importImageFile as import-prepare.ts is); doctor core_memory reports any overage',
'src/core/persistence/connector-sync.ts': 'connector-owned pages; core marking is owner-written frontmatter the connector never sets',
'src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text',
'src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged',
'src/core/persistence/change-reason.ts': 'wraps the PreparedMutation preparePageMutation returned (service.ts) in place: the core guard, exclusiveSources and every other field are the guarded object\'s own',
'src/core/persistence/import-deferral.ts': 'withSupersedes wraps the PreparedMutation preparePageMutation returned (service.ts) in place: it only adds the supersedes trailer and the outcome field to a held blind put_page; the core guard, exclusiveSources and every other field are the guarded object\'s own',
'src/core/persistence/valid-time-advisory.ts': 'wraps the PreparedMutation withChangeReason returned (service.ts) in place: its apply only adds the read-only valid_time advisory to the outcome after the guarded apply; the core guard, exclusiveSources and every other field are the guarded object\'s own',
'src/core/persistence/local-edit-adoption.ts': 'withAdoptedLocalEdit wraps the PreparedMutation preparePersistedMutation returned (service.ts) in place: its apply only adds the adopted field to the outcome after the guarded apply; the adoption it publishes is a managed_file_repair (file-repair.ts) of the bytes already in the owner checkout',
'src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing',
'src/core/generations/repair.ts': 'the managed restore of a database-only generation (chronicle event pages, never core pages) revives and retires derived items through the adapter inside the coordinated request',
'src/core/generations/managed.ts': 'the generation activation flips the derived ledger; it writes no page text (its member page writes go through preparePageMutation)',
'src/core/persistence/consumer.ts': 'dispatches to preparers; no page content of its own',
'src/core/persistence/coordinator.ts': 'takes the ordered source lock from exclusiveSources; prepares nothing itself',
'src/core/persistence/effect-journal.ts': 'post-publication effects; no page text',
'src/core/repair/file-drift.ts': 'removes a held file whose page is deleted: no live page records the path (re-read under the publication guard), the page row is untouched, and core counts only live pages; --prefer file publishes through file-repair.ts',
'src/core/repair/captured-facts.ts': 'owner-run repair that expires fact rows (shrinks only)',
'src/core/repair/agent-session-facts.ts': 'owner-run repair that re-attributes capture-lane facts and retires their takes (no content added)',
'src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',
'src/core/repair/unwithdrawn-facts.ts': 'owner-run, preview-bound repair putting expired fact rows back to their recorded before-state (row number and lifecycle); page text is unchanged',
'src/core/repair/redacted-facts.ts': 'owner-run, preview-bound repair rewriting the text of database-only fact rows to words a source page proves; page text is unchanged (fenced rows publish through put_page, preparePageMutation)',
'src/core/repair/open-facts.ts': 'owner-run, preview-first repair (#8194): its own intent only changes the visibility of named database-only fact rows in place; fenced rows publish through the keep_trust maintenance page, which preparePageMutation guards (openFactsPublication wraps it)',
'src/core/repair/visibility.ts': 'owner-run, preview-first repair that only tightens database-only fact rows from world to private; page text is unchanged (fenced rows and page labels publish through put_page, preparePageMutation)',
'src/core/repair/purged-page-facts.ts': 'owner-run repair expiring fact rows of pages that no longer exist (shrinks only; no page text)',
'src/core/repair/conversation-labels.ts': 'owner-run repair expiring fact rows and writing an outcome row (shrinks only; page text unchanged)',
'src/core/shared-skills/publication.ts': 'skill bundles, not pages',
'src/core/persistence/prepared-import.ts': 'type definitions shared by import preparers; prepares nothing itself',
'src/commands/extract-timeline-db.ts': 'writes timeline rows; timeline never enters core',
'src/core/extract-timeline-from-meetings.ts': 'writes meeting timeline rows on entity pages; page text is unchanged',
'src/core/facts/conversation-publication.ts': 'writes database-only conversation fact rows; page text is unchanged',
'src/core/facts/conversation-relink.ts': 'sets entity_slug on database-only conversation fact rows; page text is unchanged',
'src/core/cycle/extract-facts.ts': 'fence reconcile and deleted-page expiry write fact rows only; page text is unchanged',
'src/core/cycle/extract-takes.ts': 'takes reextract writes take rows only; page text is unchanged',
'src/core/persistence/upload-streamed.ts': 'an upload over the single-string ceiling refuses when the page is or would become always-loaded core (the guard renders it whole); smaller uploads go through preparePageMutation',
'src/core/persistence/page-edit.ts': 'segmented edit_page splices through page-append.ts prepareSegmentedSpliceMutation, which declines an always-loaded core page to preparePageMutation; the splice never changes frontmatter',
'src/core/trust/release-publish.ts': 'append mode publishes the page write prepareFenceFactAppend builds with preparePageMutation (core guard and exclusiveSources spread into the result); index-existing indexes a fence row the file already holds and changes no page text',
'src/core/repair/take-supersession.ts': 'reprojection writes takes.superseded_by only; fence edits go through put_page (preparePageMutation)',
};
const GUARDED = /\b(preparePageMutation|prepareMemoryMutation|prepareCoreGuard)\b/;
function walk(dir, out = []) {
for (const name of readdirSync(dir)) {
const path = join(dir, name);
if (statSync(path).isDirectory()) walk(path, out);
else if (path.endsWith('.ts') && !path.endsWith('.d.ts') && !path.includes('.generated.')) out.push(path);
}
return out;
}
const problems = [];
for (const file of walk(join(ROOT, 'src'))) {
const rel = relative(ROOT, file);
const text = readFileSync(file, 'utf8');
if (!/\bPreparedMutation\b/.test(text)) continue;
if (rel === 'src/core/persistence/page-prepare.ts' || rel === 'src/core/persistence/core-guard.ts') continue;
if (!GUARDED.test(text)) {
if (!EXEMPT[rel]) problems.push(`${rel}: builds a PreparedMutation without the core guard. Route page writes through preparePageMutation, or add it to EXEMPT in scripts/check-core-guard-coverage.mjs with the reason core pages are safe.`);
continue;
}
const names = [...text.matchAll(/(?:const|let)\s+(\w+)\s*(?::[^=]+)?=\s*(?:await\s+)?[^;\n]*?\b(?:preparePageMutation|prepareMemoryMutation)\s*\(/g)].map(m => m[1]);
const reassigned = [...text.matchAll(/\b(\w+)\s*=\s*await\s+[^;\n]*?\b(?:preparePageMutation|prepareMemoryMutation)\s*\(/g)].map(m => m[1]);
const vars = [...new Set([...names, ...reassigned])];
const returnsDirect = /return\s+(?:await\s+)?(?:preparePageMutation|prepareMemoryMutation)\s*\(/.test(text);
const spread = new Set([...text.matchAll(/\.\.\.(\w+)\b/g)].map(m => m[1]));
const forwards = text.includes('exclusiveSources') || vars.some(v => spread.has(v));
if (!returnsDirect && !forwards) problems.push(`${rel}: wraps preparePageMutation but drops exclusiveSources, so a core write would publish without the ordered source lock. Spread the prepared result or forward exclusiveSources.`);
}
if (problems.length) {
console.error('check-core-guard-coverage: FAIL');
for (const p of problems) console.error(` ${p}`);
console.error('See docs/guides/core-memory.md (write-path guard) and src/core/persistence/core-guard.ts.');
process.exit(1);
}
console.log('check-core-guard-coverage: OK');