Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(setup): write a managed brain-first instruction block into each harness's own instruction file by default (WIP)

garrytanc1eaff768d15
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 43cf61a904..ef0c5fee05 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -73,6 +73,21 @@ import {
type CodexSetupStep,
} from '../core/setup/codex.ts';
import type { CodexSetupEvent } from '../core/bootstrap/codex-hooks.ts';
+import {
+ brainFirstTarget,
+ describeBrainFirstOutcome,
+ isBrainFirstHarness,
+ priorBrainFirst,
+ readBrainFirstLedger,
+ removeBrainFirst,
+ renderBrainFirstSnippet,
+ resolveBrainFirstDecision,
+ syncBrainFirst,
+ type BrainFirstAccess,
+ type BrainFirstHarness,
+ type BrainFirstOutcome,
+} from '../core/setup/brain-first.ts';
+import { HARNESS_ADAPTERS } from '../core/harness/registry.ts';
export const SETUP_HELP = `gbrain setup <harness> — give an agent harness memory in one command
@@ -103,8 +118,31 @@ Flags:
--name NAME MCP server name (default gbrain); one name per install.
--source ID Pin the source the MCP server and hooks use.
--gbrain-bin PATH Absolute gbrain launcher (default: the gbrain on PATH).
- --remove Remove exactly what setup wrote (unchanged entries only). The
- brain and your notes stay. Combine with --dry-run to preview.
+ --remove Remove exactly what setup wrote (unchanged entries only), the
+ brain-first instruction block included. The brain and your
+ notes stay. Combine with --dry-run to preview.
+ --no-instructions Opt out of the brain-first instruction block (see below); an
+ existing block is removed and the opt-out is remembered.
+ GBRAIN_AGENT_INSTRUCTIONS=0 does the same.
+ --instructions Opt back in after an earlier --no-instructions.
+ --instructions-only Manage only the brain-first block: no brain, MCP or hook changes.
+ Works for a hosted connection too, and for any harness below.
+ --workspace DIR OpenClaw: the agent workspace whose AGENTS.md gets the block
+ (default: agents.defaults.workspace, then ~/.openclaw/workspace).
+
+Brain-first instructions: registering MCP is not enough; agents use a brain they
+are told about. By default setup also writes one short marked block into the
+harness's own instruction file (search the brain first, read the hit, fill gaps
+with other tools, apply your own access rules, finish the task). Text outside the
+markers is never touched; a re-run upgrades the block in place.
+ claude-code ~/.claude/CLAUDE.md (project scope: ./CLAUDE.local.md)
+ codex $CODEX_HOME/AGENTS.md (AGENTS.override.md when that exists)
+ opencode ~/.config/opencode/AGENTS.md
+ openclaw <workspace>/AGENTS.md
+ hermes $HERMES_HOME/SOUL.md (the identity text above it is left as it is)
+ cursor ./.cursor/rules/gbrain-brain-first.mdc (project rule)
+ Other clients (Claude Desktop, ChatGPT, Perplexity, Grok, Muse): --instructions-only
+ prints the block to paste into the client's custom instructions.
States: configured (entries written), connection-verified (the smoke answered),
native-pending (no observed push into a native session yet), native-verified (an
@@ -115,7 +153,9 @@ Refusals: setup never starts a second owner or a second brain. A hosted brain is
wired with gbrain connect <url> --harness <harness> --install; a running
serve --http owner with gbrain bootstrap harness --harness <harness> --yes.
-Supported harnesses: claude-code, codex. openclaw and hermes print their guide.
+Supported harnesses: claude-code, codex (MCP, hooks and instructions). opencode,
+openclaw, hermes and cursor: setup writes the instruction block and prints the MCP
+registration step from their guide.
setup and onboard differ: setup wires a harness to a brain; onboard (post-connect)
improves an existing brain's content.
`;
@@ -136,9 +176,12 @@ interface SetupFlags {
name: string;
source?: string;
gbrainBin?: string;
+ instructions?: boolean;
+ instructionsOnly: boolean;
+ workspace?: string;
}
-const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin']);
+const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace']);
function parseFlags(args: string[]): SetupFlags | string {
const value = (flag: string): string | undefined => {
@@ -156,6 +199,9 @@ function parseFlags(args: string[]): SetupFlags | string {
if (source !== undefined && !isValidSourceId(source)) return `invalid --source '${source}'`;
if (args.includes('--capture') && args.includes('--no-capture')) return 'pass --capture or --no-capture, not both';
if (args.includes('--providers') && args.includes('--no-providers')) return 'pass --providers or --no-providers, not both';
+ if (args.includes('--instructions') && args.includes('--no-instructions')) return 'pass --instructions or --no-instructions, not both';
+ const workspace = value('--workspace');
+ if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';
return {
harness: positionals[0],
dryRun: args.includes('--dry-run'),
@@ -169,6 +215,9 @@ function parseFlags(args: string[]): SetupFlags | string {
name,
source,
gbrainBin: value('--gbrain-bin'),
+ instructions: args.includes('--instructions') ? true : args.includes('--no-instructions') ? false : undefined,
+ instructionsOnly: args.includes('--instructions-only'),
+ workspace,
};
}
@@ -274,6 +323,11 @@ export async function runSetup(args: string[]): Promise<number> {
return 2;
}
const flags = parsed;
+ const adapter = HARNESS_ADAPTERS.find((a) => a.id === flags.harness);
+ const mcpWired = flags.harness === 'claude-code' || flags.harness === 'codex';
+ if ((flags.instructionsOnly && (isBrainFirstHarness(flags.harness) || adapter)) || (isBrainFirstHarness(flags.harness) && !mcpWired)) {
+ return runInstructionsOnly(flags, out);
+ }
if (!isSetupHarness(flags.harness) || capabilityRows(flags.harness).every((r) => r.setup !== 'supported')) {
const rows = isSetupHarness(flags.harness) ? capabilityRows(flags.harness) : [];
const guide = rows[0]?.docs;
@@ -377,7 +431,8 @@ export async function runSetup(args: string[]): Promise<number> {
{ step: 'hooks', action: found.hooksCurrent ? 'keep' : 'write', detail: plan.events.length ? `${plan.events.join(', ')} in ${found.settingsPath}` : `no hooks (${found.settingsPath})` },
...Object.entries(found.edited).map(([event]) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),
];
- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });
+ const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir });
+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions });
}
let notices: Notice[] = [];
@@ -386,7 +441,8 @@ export async function runSetup(args: string[]): Promise<number> {
beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out, 'claude-code'); } : undefined,
});
for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);
- if (!result.changed) say(out, 'Nothing changed: this install is already wired.');
+ const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir });
+ if (!result.changed && !instructionsChanged(instructions)) say(out, 'Nothing changed: this install is already wired.');
let verify: { ok: boolean; reason: string; message: string } | null;
if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Claude Code session and check /mcp lists gbrain.` };
@@ -397,7 +453,7 @@ export async function runSetup(args: string[]): Promise<number> {
}
const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];
const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,
- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })) });
+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions });
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
if (e instanceof OperationError) return refuse(e, out);
@@ -518,7 +574,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
{ step: 'trust', action: found.trustCurrent ? 'keep' : 'write', detail: `trust entries for setup's groups in ${found.configPath}` },
...Object.keys(found.edited).map((event) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),
];
- return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });
+ const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {});
+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions });
}
let notices: Notice[] = [];
@@ -528,7 +585,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
});
for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);
for (const n of result.notes) say(out, `note: ${n}`);
- if (!result.changed) say(out, 'Nothing changed: this install is already wired.');
+ const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {});
+ if (!result.changed && !instructionsChanged(instructions)) say(out, 'Nothing changed: this install is already wired.');
let verify: { ok: boolean; reason: string; message: string };
if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Codex session and check /mcp lists gbrain.` };
@@ -540,7 +598,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
const push = capabilityRows('codex')[0]!.push;
const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];
const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,
- steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved });
+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions });
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
if (e instanceof OperationError) return refuse(e, out);
@@ -562,8 +620,9 @@ async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | nu
const r = await removeCodexSetup(receipt, receiptPath, { dryRun: flags.dryRun });
for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);
for (const n of r.notes) say(out, `note: ${n}`);
+ const instructions = removeBrainFirstFor('codex', {}, flags);
say(out, 'The brain, its notes and unrelated Codex settings were left as they were.');
- return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved });
+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions });
}
function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {
@@ -590,13 +649,86 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,
}
const r = await removeClaudeSetup(receipt, receiptPath, { dryRun: flags.dryRun });
for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);
+ const instructions = removeBrainFirstFor('claude-code', { scope: receipt.scope, projectDir: receipt.project_dir }, flags);
say(out, 'The brain, its notes and unrelated Claude Code settings were left as they were.');
- return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved });
+ return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved, instructions });
+}
+
+/** The brain-first block for this run: decided from flags, env and the ledger, then applied (or previewed under --dry-run). */
+function brainFirstFor(harness: BrainFirstHarness, flags: SetupFlags, access: BrainFirstAccess, where: { scope?: WiringScope; projectDir?: string }): BrainFirstOutcome | null {
+ const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });
+ if ('error' in target) return null;
+ const decision = resolveBrainFirstDecision(flags.instructions, priorBrainFirst(harness, target.path));
+ return syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });
+}
+
+/** The uninstall half: the block setup wrote for this harness and scope, at the path the ledger recorded. */
+function removeBrainFirstFor(harness: BrainFirstHarness, where: { scope?: WiringScope; projectDir?: string }, flags: SetupFlags): BrainFirstOutcome | null {
+ const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });
+ const path = 'error' in target ? readBrainFirstLedger().find((e) => e.harness === harness)?.path : target.path;
+ return path ? removeBrainFirst({ harness, path, dryRun: flags.dryRun }) : null;
+}
+
+const instructionsChanged = (o: BrainFirstOutcome | null): boolean => !!o && (o.action === 'write' || o.action === 'remove');
+
+function describeInstructions(o: BrainFirstOutcome, dryRun: boolean): string {
+ const how = o.decision.value === 'accepted' ? 'opt out with --no-instructions' : 'opt back in with --instructions';
+ return `${describeBrainFirstOutcome(o, dryRun)} [${o.decision.source}; ${how}]`;
+}
+
+/**
+ * `--instructions-only`, and the harnesses whose MCP registration setup does
+ * not write (opencode, openclaw, hermes, cursor): manage the brain-first
+ * block and nothing else. A client with no instruction file gbrain can write
+ * (Claude Desktop, ChatGPT, …) gets the block printed to paste.
+ */
+async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number> {
+ const harness = flags.harness!;
+ const adapter = HARNESS_ADAPTERS.find((a) => a.id === harness)!;
+ const envSurface = process.env.GBRAIN_SURFACE;
+ const surface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined);
+ const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}) };
+ const mcp = { setup: flags.instructionsOnly ? 'unchanged' as const : 'manual' as const, docs: adapter.guide };
+ if (!isBrainFirstHarness(harness)) {
+ const snippet = renderBrainFirstSnippet(harness, access);
+ if (out.json) {
+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true,
+ instructions: { action: 'print', snippet, where: `${adapter.label}'s custom or system instructions` }, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ return 0;
+ }
+ console.log(`${adapter.label} has no instruction file gbrain can write. Paste this block into its custom or system instructions (keep the markers so a later paste replaces it):\n`);
+ console.log(snippet);
+ console.log(`Connect its MCP server with ${adapter.guide}.`);
+ return 0;
+ }
+ const projectDir = harness === 'cursor' || (harness === 'claude-code' && flags.scope === 'project') ? realpathSync(process.cwd()) : undefined;
+ const where = { scope: harness === 'claude-code' ? flags.scope ?? 'user' : undefined, projectDir };
+ const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });
+ if ('error' in target) {
+ return refuse(opError('invalid_params', target.error, 'Pass --workspace <absolute dir> for the agent whose AGENTS.md should carry the block.'), out);
+ }
+ let instructions: BrainFirstOutcome | null;
+ if (flags.remove) instructions = removeBrainFirstFor(harness, where, flags);
+ else {
+ say(out, `Target (${adapter.label}): ${target.path} (${target.role})`);
+ const decision = resolveBrainFirstDecision(flags.instructions, priorBrainFirst(harness, target.path));
+ instructions = syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });
+ }
+ const code = instructions?.action === 'preserve' ? 1 : 0;
+ if (out.json) {
+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ return code;
+ }
+ if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));
+ if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);
+ if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');
+ return code;
}
async function finish(out: Out, doc: {
harness?: SetupHarnessId; dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: Array<{ step: string; action: string; detail: string }>; states: string[];
verify: { ok: boolean; reason: string; message: string } | null; notices: Notice[]; notes: string[]; preserved?: unknown[];
+ instructions?: BrainFirstOutcome | null;
}): Promise<number> {
const harness = doc.harness ?? 'claude-code';
const state = doc.states.at(-1) ?? null;
@@ -604,12 +736,13 @@ async function finish(out: Out, doc: {
await writeJsonDocument(`${JSON.stringify({
harness, dry_run: doc.dryRun, remove: doc.remove ?? false,
...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),
- steps: doc.steps, preserved: doc.preserved ?? [], states: doc.states, state, verify: doc.verify,
+ steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, states: doc.states, state, verify: doc.verify,
capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),
}, null, 2)}\n`, (t) => process.stdout.write(t));
return 0;
}
+ if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));
if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);
if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);
if (state && !doc.remove) say(out, harness === 'codex'
diff --git a/src/core/bootstrap/instructions-block.ts b/src/core/bootstrap/instructions-block.ts
index 7ea2fcfd57..d4869789cf 100644
--- a/src/core/bootstrap/instructions-block.ts
+++ b/src/core/bootstrap/instructions-block.ts
@@ -12,13 +12,11 @@
* (src/core/facts/writeback-instructions.ts) so this surface structurally
* cannot drift from the MCP instructions surface.
*
- * Splice discipline copied VERBATIM from spliceCompiledBlock
- * (src/commands/compile-context.ts): exact-line marker match at column 0; no
- * markers → append a fresh block at EOF; exactly one in-order pair → replace
- * the interior; anything else (duplicates, an orphan, out of order) → THROW —
- * those are hand-edits we must not guess through. Marker-equal lines inside
- * the body are neutralized with a leading space so a body excerpt can never
- * self-wedge the next splice.
+ * Splice discipline lives in src/core/managed-block.ts (shared with the
+ * brain-first block): exact-line marker match at column 0; no markers →
+ * append a fresh block at EOF; exactly one in-order pair → replace the
+ * interior; anything else (duplicates, an orphan, out of order) → THROW.
+ * Marker-equal lines inside the body are neutralized with a leading space.
*
* The block header names the serve endpoint [OV-A3]: on a multi-brain box the
* LAST `bootstrap harness` run wins the block, and the named URL is what
@@ -28,83 +26,31 @@
import { existsSync, readFileSync } from 'node:fs';
import { buildAmbientWritebackSection } from '../facts/writeback-instructions.ts';
import { atomicWriteTextFile } from './atomic-write.ts';
+import { blockPresent, probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
export const AMBIENT_WRITEBACK_BLOCK_BEGIN = '<!-- gbrain:ambient-writeback:begin -->';
export const AMBIENT_WRITEBACK_BLOCK_END = '<!-- gbrain:ambient-writeback:end -->';
-function damagedMarkersError(begins: number, ends: number): Error {
- return new Error(
- `the gbrain ambient-writeback markers in this file are damaged ` +
- `(${begins} begin / ${ends} end` +
- `${begins === 1 && ends === 1 ? ', out of order' : ''}) — ` +
- `the managed block was hand-edited. Fix the markers (or delete the whole block, ` +
- `markers included) and re-run \`gbrain bootstrap harness\`.`,
- );
-}
-
-/**
- * The ONE marker scan (splice, remove, status probes, and doctor's drift
- * compare all consume it — divergent hand-rolled scans would classify a
- * damaged file differently per surface). 'absent' = no marker lines at all;
- * a well-formed single in-order pair returns its indexes; anything else
- * (duplicates, an orphan, out of order) THROWS the damaged-markers error.
- */
-function scanMarkers(lines: string[]): { begin: number; end: number } | 'absent' {
- const begins: number[] = [];
- const ends: number[] = [];
- lines.forEach((line, i) => {
- if (line === AMBIENT_WRITEBACK_BLOCK_BEGIN) begins.push(i);
- if (line === AMBIENT_WRITEBACK_BLOCK_END) ends.push(i);
- });
- if (begins.length === 0 && ends.length === 0) return 'absent';
- if (begins.length !== 1 || ends.length !== 1 || begins[0] > ends[0]) {
- throw damagedMarkersError(begins.length, ends.length);
- }
- return { begin: begins[0], end: ends[0] };
-}
+const AMBIENT_MARKERS: BlockMarkers = {
+ begin: AMBIENT_WRITEBACK_BLOCK_BEGIN,
+ end: AMBIENT_WRITEBACK_BLOCK_END,
+ label: 'ambient-writeback',
+ rerun: 'gbrain bootstrap harness',
+};
/** Non-throwing probe for status/doctor surfaces: one vocabulary for the
* three states, with the interior when present. */
-export function probeAmbientBlock(
- text: string,
-): { state: 'absent' | 'present' | 'damaged'; interior?: string } {
- const lines = text.split('\n');
- try {
- const scan = scanMarkers(lines);
- if (scan === 'absent') return { state: 'absent' };
- return { state: 'present', interior: lines.slice(scan.begin + 1, scan.end).join('\n') };
- } catch {
- return { state: 'damaged' };
- }
+export function probeAmbientBlock(text: string): { state: 'absent' | 'present' | 'damaged'; interior?: string } {
+ return probeBlock(AMBIENT_MARKERS, text);
}
/**
* Splice `body` into the managed block inside `existing`. No markers →
* append a fresh block at EOF. Exactly one in-order pair → replace the
- * interior. Anything else → THROW (spliceCompiledBlock discipline).
+ * interior. Anything else → THROW (managed-block.ts discipline).
*/
export function spliceAmbientWritebackBlock(existing: string, body: string): string {
- const lines = existing.length > 0 ? existing.split('\n') : [];
- const scan = scanMarkers(lines);
- // Neutralize marker-equal lines INSIDE the body: a body line that is
- // exactly a marker string would land as a real marker line — the first
- // splice succeeds, and every run after that sees damaged markers
- // (self-wedge until hand-edit). A leading space keeps the text visible but
- // fails the exact-line match. Deterministic, so re-splices compare
- // like-for-like.
- const neutralized = body
- .split('\n')
- .map((l) => (l === AMBIENT_WRITEBACK_BLOCK_BEGIN || l === AMBIENT_WRITEBACK_BLOCK_END ? ` ${l}` : l))
- .join('\n');
- const interior = neutralized.endsWith('\n') ? neutralized.slice(0, -1) : neutralized;
- if (scan === 'absent') {
- const head =
- existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
- return `${head}${AMBIENT_WRITEBACK_BLOCK_BEGIN}\n${interior}\n${AMBIENT_WRITEBACK_BLOCK_END}\n`;
- }
- const out = [...lines.slice(0, scan.begin + 1), ...interior.split('\n'), ...lines.slice(scan.end)];
- const joined = out.join('\n');
- return joined.endsWith('\n') ? joined : `${joined}\n`;
+ return spliceBlock(AMBIENT_MARKERS, existing, body);
}
/**
@@ -114,24 +60,13 @@ export function spliceAmbientWritebackBlock(existing: string, body: string): str
* callers — a file left empty of our content stays in place.
*/
export function removeAmbientWritebackBlock(existing: string): { text: string; removed: boolean } {
- const lines = existing.length > 0 ? existing.split('\n') : [];
- const scan = scanMarkers(lines);
- if (scan === 'absent') return { text: existing, removed: false };
- // Consume at most one trailing BLANK line after the end marker. The final
- // '' element of a newline-terminated file is the trailing-newline sentinel,
- // not a blank line — only consume when something follows it.
- let after = scan.end + 1;
- if (after < lines.length - 1 && lines[after] === '') after++;
- const out = [...lines.slice(0, scan.begin), ...lines.slice(after)];
- return { text: out.join('\n'), removed: true };
+ return removeBlock(AMBIENT_MARKERS, existing);
}
/** True when any exact marker line is present (well-formed OR damaged) —
* the cheap probe callers run before locking for a strip. */
export function ambientBlockPresent(text: string): boolean {
- return text
- .split('\n')
- .some((l) => l === AMBIENT_WRITEBACK_BLOCK_BEGIN || l === AMBIENT_WRITEBACK_BLOCK_END);
+ return blockPresent(AMBIENT_MARKERS, text);
}
export interface AmbientInstructionBlockOpts {
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index fde20210b6..3a046ef315 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -121,7 +121,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
+ 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--workspace', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
diff --git a/src/core/managed-block.ts b/src/core/managed-block.ts
new file mode 100644
index 0000000000..92d46cb9bd
--- /dev/null
+++ b/src/core/managed-block.ts
@@ -0,0 +1,91 @@
+/**
+ * managed-block.ts — one marker-delimited block inside a text file the user
+ * also edits (CLAUDE.md, AGENTS.md, SOUL.md, a Cursor rule).
+ *
+ * Discipline (shared by the ambient-writeback block and the brain-first
+ * block): exact-line marker match at column 0; no markers → append a fresh
+ * block at EOF; exactly one in-order pair → replace the interior; anything
+ * else (duplicates, an orphan, out of order) → THROW, because those are
+ * hand-edits we must not guess through. Marker-equal lines inside the body
+ * are neutralized with a leading space so a body can never self-wedge the
+ * next splice. Text outside the markers is never touched.
+ */
+
+export interface BlockMarkers {
+ begin: string;
+ end: string;
+ /** Names the block and the command that rewrites it, for the damaged-markers error. */
+ label: string;
+ rerun: string;
+}
+
+function damagedMarkersError(m: BlockMarkers, begins: number, ends: number): Error {
+ return new Error(
+ `the gbrain ${m.label} markers in this file are damaged ` +
+ `(${begins} begin / ${ends} end` +
+ `${begins === 1 && ends === 1 ? ', out of order' : ''}) — ` +
+ `the managed block was hand-edited. Fix the markers (or delete the whole block, ` +
+ `markers included) and re-run \`${m.rerun}\`.`,
+ );
+}
+
+function scanMarkers(m: BlockMarkers, lines: string[]): { begin: number; end: number } | 'absent' {
+ const begins: number[] = [];
+ const ends: number[] = [];
+ lines.forEach((line, i) => {
+ if (line === m.begin) begins.push(i);
+ if (line === m.end) ends.push(i);
+ });
+ if (begins.length === 0 && ends.length === 0) return 'absent';
+ if (begins.length !== 1 || ends.length !== 1 || begins[0] > ends[0]) throw damagedMarkersError(m, begins.length, ends.length);
+ return { begin: begins[0], end: ends[0] };
+}
+
+/** Non-throwing probe: absent, present (with its interior) or damaged. */
+export function probeBlock(m: BlockMarkers, text: string): { state: 'absent' | 'present' | 'damaged'; interior?: string } {
+ const lines = text.split('\n');
+ try {
+ const scan = scanMarkers(m, lines);
+ if (scan === 'absent') return { state: 'absent' };
+ return { state: 'present', interior: lines.slice(scan.begin + 1, scan.end).join('\n') };
+ } catch {
+ return { state: 'damaged' };
+ }
+}
+
+/** Splice `body` into the block; no markers → append at EOF; damaged markers throw. */
+export function spliceBlock(m: BlockMarkers, existing: string, body: string): string {
+ const lines = existing.length > 0 ? existing.split('\n') : [];
+ const scan = scanMarkers(m, lines);
+ const neutralized = body
+ .split('\n')
+ .map((l) => (l === m.begin || l === m.end ? ` ${l}` : l))
+ .join('\n');
+ const interior = neutralized.endsWith('\n') ? neutralized.slice(0, -1) : neutralized;
+ if (scan === 'absent') {
+ const head = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ return `${head}${m.begin}\n${interior}\n${m.end}\n`;
+ }
+ const out = [...lines.slice(0, scan.begin + 1), ...interior.split('\n'), ...lines.slice(scan.end)];
+ const joined = out.join('\n');
+ return joined.endsWith('\n') ? joined : `${joined}\n`;
+}
+
+/**
+ * Strip the block (markers, interior and at most one trailing blank line).
+ * No markers → `removed: false` with the text unchanged; damaged markers throw.
+ */
+export function removeBlock(m: BlockMarkers, existing: string): { text: string; removed: boolean } {
+ const lines = existing.length > 0 ? existing.split('\n') : [];
+ const scan = scanMarkers(m, lines);
+ if (scan === 'absent') return { text: existing, removed: false };
+ let after = scan.end + 1;
+ if (after < lines.length - 1 && lines[after] === '') after++;
+ const out = [...lines.slice(0, scan.begin), ...lines.slice(after)];
+ return { text: out.join('\n'), removed: true };
+}
+
+/** True when any exact marker line is present, well-formed or damaged. */
+export function blockPresent(m: BlockMarkers, text: string): boolean {
+ return text.split('\n').some((l) => l === m.begin || l === m.end);
+}
diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.ts
new file mode 100644
index 0000000000..c60bbc61a1
--- /dev/null
+++ b/src/core/setup/brain-first.ts
@@ -0,0 +1,331 @@
+/**
+ * brain-first.ts — the managed brain-first instruction block that every
+ * harness install writes into the harness's own instruction surface.
+ *
+ * Why: registering the MCP server is not enough. In a preregistered harness
+ * run, agents with gbrain registered and no instruction reached for it in
+ * 1 trial of 100 (no harness acts on the MCP `initialize` instructions),
+ * and 92 of 100 once one short rule sat in the agent's own instructions.
+ * So `gbrain setup <harness>`, `gbrain connect --install` and
+ * `gbrain bootstrap harness` write this block by default; `--no-instructions`
+ * (or GBRAIN_AGENT_INSTRUCTIONS=0) opts out and removes it.
+ *
+ * Ownership is by markers (src/core/managed-block.ts): the interior is
+ * gbrain's and is replaced on upgrade; text outside the markers is never
+ * touched. The ledger at <configDir>/agent-instructions.json records each
+ * surface's decision (installed or declined), the access the block names and
+ * whether gbrain created the file, so a re-run keeps an opt-out, `--remove`
+ * deletes a file only gbrain created, and doctor's harness_wiring check can
+ * tell current from stale.
+ *
+ * The text stays short on purpose: it is loaded into every turn.
+ */
+import { existsSync, readFileSync, unlinkSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
+import { claudeUserMemoryPath, codexAgentsOverridePath, codexGlobalAgentsPath, opencodeConfigDir } from '../bootstrap/host-specs.ts';
+import { configDir } from '../config.ts';
+import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
+import { ensureGitExcluded } from '../context/compiled-core.ts';
+import type { McpSurface } from '../../mcp/surface.ts';
+
+export const BRAIN_FIRST_VERSION = 1;
+export const BRAIN_FIRST_BEGIN = '<!-- gbrain:brain-first:begin -->';
+export const BRAIN_FIRST_END = '<!-- gbrain:brain-first:end -->';
+export const BRAIN_FIRST_OPT_OUT_ENV = 'GBRAIN_AGENT_INSTRUCTIONS';
+const MARKERS: BlockMarkers = { begin: BRAIN_FIRST_BEGIN, end: BRAIN_FIRST_END, label: 'brain-first', rerun: 'gbrain setup <harness> --instructions-only' };
+const LEDGER_FILE = 'agent-instructions.json';
+
+/** Harnesses whose instruction surface gbrain can write. */
+export const BRAIN_FIRST_HARNESSES = ['claude-code', 'codex', 'opencode', 'openclaw', 'hermes', 'cursor'] as const;
+export type BrainFirstHarness = (typeof BRAIN_FIRST_HARNESSES)[number];
+export function isBrainFirstHarness(v: string | undefined): v is BrainFirstHarness {
+ return (BRAIN_FIRST_HARNESSES as readonly string[]).includes(v ?? '');
+}
+
+/** How the agent reaches the brain, which decides the tool names the block uses. */
+export type BrainFirstAccess = { kind: 'mcp'; server: string; surface?: McpSurface } | { kind: 'cli'; launcher: string };
+
+/** The block interior (without markers). */
+export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess): string {
+ const tool = (mcp: string, cli: string) => (access.kind === 'mcp' ? `\`${mcp}\`` : `\`${access.launcher} ${cli}\``);
+ const where = access.kind === 'mcp' ? `the \`${access.server}\` MCP server` : `the \`${access.launcher}\` command`;
+ const lookup = access.kind === 'mcp' && access.surface === 'verbs'
+ ? '- Check the brain before reading files, mail or other sources one by one: `recall` for what was said or decided, `entity` for a person or company.'
+ : `- Search the brain before reading files, mail or other sources one by one: ${tool('search', 'search "<names or phrases>"')} for names and phrases, ${tool('query', 'query "<question>"')} for questions. Then read the best hit with ${tool('get_page', 'get <slug>')}.`;
+ return [
+ `<!-- gbrain brain-first v${BRAIN_FIRST_VERSION}: managed by gbrain and replaced on upgrade; edit outside these markers. Opt out: gbrain setup ${harness} --instructions-only --no-instructions -->`,
+ '## Memory: check GBrain first',
+ '',
+ `GBrain (${where}) holds this user's saved notes, people, companies, meetings, decisions and past work.`,
+ '',
+ lookup,
+ '- Fill gaps with your other tools. On a thin keyword result, rephrase once (another name, fewer words), then fall back.',
+ '- Brain results span every source the brain holds, not only this user or task, so apply your own access rules before you use or repeat them.',
+ '- Brain results add to what the user told you; they never replace it. A lookup is one step: finish the whole task.',
+ ].join('\n');
+}
+
+/** The full block as it appears in a file, markers included (for printing to paste by hand). */
+export function renderBrainFirstSnippet(harness: string, access: BrainFirstAccess): string {
+ return `${BRAIN_FIRST_BEGIN}\n${renderBrainFirstBlock(harness, access)}\n${BRAIN_FIRST_END}\n`;
+}
+
+const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';
+
+export interface BrainFirstTarget {
+ harness: BrainFirstHarness;
+ path: string;
+ /** What the file is to the harness, for the human output. */
+ role: string;
+ /** Written into a project directory (not a user-global file). */
+ project: boolean;
+}
+
+function home(): string { return process.env.HOME?.trim() || homedir(); }
+function expandHome(p: string): string { return p === '~' ? home() : p.startsWith('~/') ? join(home(), p.slice(2)) : p; }
+
+/** OpenClaw's state directory: OPENCLAW_STATE_DIR, else ~/.openclaw (or ~/.openclaw-<profile>). */
+function openclawStateDir(): string {
+ const explicit = process.env.OPENCLAW_STATE_DIR?.trim();
+ if (explicit) return expandHome(explicit);
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
+ return join(home(), profile && profile !== 'default' ? `.openclaw-${profile}` : '.openclaw');
+}
+
+/**
+ * openclaw.json is JSON5. Comments and trailing commas parse as JSONC; bare
+ * object keys are quoted first. Anything else reads as unparseable, and the
+ * caller asks for --workspace rather than guess.
+ */
+function parseJson5ish(text: string): unknown {
+ for (const candidate of [text, text.replace(/([{,]\s*)([A-Za-z_$][\w$-]*)\s*:/g, '$1"$2":')]) {
+ const errors: ParseError[] = [];
+ const value = parseJsonc(candidate, errors, { allowTrailingComma: true });
+ if (errors.length === 0) return value;
+ }
+ return undefined;
+}
+
+/**
+ * The OpenClaw workspace whose AGENTS.md (its operating instructions, loaded
+ * every session and by subagents) gets the block: an explicit
+ * `agents.defaults.workspace` in openclaw.json, else OPENCLAW_WORKSPACE_DIR,
+ * else <state dir>/workspace. A roster of several agents has no single
+ * workspace, so the caller must name one.
+ */
+export function resolveOpenclawWorkspace(): { path: string } | { error: string } {
+ const configPath = join(openclawStateDir(), 'openclaw.json');
+ let configured: string | undefined;
+ if (existsSync(configPath)) {
+ const cfg = parseJson5ish(readFileSync(configPath, 'utf8')) as { agents?: { defaults?: { workspace?: unknown }; list?: unknown; entries?: unknown } } | undefined;
+ if (!cfg || typeof cfg !== 'object') return { error: `${configPath} could not be read as JSON, so the workspace is unknown. Pass --workspace <dir>.` };
+ const roster = Array.isArray(cfg.agents?.list) ? cfg.agents.list.length : cfg.agents?.entries && typeof cfg.agents.entries === 'object' ? Object.keys(cfg.agents.entries).length : 0;
+ if (roster > 1) return { error: `${configPath} defines ${roster} agents, each with its own workspace. Pass --workspace <dir> for the agent that should use gbrain.` };
+ if (typeof cfg.agents?.defaults?.workspace === 'string' && cfg.agents.defaults.workspace.trim()) configured = cfg.agents.defaults.workspace.trim();
+ }
+ const fromEnv = process.env.OPENCLAW_WORKSPACE_DIR?.trim();
+ return { path: expandHome(configured ?? fromEnv ?? join(openclawStateDir(), 'workspace')) };
+}
+
+/** The instruction file a harness loads every session, or an error naming what to pass. */
+export function brainFirstTarget(harness: BrainFirstHarness, opts: { scope?: 'user' | 'project'; projectDir?: string; workspace?: string } = {}): BrainFirstTarget | { error: string } {
+ const projectDir = opts.projectDir ?? process.cwd();
+ switch (harness) {
+ case 'claude-code':
+ return opts.scope === 'project'
+ ? { harness, path: join(projectDir, 'CLAUDE.local.md'), role: 'Claude Code local project instructions', project: true }
+ : { harness, path: claudeUserMemoryPath(), role: 'Claude Code user instructions', project: false };
+ case 'codex': {
+ const override = codexAgentsOverridePath();
+ return existsSync(override)
+ ? { harness, path: override, role: 'Codex user instructions (AGENTS.override.md, which Codex loads instead of AGENTS.md)', project: false }
+ : { harness, path: codexGlobalAgentsPath(), role: 'Codex user instructions', project: false };
+ }
+ case 'opencode':
+ return { harness, path: join(opencodeConfigDir(), 'AGENTS.md'), role: 'opencode global rules', project: false };
+ case 'openclaw': {
+ const ws = opts.workspace ? { path: expandHome(opts.workspace) } : resolveOpenclawWorkspace();
+ if ('error' in ws) return ws;
+ return { harness, path: join(ws.path, 'AGENTS.md'), role: 'OpenClaw workspace operating instructions', project: false };
+ }
+ case 'hermes': {
+ const hermesHome = process.env.HERMES_HOME?.trim() ? expandHome(process.env.HERMES_HOME.trim()) : join(home(), '.hermes');
+ return { harness, path: join(hermesHome, 'SOUL.md'), role: 'Hermes system prompt (SOUL.md, slot 1; the identity text above the block is left as it is)', project: false };
+ }
+ case 'cursor':
+ return { harness, path: join(projectDir, '.cursor', 'rules', 'gbrain-brain-first.mdc'), role: 'Cursor project rule (always applied)', project: true };
+ }
+}
+
+// ── Ledger ────────────────────────────────────────────────────────────────
+
+export interface BrainFirstLedgerEntry {
+ harness: string;
+ path: string;
+ status: 'installed' | 'declined';
+ block_version: number;
+ access: BrainFirstAccess;
+ /** The command that last wrote or declined it. */
+ writer: string;
+ /** gbrain created the file, so removal may delete it once nothing else is left. */
+ created_file: boolean;
+ updated_at: string;
+}
+
+interface Ledger { version: 1; entries: BrainFirstLedgerEntry[] }
+
+export function brainFirstLedgerPath(): string { return join(configDir(), LEDGER_FILE); }
+
+export function readBrainFirstLedger(): BrainFirstLedgerEntry[] {
+ const path = brainFirstLedgerPath();
+ if (!existsSync(path)) return [];
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as Ledger;
+ return Array.isArray(raw?.entries) ? raw.entries.filter((e) => e && typeof e.path === 'string' && typeof e.harness === 'string') : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeLedger(entries: BrainFirstLedgerEntry[]): void {
+ atomicWriteTextFile(brainFirstLedgerPath(), `${JSON.stringify({ version: 1, entries }, null, 2)}\n`, { freshMode: 0o600 });
+}
+
+function upsertLedger(entry: BrainFirstLedgerEntry): void {
+ writeLedger([...readBrainFirstLedger().filter((e) => !(e.harness === entry.harness && e.path === entry.path)), entry]);
+}
+
+function dropLedger(harness: string, path: string): void {
+ const all = readBrainFirstLedger();
+ const rest = all.filter((e) => !(e.harness === harness && e.path === path));
+ if (rest.length !== all.length) writeLedger(rest);
+}
+
+export function priorBrainFirst(harness: string, path: string): BrainFirstLedgerEntry | undefined {
+ return readBrainFirstLedger().find((e) => e.harness === harness && e.path === path);
+}
+
+// ── Decision, inspection, sync, removal ───────────────────────────────────
+
+export type BrainFirstDecisionSource = 'flag' | 'default' | 'prior' | 'opt_out';
+export interface BrainFirstDecision { value: 'accepted' | 'declined'; source: BrainFirstDecisionSource }
+
+/** --instructions / --no-instructions win, then GBRAIN_AGENT_INSTRUCTIONS=0, then a recorded decision, then on by default. */
+export function resolveBrainFirstDecision(flag: boolean | undefined, prior: BrainFirstLedgerEntry | undefined): BrainFirstDecision {
+ if (flag !== undefined) return { value: flag ? 'accepted' : 'declined', source: 'flag' };
+ if (process.env[BRAIN_FIRST_OPT_OUT_ENV] === '0') return { value: 'declined', source: 'opt_out' };
+ if (prior) return { value: prior.status === 'declined' ? 'declined' : 'accepted', source: 'prior' };
+ return { value: 'accepted', source: 'default' };
+}
+
+export type BrainFirstState = 'no_file' | 'absent' | 'current' | 'stale' | 'damaged';
+
+/** Is the block in `path` the one gbrain would write for this access? */
+export function inspectBrainFirst(path: string, expected?: string): { state: BrainFirstState; version?: number } {
+ if (!existsSync(path)) return { state: 'no_file' };
+ const probe = probeBlock(MARKERS, readFileSync(path, 'utf8'));
+ if (probe.state !== 'present') return { state: probe.state };
+ const version = Number(/gbrain brain-first v(\d+)/.exec(probe.interior ?? '')?.[1] ?? 0);
+ const current = expected !== undefined ? probe.interior === expected : version === BRAIN_FIRST_VERSION;
+ return { state: current ? 'current' : 'stale', version };
+}
+
+export interface BrainFirstOutcome {
+ harness: string;
+ path: string;
+ role: string;
+ decision: BrainFirstDecision;
+ /** write: added or upgraded; keep: already current; remove: opted out, block deleted; skip: nothing to do; preserve: left alone (see detail). */
+ action: 'write' | 'keep' | 'remove' | 'skip' | 'preserve';
+ state_before: BrainFirstState;
+ detail: string;
+}
+
+/**
+ * Make the surface match the decision: write or upgrade the block when
+ * accepted, strip it when declined, record the decision. Never throws: a
+ * damaged block or an unwritable file is reported as `preserve` so the rest
+ * of the install still finishes.
+ */
+export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFirstAccess; decision: BrainFirstDecision; writer: string; dryRun: boolean }): BrainFirstOutcome {
+ const { target, access, decision } = opts;
+ const body = renderBrainFirstBlock(target.harness, access);
+ const before = inspectBrainFirst(target.path, body);
+ const out = (action: BrainFirstOutcome['action'], detail: string): BrainFirstOutcome =>
+ ({ harness: target.harness, path: target.path, role: target.role, decision, action, state_before: before.state, detail });
+ const prior = priorBrainFirst(target.harness, target.path);
+ const record = (status: 'installed' | 'declined', created: boolean) => {
+ if (opts.dryRun) return;
+ upsertLedger({ harness: target.harness, path: target.path, status, block_version: BRAIN_FIRST_VERSION, access, writer: opts.writer, created_file: created, updated_at: new Date().toISOString() });
+ };
+ try {
+ if (before.state === 'damaged') {
+ return out('preserve', `the brain-first markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`);
+ }
+ if (decision.value === 'declined') {
+ if (before.state === 'no_file' || before.state === 'absent') {
+ record('declined', false);
+ return out('skip', `no brain-first block in ${target.path}; opt-out recorded`);
+ }
+ const existing = readFileSync(target.path, 'utf8');
+ if (!opts.dryRun) {
+ const stripped = removeBlock(MARKERS, existing).text;
+ if ((prior?.created_file ?? false) && (stripped.trim() === '' || stripped === CURSOR_HEAD)) unlinkSync(target.path);
+ else atomicWriteTextFile(target.path, stripped);
+ }
+ record('declined', false);
+ return out('remove', `brain-first block from ${target.path}; opt-out recorded`);
+ }
+ if (before.state === 'current') {
+ record('installed', prior?.created_file ?? false);
+ return out('keep', `brain-first block in ${target.path} is current`);
+ }
+ const created = before.state === 'no_file';
+ if (!opts.dryRun) {
+ const existing = created ? (target.harness === 'cursor' ? CURSOR_HEAD : '') : readFileSync(target.path, 'utf8');
+ atomicWriteTextFile(target.path, spliceBlock(MARKERS, existing, body), { freshMode: 0o644 });
+ if (created && target.project) {
+ try { ensureGitExcluded(target.path); } catch { /* a project file outside git, or an unwritable exclude, stays as written */ }
+ }
+ }
+ record('installed', created || (prior?.created_file ?? false));
+ return out('write', `brain-first block ${before.state === 'stale' ? 'upgraded in' : created ? 'in new file' : 'appended to'} ${target.path}`);
+ } catch (e) {
+ return out('preserve', `${target.path} could not be updated (${e instanceof Error ? e.message : String(e)}); nothing else was changed`);
+ }
+}
+
+/** The uninstall path: strip the block, delete the file only when gbrain created it and nothing else is left, forget the record. */
+export function removeBrainFirst(opts: { harness: string; path: string; dryRun: boolean }): BrainFirstOutcome {
+ const prior = priorBrainFirst(opts.harness, opts.path);
+ const before = inspectBrainFirst(opts.path);
+ const decision: BrainFirstDecision = { value: 'declined', source: 'flag' };
+ const out = (action: BrainFirstOutcome['action'], detail: string): BrainFirstOutcome =>
+ ({ harness: opts.harness, path: opts.path, role: 'instruction file', decision, action, state_before: before.state, detail });
+ try {
+ if (before.state === 'damaged') return out('preserve', `the brain-first markers in ${opts.path} were hand-edited; remove the block by hand`);
+ if (before.state === 'no_file' || before.state === 'absent') {
+ if (!opts.dryRun) dropLedger(opts.harness, opts.path);
+ return out('skip', `no brain-first block in ${opts.path}`);
+ }
+ if (!opts.dryRun) {
+ const stripped = removeBlock(MARKERS, readFileSync(opts.path, 'utf8')).text;
+ const deleteFile = (prior?.created_file ?? false) && (stripped.trim() === '' || stripped === CURSOR_HEAD);
+ if (deleteFile) unlinkSync(opts.path);
+ else atomicWriteTextFile(opts.path, stripped);
+ dropLedger(opts.harness, opts.path);
+ return out('remove', `brain-first block from ${opts.path}${deleteFile ? ' (file removed: gbrain created it and nothing else was in it)' : ''}`);
+ }
+ return out('remove', `brain-first block from ${opts.path}`);
+ } catch (e) {
+ return out('preserve', `${opts.path} could not be updated (${e instanceof Error ? e.message : String(e)})`);
+ }
+}
+
+/** One human line per outcome, matching setup's step lines. */
+export function describeBrainFirstOutcome(o: BrainFirstOutcome, dryRun: boolean): string {
+ return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'instructions'.padEnd(7)} ${o.detail}`;
+}