Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
compile-context core arm: --include-core/--remove-core, codex-global and hermes targets, git-tracked refusal, compiled-core records in doctor
garrytand0a84f1e2eb6
diff --git a/src/commands/compile-context.ts b/src/commands/compile-context.tsindex 42d096ca41..db7a8d64c9 100644--- a/src/commands/compile-context.ts+++ b/src/commands/compile-context.ts@@ -34,10 +34,13 @@ import { atomicWriteTextFile } from '../core/bootstrap/atomic-write.ts';import { compileView, type CompileViewMeta } from '../core/context/compile-view.ts';import { formatSensitivityDrop, loadSensitivityConfig } from '../core/context/sensitivity-scan.ts';import { resolveSourceId, ALL_SOURCES } from '../core/source-resolver.ts';+import { homedir } from 'os';+import { listCorePages, loadCoreBlock } from '../core/core-memory.ts';+import { ensureGitExcluded, gitRoot, isGitTracked, updateCompiledCoreRecord } from '../core/context/compiled-core.ts';// ── Constants ───────────────────────────────────────────────────────────────-export const COMPILE_TARGETS = ['claude-code', 'codex', 'openclaw'] as const;+export const COMPILE_TARGETS = ['claude-code', 'codex', 'openclaw', 'codex-global', 'hermes'] as const;export type CompileTarget = (typeof COMPILE_TARGETS)[number];/** Managed-block markers for the codex (AGENTS.md) target. Exact-line match. */@@ -62,6 +65,8 @@ interface CompileFlags {include?: string[];check: boolean;json: boolean;+ includeCore: boolean;+ removeCore: boolean;}class UsageError extends Error {}@@ -111,9 +116,15 @@ function parseCompileFlags(args: string[]): CompileFlags {...(include && include.length > 0 ? { include } : {}),check: args.includes('--check'),json: args.includes('--json'),+ // codex-global exists to carry core, so it includes core unless told to remove it.+ includeCore: !args.includes('--remove-core') && (args.includes('--include-core') || target === 'codex-global'),+ removeCore: args.includes('--remove-core'),};}+/** Targets whose output is a managed block inside a file the user also edits. */+const SPLICE_TARGETS: ReadonlySet<CompileTarget> = new Set(['codex', 'codex-global']);+// ── Codex AGENTS.md splice ──────────────────────────────────────────────────/**@@ -175,9 +186,24 @@ export function defaultOutPath(target: CompileTarget, cwd: string): string {case 'openclaw':// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversalreturn join(cwd, '.gbrain', 'compiled-context.md');+ case 'codex-global':+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal+ return join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'AGENTS.md');+ case 'hermes':+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal+ return join(gitRoot(cwd) ?? cwd, '.hermes.md');}}+/** Removes the managed block from a splice target, leaving the user's own text. */+export function removeCompiledBlock(existing: string): string {+ const lines = existing.split('\n');+ const begin = lines.indexOf(COMPILED_BLOCK_BEGIN);+ const end = lines.indexOf(COMPILED_BLOCK_END);+ if (begin === -1 || end < begin) return existing;+ return [...lines.slice(0, begin), ...lines.slice(end + 1)].join('\n');+}+// ── Help ────────────────────────────────────────────────────────────────────function printCompileContextHelp(): void {@@ -196,6 +222,9 @@ Flags:--include <p,...> Extra slug prefixes selected alongside the defaults.--check Recompile in memory and byte-compare against theexisting output. Exit 0 same, 1 different, 2 error.+ --include-core Render always-loaded core memory first, in full. Refused+ when the output file is tracked by git.+ --remove-core Recompile without core (codex-global: remove the block).--json Machine-readable result envelope on stdout.--help Show this help.@@ -203,6 +232,10 @@ Targets:claude-code .claude/gbrain-context.md + a one-line CLAUDE.md import.codex AGENTS.md managed block (also loads natively in opencode).openclaw .gbrain/compiled-context.md in the workspace.+ codex-global $CODEX_HOME/AGENTS.md managed block: the default source's+ core memory, loaded in every Codex session.+ hermes .hermes.md at the git root, kept out of git via+ .git/info/exclude.`);}@@ -249,8 +282,9 @@ export async function runCompileContext(try {// Source resolution runs even when the source flag is omitted (6-tier- // resolution: flag > env > dotfile > ... > 'default').- const sourceId = await resolveSourceId(engine, flags.source ?? null, cwd);+ // resolution: flag > env > dotfile > ... > 'default'). The user-global+ // codex file holds the default source's core only.+ const sourceId = flags.target === 'codex-global' ? 'default' : await resolveSourceId(engine, flags.source ?? null, cwd);if (sourceId === ALL_SOURCES) {process.stderr.write('compile-context: compiles exactly ONE source — pass a concrete source id.\n',@@ -263,6 +297,25 @@ export async function runCompileContext(// could be written.const scanConfig = loadSensitivityConfig({ workspaceRoot: cwd });+ const outPath = flags.out ?? defaultOutPath(flags.target, cwd);+ // Core reaches every session that loads this file, so it never goes into a shared (git-tracked) file.+ if (flags.includeCore && !flags.stdout) {+ if (flags.target === 'hermes' && !isGitTracked(outPath)) ensureGitExcluded(outPath);+ if (isGitTracked(outPath)) {+ process.stderr.write(`compile-context: ${outPath} is tracked by git, so always-loaded core memory will not be written into it (it would be committed and shared). `+ + 'Use a local target (--target claude-code, hermes or codex-global) or --out <untracked path>, or drop --include-core.\n');+ return EXIT_ERROR;+ }+ }+ // Core pages leave the arms either way: with --include-core they render in full, without it they stay out.+ const excludeSlugs = new Set((await listCorePages(engine, { sourceIds: [sourceId] })).map(p => p.slug));+ let core: { text: string; revision: string; command: string } | undefined;+ if (flags.includeCore) {+ const block = await loadCoreBlock(engine, { sessionSourceId: sourceId, excludePrivate: true, notices: [] });+ const command = `gbrain compile-context --target ${flags.target}${flags.target === 'codex-global' ? '' : ' --include-core'}${flags.out ? ` --out ${flags.out}` : ''}`;+ core = { text: block.text, revision: block.revision, command };+ }+const { text, meta } = await compileView({engine,sourceId,@@ -270,6 +323,9 @@ export async function runCompileContext(budget: flags.budget,...(flags.include ? { includePrefixes: flags.include } : {}),scanConfig,+ excludeSlugs,+ ...(core ? { core } : {}),+ ...(flags.target === 'codex-global' ? { coreOnly: true } : {}),});// Drops are always reported: slug + family + fingerprint, never the text.@@ -277,7 +333,6 @@ export async function runCompileContext(process.stderr.write(`compile-context: ${formatSensitivityDrop(d, cwd)}\n`);}- const outPath = flags.out ?? defaultOutPath(flags.target, cwd);const existing = existsSync(outPath) ? readFileSync(outPath, 'utf-8') : null;const envelope = (extra: Partial<CompileEnvelope>): CompileEnvelope => ({@@ -291,7 +346,7 @@ export async function runCompileContext(if (flags.check) {let same: boolean;- if (flags.target === 'codex') {+ if (SPLICE_TARGETS.has(flags.target)) {// "Would a write change the file?" — includes missing/absent block.same = existing !== null && spliceCompiledBlock(existing, text) === existing;} else {@@ -319,9 +374,16 @@ export async function runCompileContext(return EXIT_OK;}+ if (flags.target === 'codex-global' && flags.removeCore) {+ if (existing !== null) atomicWriteTextFile(outPath, removeCompiledBlock(existing), { freshMode: 0o644 });+ updateCompiledCoreRecord(outPath, null);+ process.stdout.write(flags.json ? `${JSON.stringify(envelope({}))}\n` : `compile-context: removed core memory from ${outPath}\n`);+ return EXIT_OK;+ }const fileText =- flags.target === 'codex' ? spliceCompiledBlock(existing ?? '', text) : text;+ SPLICE_TARGETS.has(flags.target) ? spliceCompiledBlock(existing ?? '', text) : text;atomicWriteTextFile(outPath, fileText, { freshMode: 0o644 });+ updateCompiledCoreRecord(outPath, core ? { target: flags.target, source_id: sourceId, revision: core.revision, command: core.command } : null);if (flags.json) {process.stdout.write(`${JSON.stringify(envelope({}))}\n`);diff --git a/src/commands/doctor/checks/core-memory.ts b/src/commands/doctor/checks/core-memory.tsindex 354edd241d..17aeb37f8a 100644--- a/src/commands/doctor/checks/core-memory.ts+++ b/src/commands/doctor/checks/core-memory.ts@@ -3,8 +3,9 @@* Warns when core is over its brain-wide budget (owner git edits may push it* there), when a stored core/pressure setting is out of range (the readers* fall back to the default), when the delivery sensitivity policy withholds a- * core page, when remote edits wait for review, and when core pages exist but- * no session-start delivered them in the last week.+ * core page, when remote edits wait for review, when a compiled file carries+ * an old or no-longer-wanted core revision, and when core pages exist but no+ * session-start delivered them in the last week.*/import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';@@ -15,6 +16,8 @@ import {} from '../../../core/core-memory.ts';import { PRESSURE_CONFIG_KEYS, validatePressureConfigValue } from '../../../core/context/pressure.ts';import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';+import { compiledCoreRevision, readCompiledCoreRecords } from '../../../core/context/compiled-core.ts';+import { existsSync, readFileSync } from 'node:fs';const DELIVERY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;@@ -29,11 +32,22 @@ export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check,const problem = validateCoreConfigValue(key, value) ?? validatePressureConfigValue(key, value);if (problem) badConfig.push(`${key}=${value} is ignored (${problem})`);}+ // Compiled files carrying core (compile-context --include-core, codex-global): stale or leftover copies.+ const compiled: string[] = [];+ for (const rec of readCompiledCoreRecords()) {+ if (!existsSync(rec.path)) continue;+ const onDisk = compiledCoreRevision(readFileSync(rec.path, 'utf8'));+ if (!onDisk) continue;+ const current = (await loadCoreBlock(engine, { sessionSourceId: rec.source_id, excludePrivate: true, notices: [], settings })).revision;+ if (!settings.enabled || usage.pages.length === 0) compiled.push(`${rec.path} still carries core memory that is now ${settings.enabled ? 'empty' : 'disabled'}; remove it with ${rec.command} --remove-core`);+ else if (onDisk !== current) compiled.push(`${rec.path} carries an older core revision; refresh it with ${rec.command}`);+ }if (usage.pages.length === 0) {+ const issues = [...badConfig, ...compiled];return {- status: badConfig.length ? 'warn' : 'ok',- message: badConfig.length ? `No core pages. ${badConfig.join('; ')}.` : 'No core pages. Start one with gbrain core init, then fill it in with the user.',- details: { pages: 0, chars_used: 0, chars_limit: settings.maxChars, enabled: settings.enabled, bad_config: badConfig, docs: CORE_DOCS },+ status: issues.length ? 'warn' : 'ok',+ message: issues.length ? `No core pages. ${issues.join('; ')}.` : 'No core pages. Start one with gbrain core init, then fill it in with the user.',+ details: { pages: 0, chars_used: 0, chars_limit: settings.maxChars, enabled: settings.enabled, bad_config: badConfig, compiled, docs: CORE_DOCS },};}const block = await loadCoreBlock(engine, { excludePrivate: true, settings });@@ -42,7 +56,7 @@ export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check,const over = usage.chars - settings.maxChars;const largest = [...usage.pages].sort((a, b) => b.chars - a.chars)[0]!;if (over > 0) problems.push(`core is ${usage.chars} chars, over the ${settings.maxChars}-char budget by ${over}, so sessions get a truncated block; shorten the largest page (${largest.source_id}:${largest.slug}, ${largest.chars} chars) or raise memory.core.max_chars`);- problems.push(...badConfig);+ problems.push(...badConfig, ...compiled);if (withheld.length) problems.push(`${withheld.length} core page(s) withheld from delivery for sensitive content: ${withheld.map(w => `${w.source_id}:${w.slug}`).join(', ')}`);if (notices.length) problems.push(`${notices.length} remote edit(s) to core pages await the user's review (gbrain core diff, then gbrain core ack)`);let delivered: boolean | null = null;@@ -58,7 +72,7 @@ export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check,}const details = {enabled: settings.enabled, pages: usage.pages.length, chars_used: usage.chars, chars_limit: settings.maxChars, remote_edit: settings.remoteEdit,- revision: block.revision, withheld, pending_notices: notices.length, delivered_last_7d: delivered, bad_config: badConfig, docs: CORE_DOCS,+ revision: block.revision, withheld, pending_notices: notices.length, delivered_last_7d: delivered, bad_config: badConfig, compiled, docs: CORE_DOCS,};if (!problems.length) {return { status: 'ok', message: `Core memory ${settings.enabled ? 'on' : 'off'}: ${usage.pages.length} page(s), ${usage.chars}/${settings.maxChars} chars.`, details };diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex fab81a6e62..ad04ea5f46 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -38,7 +38,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],- 'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],+ 'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--revision', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--revision', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],@@ -123,7 +123,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/context/compile-view.ts b/src/core/context/compile-view.tsindex 8a5ce80789..0cccb6206e 100644--- a/src/core/context/compile-view.ts+++ b/src/core/context/compile-view.ts@@ -110,6 +110,16 @@ export interface CompileViewInput {includePrefixes?: string[];/** Pre-loaded sensitivity config — loader failures already threw upstream. */scanConfig: SensitivityScanConfig;+ /**+ * Always-loaded core block (core-memory.ts), rendered in full right after+ * the envelope; its tokens come out of the budget first. The header then+ * records the core revision and the command that refreshes it.+ */+ core?: { text: string; revision: string; command: string };+ /** Slugs never selected by the arms: core pages, which only reach a compiled file through `core`. */+ excludeSlugs?: ReadonlySet<string>;+ /** Render the core block alone (no arms), e.g. the user-global codex file. */+ coreOnly?: boolean;}export interface CompileViewScanDrop {@@ -176,6 +186,7 @@ async function fetchCandidates(const add = (pages: Page[], pinned: boolean) => {for (const page of pages) {+ if (input.excludeSlugs?.has(page.slug)) continue;const existing = bySlug.get(page.slug);if (existing) {existing.pinned = existing.pinned || pinned;@@ -276,8 +287,9 @@ function renderEntry(page: Page): RenderedEntry {return { slug: page.slug, date, block, rendered: `\n\n${block}` };}-function headerLine(digestHex16: string, target: string, budget: number): string {- return `<!-- gbrain:compiled-context digest=sha256:${digestHex16} target=${target} budget=${budget} -->`;+function headerLine(digestHex16: string, target: string, budget: number, core?: CompileViewInput['core']): string {+ const coreAttrs = core ? ` core_revision=${core.revision} refresh="${core.command}"` : '';+ return `<!-- gbrain:compiled-context digest=sha256:${digestHex16} target=${target} budget=${budget}${coreAttrs} -->`;}function sha256Hex16(text: string): string {@@ -301,7 +313,7 @@ function computeDigest(entries: RenderedEntry[]): string {* sensitivity config was loaded (and its failures thrown) upstream.*/export async function compileView(input: CompileViewInput): Promise<CompileViewResult> {- const { candidates, anchor } = await fetchCandidates(input);+ const { candidates, anchor } = input.coreOnly ? { candidates: [], anchor: null } : await fetchCandidates(input);// Total order: (score desc, slug asc).const scored = candidates@@ -341,8 +353,9 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR// Header cost: the digest value is FIXED-LENGTH (hex16), so a placeholder// of the same length prices the header before the kept set is known.const budget = input.budget;- const headerWithPlaceholder = headerLine('0'.repeat(16), input.target, budget);- const headerText = `${headerWithPlaceholder}\n${COMPILED_CONTEXT_ENVELOPE}`;+ const headerWithPlaceholder = headerLine('0'.repeat(16), input.target, budget, input.core);+ const coreText = input.core?.text ? `\n\n${input.core.text}` : '';+ const headerText = `${headerWithPlaceholder}\n${COMPILED_CONTEXT_ENVELOPE}${coreText}`;const noFitComment = `\n\n<!-- no entries fit budget ${budget} -->`;// Count every non-entry byte (header, envelope, trailing newline).const headerCost = estimateTokens(`${headerText}\n`);@@ -359,7 +372,7 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR}const digest = computeDigest(kept);- let text = `${headerLine(digest, input.target, budget)}\n${COMPILED_CONTEXT_ENVELOPE}`;+ let text = `${headerLine(digest, input.target, budget, input.core)}\n${COMPILED_CONTEXT_ENVELOPE}${coreText}`;if (kept.length > 0) {text += kept.map((e) => e.rendered).join('');} else if (entries.length > 0) {diff --git a/src/core/context/compiled-core.ts b/src/core/context/compiled-core.tsnew file mode 100644index 0000000000..d652cb9bf2--- /dev/null+++ b/src/core/context/compiled-core.ts@@ -0,0 +1,81 @@+/**+ * Static-file delivery of always-loaded core memory (`gbrain compile-context+ * --include-core`): git safety for the output path and a small local record+ * of every compiled file that carries core, so `gbrain doctor` can name+ * stale or leftover copies and the command that refreshes them.+ */+import { execFileSync } from 'node:child_process';+import { appendFileSync, existsSync, readFileSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { resolveGbrainHome } from '../gbrain-home.ts';++function git(cwd: string, args: string[]): string | null {+ try {+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ } catch {+ return null;+ }+}++export function gitRoot(cwd: string): string | null {+ return git(cwd, ['rev-parse', '--show-toplevel']);+}++/** True when the file is tracked by the git repository that contains it. */+export function isGitTracked(path: string): boolean {+ const dir = dirname(resolve(path));+ if (!existsSync(dir)) return false;+ return git(dir, ['ls-files', '--error-unmatch', '--', resolve(path)]) !== null;+}++/** Adds the path to the repository's local exclude file (never .gitignore, which is shared). */+export function ensureGitExcluded(path: string): void {+ const root = gitRoot(dirname(resolve(path)));+ if (!root) return;+ const excludeRel = git(root, ['rev-parse', '--git-path', 'info/exclude']);+ if (!excludeRel) return;+ const exclude = isAbsolute(excludeRel) ? excludeRel : join(root, excludeRel);+ const entry = `/${relative(root, resolve(path)).split('\\').join('/')}`;+ const current = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';+ if (current.split('\n').some(line => line.trim() === entry)) return;+ appendFileSync(exclude, `${current && !current.endsWith('\n') ? '\n' : ''}${entry}\n`);+}++export interface CompiledCoreRecord {+ path: string;+ target: string;+ source_id: string;+ revision: string;+ command: string;+ compiled_at: string;+}++function recordFile(): string {+ return join(resolveGbrainHome(), 'compiled-core.json');+}++export function readCompiledCoreRecords(): CompiledCoreRecord[] {+ try {+ const parsed = JSON.parse(readFileSync(recordFile(), 'utf8')) as { files?: CompiledCoreRecord[] };+ return Array.isArray(parsed.files) ? parsed.files : [];+ } catch {+ return [];+ }+}++/** Upserts (record) or drops (null) the entry for one output path. Best-effort. */+export function updateCompiledCoreRecord(path: string, record: Omit<CompiledCoreRecord, 'path' | 'compiled_at'> | null): void {+ try {+ const abs = resolve(path);+ const files = readCompiledCoreRecords().filter(r => r.path !== abs);+ if (record) files.push({ ...record, path: abs, compiled_at: new Date().toISOString() });+ atomicWriteTextFile(recordFile(), `${JSON.stringify({ files }, null, 2)}\n`, { freshMode: 0o600 });+ } catch { /* observability only */ }+}++/** Reads `core_revision=` from a compiled file's header line; null when the file has no core. */+export function compiledCoreRevision(text: string): string | null {+ const m = /<!-- gbrain:compiled-context [^\n]*core_revision=([0-9a-f]+|disabled)/.exec(text);+ return m ? m[1]! : null;+}diff --git a/test/compile-context-core.test.ts b/test/compile-context-core.test.tsnew file mode 100644index 0000000000..4255628e0a--- /dev/null+++ b/test/compile-context-core.test.ts@@ -0,0 +1,128 @@+/**+ * compile-context core arm: --include-core renders always-loaded core first+ * and records its revision in the header; without it core pages stay out of+ * every arm; core is never written into a git-tracked file; codex-global+ * carries the default source's core in a managed block that --remove-core+ * takes out; hermes writes .hermes.md at the git root and excludes it+ * locally. PGLite in-memory, no DATABASE_URL.+ */+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';+import { execFileSync } from 'child_process';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCompileContext, COMPILED_BLOCK_BEGIN } from '../src/commands/compile-context.ts';+import { compiledCoreRevision, readCompiledCoreRecords } from '../src/core/context/compiled-core.ts';++let engine: PGLiteEngine;+let cwd: string;+let fakeHome: string;+const saved: Record<string, string | undefined> = {};++beforeAll(async () => {+ for (const key of ['HOME', 'GBRAIN_HOME', 'GBRAIN_SOURCE', 'AGENT_VOICE_PII_BLOCKLIST', 'CODEX_HOME']) saved[key] = process.env[key];+ fakeHome = mkdtempSync(join(tmpdir(), 'compile-core-home-'));+ process.env.HOME = fakeHome;+ process.env.GBRAIN_HOME = fakeHome;+ process.env.CODEX_HOME = join(fakeHome, '.codex');+ delete process.env.GBRAIN_SOURCE;+ delete process.env.AGENT_VOICE_PII_BLOCKLIST;+ cwd = mkdtempSync(join(tmpdir(), 'compile-core-ws-'));+ execFileSync('git', ['init', '-q'], { cwd });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('people/ada-example', { type: 'note', title: 'Ada Example', compiled_truth: 'A collaborator profile used by the compile fixtures.' });+ await engine.putPage('concepts/core-prefs', {+ type: 'note', title: 'Working preferences', compiled_truth: 'Prefers short answers with the command to run.',+ frontmatter: { always_load: true },+ });+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; }+ rmSync(cwd, { recursive: true, force: true });+ rmSync(fakeHome, { recursive: true, force: true });+});++async function run(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {+ const out: string[] = [];+ const err: string[] = [];+ const so = spyOn(process.stdout, 'write').mockImplementation(((c: unknown) => { out.push(String(c)); return true; }) as typeof process.stdout.write);+ const se = spyOn(process.stderr, 'write').mockImplementation(((c: unknown) => { err.push(String(c)); return true; }) as typeof process.stderr.write);+ try {+ return { code: await runCompileContext(engine, args, { cwd }), stdout: out.join(''), stderr: err.join('') };+ } finally { so.mockRestore(); se.mockRestore(); }+}++describe('compile-context core arm', () => {+ test('without --include-core, core pages stay out of every arm and the header has no core', async () => {+ const r = await run(['--target', 'claude-code', '--stdout']);+ expect(r.code).toBe(0);+ expect(r.stdout).toContain('people/ada-example');+ expect(r.stdout).not.toContain('core-prefs');+ expect(compiledCoreRevision(r.stdout)).toBeNull();+ });++ test('--include-core renders core first in full, records the revision and the refresh command, byte-stable', async () => {+ const a = await run(['--target', 'claude-code', '--stdout', '--include-core']);+ const b = await run(['--target', 'claude-code', '--stdout', '--include-core']);+ expect(a.code).toBe(0);+ expect(b.stdout).toBe(a.stdout);+ expect(compiledCoreRevision(a.stdout)).toMatch(/^[0-9a-f]{16}$/);+ expect(a.stdout).toContain('refresh="gbrain compile-context --target claude-code --include-core"');+ const coreAt = a.stdout.indexOf('Prefers short answers');+ expect(coreAt).toBeGreaterThan(0);+ expect(coreAt).toBeLessThan(a.stdout.indexOf('people/ada-example'));+ expect(a.stdout.match(/core-prefs/g)?.length).toBe(1);+ });++ test('core is refused for a git-tracked output file', async () => {+ writeFileSync(join(cwd, 'AGENTS.md'), '# repo agents\n');+ execFileSync('git', ['add', 'AGENTS.md'], { cwd });+ const r = await run(['--target', 'codex', '--include-core']);+ expect(r.code).toBe(2);+ expect(r.stderr).toContain('tracked by git');+ expect(readFileSync(join(cwd, 'AGENTS.md'), 'utf8')).toBe('# repo agents\n');+ });++ test('codex-global writes the default core block into $CODEX_HOME/AGENTS.md; --remove-core takes it out', async () => {+ const path = join(fakeHome, '.codex', 'AGENTS.md');+ const r = await run(['--target', 'codex-global']);+ expect(r.code).toBe(0);+ const text = readFileSync(path, 'utf8');+ expect(text).toContain(COMPILED_BLOCK_BEGIN);+ expect(text).toContain('Prefers short answers');+ expect(text).not.toContain('people/ada-example');+ expect(readCompiledCoreRecords().map(x => x.target)).toContain('codex-global');+ writeFileSync(path, `# my notes\n${readFileSync(path, 'utf8')}`);+ expect((await run(['--target', 'codex-global', '--remove-core'])).code).toBe(0);+ expect(readFileSync(path, 'utf8')).toBe('# my notes\n');+ expect(readCompiledCoreRecords().map(x => x.target)).not.toContain('codex-global');+ });++ test('hermes writes .hermes.md at the git root and excludes it locally', async () => {+ const r = await run(['--target', 'hermes', '--include-core']);+ expect(r.code).toBe(0);+ expect(existsSync(join(cwd, '.hermes.md'))).toBe(true);+ expect(readFileSync(join(cwd, '.git', 'info', 'exclude'), 'utf8')).toContain('/.hermes.md');+ expect(execFileSync('git', ['status', '--porcelain'], { cwd, encoding: 'utf8' })).not.toContain('.hermes.md');+ });+});++describe('core_memory doctor check sees compiled copies', () => {+ test('a compiled file with an older core revision is named with its refresh command', async () => {+ const { coreMemoryCheck } = await import('../src/commands/doctor/checks/core-memory.ts');+ expect((await run(['--target', 'claude-code', '--include-core'])).code).toBe(0);+ expect((await coreMemoryCheck(engine)).message).not.toContain('older core revision');+ await engine.putPage('concepts/core-prefs', {+ type: 'note', title: 'Working preferences', compiled_truth: 'Prefers short answers; always include the command.',+ frontmatter: { always_load: true },+ });+ const check = await coreMemoryCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain-context.md carries an older core revision; refresh it with gbrain compile-context --target claude-code --include-core');+ });+});