Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

brain-first: review hardening (empty Codex override, CRLF/BOM markers, symlinks, per-connection removal, thin-client opt-out, Hermes identity, OpenClaw config, doctor repair argv)

garrytanc17d80c7ff9c
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 45af2e3986..cdd08a0a1e 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -160,10 +160,10 @@ search to what the current requester may see), then finish the task.
| Harness | File |
|---|---|
| claude-code | `~/.claude/CLAUDE.md` (`--scope project`: `./CLAUDE.local.md`) |
-| codex | `$CODEX_HOME/AGENTS.md`, or `AGENTS.override.md` when that exists |
+| codex | `$CODEX_HOME/AGENTS.md`, or a non-empty `AGENTS.override.md` (the file Codex loads) |
| opencode | `~/.config/opencode/AGENTS.md` |
| openclaw | `<workspace>/AGENTS.md` (`agents.defaults.workspace`, else `~/.openclaw/workspace`; several agents need `--workspace`) |
-| hermes | `$HERMES_HOME/SOUL.md`, after the identity text |
+| hermes | `$HERMES_HOME/SOUL.md`, after the identity text; never created, since a SOUL.md replaces Hermes's default identity |
| cursor | `./.cursor/rules/gbrain-brain-first.mdc` (an always-applied project rule) |
Text outside the markers is never touched, and a re-run upgrades the block in
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 61f2f105c2..21950933d1 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -191,7 +191,7 @@ brain nobody told them about, so finish the install with:
gbrain setup codex --instructions-only
```
-It writes one short marked block into `$CODEX_HOME/AGENTS.md` (or `AGENTS.override.md` when that exists, since Codex
+It writes one short marked block into `$CODEX_HOME/AGENTS.md` (or a non-empty `AGENTS.override.md`, since Codex
then reads only the override): search the brain before reading
sources one by one, read the best hit, fill gaps with other tools, apply your own
access rules, then finish the task. Text outside the markers is never touched, a
diff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.md
index 91c14aa62e..bdea4442e0 100644
--- a/docs/mcp/HERMES.md
+++ b/docs/mcp/HERMES.md
@@ -45,7 +45,9 @@ sources one by one, read the best hit, fill gaps with other tools, apply your ow
access rules, then finish the task. Text outside the markers is never touched, a
re-run upgrades the block in place, `--dry-run` previews it,
`--no-instructions` opts out (and is remembered) and `--remove` takes it out.
-`gbrain doctor` warns when the block is missing or out of date.
+`gbrain doctor` warns when the block is missing or out of date. Setup never
+creates `SOUL.md`: Hermes uses a non-empty one instead of its default identity,
+so start Hermes once (it seeds the file) or write your identity there first.
## Direct config (equally supported)
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index b92fcf0b57..d6bd7ebf0c 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -26,7 +26,7 @@
*/
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
-import { isAbsolute, join } from 'node:path';
+import { basename, dirname, isAbsolute, join } from 'node:path';
import { gbrainPath, loadConfig } from '../../../core/config.ts';
import { peekLock } from '../../../core/pglite-lock.ts';
import { harnessWiringEntry, httpStatusServerEntry, type ReadinessHarness } from '../../../core/readiness.ts';
@@ -40,7 +40,7 @@ import type { Check } from '../../doctor.ts';
import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';
import type { DoctorContext, DoctorEntry } from '../context.ts';
import { VERSION } from '../../../version.ts';
-import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock } from '../../../core/setup/brain-first.ts';
+import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock, type BrainFirstAccess } from '../../../core/setup/brain-first.ts';
export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;
export const HARNESS_HTTP_PROBE_TIMEOUT_MS = 3_000;
@@ -348,6 +348,8 @@ export interface InstructionBlockView {
state: 'current' | 'stale' | 'missing' | 'damaged' | 'opted_out';
/** Where the record came from: the brain-first ledger, or the harness's default file for a registration with no record. */
from: 'ledger' | 'default_path';
+ /** The access the recorded block names, so the repair rewrites that block and not a default one. */
+ access?: BrainFirstAccess;
}
/**
@@ -358,9 +360,14 @@ export interface InstructionBlockView {
export function instructionBlockViews(regs: HarnessRegistration[]): InstructionBlockView[] {
const state = (s: ReturnType<typeof inspectBrainFirst>['state']): InstructionBlockView['state'] =>
s === 'current' ? 'current' : s === 'stale' ? 'stale' : s === 'damaged' ? 'damaged' : 'missing';
- const views: InstructionBlockView[] = readBrainFirstLedger().map((e) => e.status === 'declined'
- ? { harness: e.harness, path: e.path, state: 'opted_out', from: 'ledger' }
- : { harness: e.harness, path: e.path, state: state(inspectBrainFirst(e.path, renderBrainFirstBlock(e.harness, e.access)).state), from: 'ledger' });
+ const views: InstructionBlockView[] = readBrainFirstLedger().map((e) => {
+ // Codex reads one global file: once a non-empty AGENTS.override.md appears, a block in AGENTS.md is no longer loaded.
+ const live = e.harness === 'codex' ? brainFirstTarget('codex') : undefined;
+ const path = live && !('error' in live) && dirname(live.path) === dirname(e.path) ? live.path : e.path;
+ return e.status === 'declined'
+ ? { harness: e.harness, path, state: 'opted_out', from: 'ledger' }
+ : { harness: e.harness, path, state: state(inspectBrainFirst(path, renderBrainFirstBlock(e.harness, e.access)).state), from: 'ledger', access: e.access };
+ });
for (const r of regs) {
if (views.some((v) => v.harness === r.harness) || !isBrainFirstHarness(r.harness)) continue;
const target = brainFirstTarget(r.harness);
@@ -398,11 +405,28 @@ export function withInstructionBlocks(check: Check, views: InstructionBlockView[
? { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),
why: `The brain-first markers in ${first.path} were hand-edited; gbrain will not guess which lines are its own.`,
user_message: `The gbrain instruction block in ${first.path} has damaged markers. Please delete the block (both marker lines included), then I'll write a fresh one.` }
- : { argv: ['gbrain', 'setup', first.harness, '--instructions-only'], consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(NAME),
- why: `Writes or upgrades only the marked brain-first block in ${first.path}; text outside the markers is left as it is. \`--no-instructions\` opts out instead.` };
+ : repairArgv(first);
return { name: check.name, status: 'warn', message, details, fix };
}
+/** The setup command that rewrites exactly this block: same file, same connection name and surface. A project file needs its own directory, so the user runs it there. */
+function repairArgv(v: InstructionBlockView): Action {
+ const access = v.access;
+ const argv = ['gbrain', 'setup', v.harness, '--instructions-only',
+ ...(access?.kind === 'mcp' && access.server !== 'gbrain' ? ['--name', access.server] : []),
+ ...(access?.kind === 'mcp' && access.surface ? ['--surface', access.surface] : []),
+ ...(v.harness === 'openclaw' ? ['--workspace', dirname(v.path)] : []),
+ ...(v.harness === 'claude-code' && basename(v.path) === 'CLAUDE.local.md' ? ['--scope', 'project'] : [])];
+ const why = `Writes or upgrades only the marked brain-first block in ${v.path}; text outside the markers is left as it is. \`--no-instructions\` opts out instead.`;
+ const project = v.harness === 'cursor' || basename(v.path) === 'CLAUDE.local.md';
+ if (project) {
+ const dir = v.harness === 'cursor' ? dirname(dirname(dirname(v.path))) : dirname(v.path);
+ return { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME), why,
+ user_message: `The gbrain instruction block in ${v.path} needs a refresh. From ${dir}, run: ${argv.join(' ')}` };
+ }
+ return { argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(NAME), why };
+}
+
/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block. */
export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {
const regs = readHarnessRegistrations();
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index cd228ceb20..ae1ee7fb47 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -136,10 +136,11 @@ 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)
+ codex $CODEX_HOME/AGENTS.md (a non-empty AGENTS.override.md instead)
opencode ~/.config/opencode/AGENTS.md
openclaw <workspace>/AGENTS.md
- hermes $HERMES_HOME/SOUL.md (the identity text above it is left as it is)
+ hermes $HERMES_HOME/SOUL.md, after the identity text (never created: an
+ empty SOUL.md would replace Hermes's default identity)
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.
diff --git a/src/core/bootstrap/harness-brain-first.ts b/src/core/bootstrap/harness-brain-first.ts
index 69557d8668..7a602903f9 100644
--- a/src/core/bootstrap/harness-brain-first.ts
+++ b/src/core/bootstrap/harness-brain-first.ts
@@ -4,8 +4,7 @@
* the managed block in its own instruction file; removal strips only the
* blocks this lane recorded.
*/
-import { existsSync } from 'node:fs';
-import { brainFirstTargetAt, describeBrainFirstOutcome, installerBrainFirst, readBrainFirstLedger, removeBrainFirst } from '../setup/brain-first.ts';
+import { brainFirstTargetAt, codexInstructionFile, describeBrainFirstOutcome, installerBrainFirst, readBrainFirstLedger, removeBrainFirst } from '../setup/brain-first.ts';
const WRITER = 'gbrain bootstrap harness';
@@ -22,7 +21,7 @@ export function writeHarnessBrainFirst(opts: { hosts: readonly BrainFirstHost[];
const { paths } = opts;
for (const host of opts.hosts) {
const path = host === 'claude-code' ? paths.claudeMemoryPath
- : host === 'codex' ? (existsSync(paths.codexAgentsOverride) ? paths.codexAgentsOverride : paths.codexAgentsPath)
+ : host === 'codex' ? codexInstructionFile(paths.codexAgentsOverride, paths.codexAgentsPath)
: paths.opencodeAgentsPath;
const o = installerBrainFirst({ target: brainFirstTargetAt(host, path), access: { kind: 'mcp', server: opts.server },
writer: WRITER, instructions: opts.optOut ? false : undefined });
@@ -30,8 +29,8 @@ export function writeHarnessBrainFirst(opts: { hosts: readonly BrainFirstHost[];
}
}
-export function removeHarnessBrainFirst(log: (line: string) => void): void {
+export function removeHarnessBrainFirst(server: string, log: (line: string) => void): void {
for (const e of readBrainFirstLedger().filter((entry) => entry.writer === WRITER)) {
- log(describeBrainFirstOutcome(removeBrainFirst({ harness: e.harness, path: e.path, dryRun: false }), false).trim());
+ log(describeBrainFirstOutcome(removeBrainFirst({ harness: e.harness, path: e.path, dryRun: false, server }), false).trim());
}
}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 968ac51eb5..c6b2fd9c1c 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -2261,7 +2261,7 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
d.log('current token was supplied via --token — not revoked (not ours to revoke).');
}
- removeHarnessBrainFirst(d.log);
+ removeHarnessBrainFirst(flags.name, d.log);
if (remaining.length === 0 && tokenDone && skillsDone) {
deleteHarnessReceipt(d.gbrainHome);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 1a2aff397b..056cf846ec 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--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', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--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', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--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-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index b75109ddf9..85a7a9b4a1 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -19,7 +19,7 @@ import { installSharedSkillsConnection } from './shared-skills.ts';
import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';
import { harnessSharedSkillsRoot } from './status.ts';
import { gitChildEnv } from '../git-env.ts';
-import { brainFirstTargetAt, installerBrainFirst, renderBrainFirstSnippet, type BrainFirstHarness } from '../setup/brain-first.ts';
+import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';
export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;
sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean;
@@ -98,7 +98,7 @@ function assertEntryOwned(entry: unknown, prior: Record<string, any>, connection
/** The harness's own instruction file, next to the config this install writes. */
function instructionFileBeside(connection: string, configPath: string): { harness: BrainFirstHarness; path: string } {
const dir = dirname(configPath);
- if (connection === 'codex-toml') return { harness: 'codex', path: join(dir, existsSync(join(dir, 'AGENTS.override.md')) ? 'AGENTS.override.md' : 'AGENTS.md') };
+ if (connection === 'codex-toml') return { harness: 'codex', path: codexInstructionFile(join(dir, 'AGENTS.override.md'), join(dir, 'AGENTS.md')) };
if (connection === 'opencode-json') return { harness: 'opencode', path: join(dir, 'AGENTS.md') };
return { harness: 'claude-code', path: process.env.CLAUDE_CONFIG_DIR?.trim() === dir ? join(dir, 'CLAUDE.md') : join(dir, '.claude', 'CLAUDE.md') };
}
@@ -214,11 +214,12 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, co
oauth_client_id: c.client_id, oauth_client_secret: c.client_secret } };
const sourceCli = fileURLToPath(new URL('../../cli.ts', import.meta.url));
const launcher = join(root, 'bin', 'gbrain');
+ const brainFirst = resolveBrainFirstDecision(opts.instructions, prior.brain_first_instructions === 'declined' ? { status: 'declined' } : undefined).value;
const files = [
{ path: '.gbrain/config.json', text: `${JSON.stringify(config, null, 2)}\n`, mode: 0o600 },
{ path: 'bin/gbrain', text: renderAgentLauncher({ root, bunPath: process.execPath, cliPath: sourceCli.includes('$bunfs') ? undefined : sourceCli, mode: 'thin-client',
repairHint: `Reinstall GBrain in this environment, then repeat: gbrain connect ${shellQuote(c.mcp_url)} --harness ${shellQuote(opts.harness)} --credentials-file <private-handoff-file> --root ${shellQuote(root)} --install` }), mode: 0o700 },
- { path: 'GBRAIN-INSTRUCTIONS.md', text: `${opts.instructions === false ? '' : `${renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}\n`}${GBRAIN_MCP_INSTRUCTIONS}\n\nRun commands with the absolute launcher: ${launcher}\nThis is a hosted connection. The host grant controls sources and permissions.\n`, mode: 0o600 },
+ { path: 'GBRAIN-INSTRUCTIONS.md', text: `${brainFirst === 'declined' ? '' : `${renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}\n`}${GBRAIN_MCP_INSTRUCTIONS}\n\nRun commands with the absolute launcher: ${launcher}\nThis is a hosted connection. The host grant controls sources and permissions.\n`, mode: 0o600 },
];
const owned: Record<string, string> = prior.owned_files ?? {};
const pending: Record<string, { before: string | null; after: string }> = prior.pending_files ?? {};
@@ -232,7 +233,7 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, co
privateWrite(receiptPath, `${JSON.stringify({ ...common, root, status: 'removed', owned_files: {} }, null, 2)}\n`);
return { ...common, status: 'removed', root, next_action: 'Disable the native skill and routine. Revoke the client on the host to end access; separately protect or remove retained handoff files.' };
}
- const receipt = { ...common, root, launcher, config_path: configPath, status: 'prepared', native_instructions: 'pending', owned_files: owned, pending_files: pending };
+ const receipt = { ...common, root, launcher, config_path: configPath, status: 'prepared', native_instructions: 'pending', brain_first_instructions: brainFirst, owned_files: owned, pending_files: pending };
const save = () => privateWrite(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
save();
for (const file of files) {
diff --git a/src/core/managed-block.ts b/src/core/managed-block.ts
index 92d46cb9bd..fec7b374bb 100644
--- a/src/core/managed-block.ts
+++ b/src/core/managed-block.ts
@@ -29,12 +29,17 @@ function damagedMarkersError(m: BlockMarkers, begins: number, ends: number): Err
);
}
+/** A line as an editor may have saved it: a CRLF line ending or a leading BOM does not hide a marker. */
+function bare(line: string, i: number): string {
+ return (i === 0 ? line.replace(/^\uFEFF/, '') : line).replace(/\r$/, '');
+}
+
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 (bare(line, i) === m.begin) begins.push(i);
+ if (bare(line, i) === 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);
@@ -47,7 +52,7 @@ export function probeBlock(m: BlockMarkers, text: string): { state: 'absent' | '
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') };
+ return { state: 'present', interior: lines.slice(scan.begin + 1, scan.end).map((l) => l.replace(/\r$/, '')).join('\n') };
} catch {
return { state: 'damaged' };
}
@@ -80,12 +85,13 @@ export function removeBlock(m: BlockMarkers, existing: string): { text: string;
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++;
+ if (after < lines.length - 1 && bare(lines[after], after) === '') after++;
const out = [...lines.slice(0, scan.begin), ...lines.slice(after)];
- return { text: out.join('\n'), removed: true };
+ const bom = scan.begin === 0 && lines[0].startsWith('\uFEFF') ? '\uFEFF' : '';
+ return { text: bom + 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);
+ return text.split('\n').some((l, i) => bare(l, i) === m.begin || bare(l, i) === m.end);
}
diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.ts
index b150712042..1e6c86aaa7 100644
--- a/src/core/setup/brain-first.ts
+++ b/src/core/setup/brain-first.ts
@@ -20,7 +20,7 @@
*
* The text stays short on purpose: it is loaded into every turn.
*/
-import { existsSync, readFileSync, unlinkSync } from 'node:fs';
+import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
@@ -91,6 +91,18 @@ export interface BrainFirstTarget {
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; }
+/**
+ * The global file Codex actually loads: AGENTS.override.md when it exists
+ * and is non-empty, else AGENTS.md (Codex uses the first non-empty file at
+ * this level, so writing into an empty override would hide AGENTS.md).
+ */
+export function codexInstructionFile(overridePath: string, agentsPath: string): string {
+ try {
+ if (readFileSync(overridePath, 'utf8').trim() !== '') return overridePath;
+ } catch { /* no override */ }
+ return agentsPath;
+}
+
/** OpenClaw's state directory: OPENCLAW_STATE_DIR, else ~/.openclaw (or ~/.openclaw-<profile>). */
function openclawStateDir(): string {
const explicit = process.env.OPENCLAW_STATE_DIR?.trim();
@@ -105,7 +117,9 @@ function openclawStateDir(): string {
* 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 quotedKeys = text.replace(/([{,]\s*)([A-Za-z_$][\w$-]*)\s*:/g, '$1"$2":');
+ const doubleQuoted = quotedKeys.replace(/'((?:[^'\\\n]|\\.)*)'/g, (_m, s: string) => JSON.stringify(s.replace(/\\'/g, "'")));
+ for (const candidate of [text, quotedKeys, doubleQuoted]) {
const errors: ParseError[] = [];
const value = parseJsonc(candidate, errors, { allowTrailingComma: true });
if (errors.length === 0) return value;
@@ -121,14 +135,16 @@ function parseJson5ish(text: string): unknown {
* workspace, so the caller must name one.
*/
export function resolveOpenclawWorkspace(): { path: string } | { error: string } {
- const configPath = join(openclawStateDir(), 'openclaw.json');
+ const configPath = process.env.OPENCLAW_CONFIG_PATH?.trim() ? expandHome(process.env.OPENCLAW_CONFIG_PATH.trim()) : 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 sole = roster === 1 ? (Array.isArray(cfg.agents?.list) ? cfg.agents.list[0] : Object.values(cfg.agents?.entries as object)[0]) as { workspace?: unknown } | undefined : undefined;
+ const workspace = [sole?.workspace, cfg.agents?.defaults?.workspace].find((w): w is string => typeof w === 'string' && w.trim() !== '');
+ if (workspace) configured = workspace.trim();
}
const fromEnv = process.env.OPENCLAW_WORKSPACE_DIR?.trim();
return { path: expandHome(configured ?? fromEnv ?? join(openclawStateDir(), 'workspace')) };
@@ -143,10 +159,10 @@ export function brainFirstTarget(harness: BrainFirstHarness, opts: { scope?: 'us
? { 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 };
+ const path = codexInstructionFile(codexAgentsOverridePath(), codexGlobalAgentsPath());
+ return path === codexGlobalAgentsPath()
+ ? { harness, path, role: 'Codex user instructions', project: false }
+ : { harness, path, role: 'Codex user instructions (a non-empty AGENTS.override.md, which Codex loads instead of AGENTS.md)', project: false };
}
case 'opencode':
return { harness, path: join(opencodeConfigDir(), 'AGENTS.md'), role: 'opencode global rules', project: false };
@@ -208,8 +224,10 @@ function dropLedger(harness: string, path: string): void {
if (rest.length !== all.length) writeLedger(rest);
}
+/** The record for this surface; failing that, an opt-out recorded for the same harness at another path (the target moved), so an opt-out survives the move. */
export function priorBrainFirst(harness: string, path: string): BrainFirstLedgerEntry | undefined {
- return readBrainFirstLedger().find((e) => e.harness === harness && e.path === path);
+ const all = readBrainFirstLedger();
+ return all.find((e) => e.harness === harness && e.path === path) ?? all.find((e) => e.harness === harness && e.status === 'declined');
}
// ── Decision, inspection, sync, removal ───────────────────────────────────
@@ -218,7 +236,7 @@ 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 {
+export function resolveBrainFirstDecision(flag: boolean | undefined, prior: Pick<BrainFirstLedgerEntry, 'status'> | 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' };
@@ -248,6 +266,28 @@ export interface BrainFirstOutcome {
detail: string;
}
+/** A directory entry exists, a dangling symlink included (existsSync follows links). */
+function direntExists(path: string): boolean {
+ try { lstatSync(path); return true; } catch { return false; }
+}
+
+/** gbrain created this file, it is still a plain file, and nothing but our block was in it. */
+function ownedEmptyFile(prior: BrainFirstLedgerEntry | undefined, path: string, stripped: string): boolean {
+ return (prior?.created_file ?? false) && !lstatSync(path).isSymbolicLink() && (stripped.trim() === '' || stripped === CURSOR_HEAD);
+}
+
+/**
+ * Write `next` only if the file still holds what we read: another writer (an
+ * editor, a second install) that saved in between keeps its text, and this run
+ * reports the file as changed instead. A file that appeared since we found
+ * none is never replaced.
+ */
+function writeUnlessChanged(path: string, read: string, wasMissing: boolean, next: string): void {
+ const now = direntExists(path) && existsSync(path) ? readFileSync(path, 'utf8') : null;
+ if (wasMissing ? now !== null : now !== read) throw new Error('the file changed while gbrain was updating it; re-run to apply the block to the new contents');
+ atomicWriteTextFile(path, next, { freshMode: 0o644 });
+}
+
/**
* Make the surface match the decision: write or upgrade the block when
* accepted, strip it when declined, record the decision. Never throws: a
@@ -260,7 +300,8 @@ export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFi
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 recorded = priorBrainFirst(target.harness, target.path);
+ const prior = recorded?.path === target.path ? recorded : undefined;
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() });
@@ -277,8 +318,8 @@ export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFi
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);
+ if (ownedEmptyFile(prior, target.path, stripped)) unlinkSync(target.path);
+ else writeUnlessChanged(target.path, existing, false, stripped);
}
record('declined', false);
return out('remove', `brain-first block from ${target.path}; opt-out recorded`);
@@ -287,10 +328,13 @@ export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFi
record('installed', prior?.created_file ?? false);
return out('keep', `brain-first block in ${target.path} is current`);
}
- const created = before.state === 'no_file';
+ if (target.harness === 'hermes' && (before.state === 'no_file' || readFileSync(target.path, 'utf8').trim() === '')) {
+ return out('skip', `${target.path} is missing or empty, and Hermes uses a non-empty SOUL.md instead of its default identity; start Hermes once (it seeds SOUL.md) or write your identity there, then re-run`);
+ }
+ const created = before.state === 'no_file' && !direntExists(target.path);
if (!opts.dryRun) {
- const existing = created ? (target.harness === 'cursor' ? CURSOR_HEAD : '') : readFileSync(target.path, 'utf8');
- atomicWriteTextFile(target.path, spliceBlock(MARKERS, existing, body), { freshMode: 0o644 });
+ const existing = before.state === 'no_file' ? (created && target.harness === 'cursor' ? CURSOR_HEAD : '') : readFileSync(target.path, 'utf8');
+ writeUnlessChanged(target.path, existing, before.state === 'no_file', spliceBlock(MARKERS, existing, body));
if (created && target.project) {
try { ensureGitExcluded(target.path); } catch { /* a project file outside git, or an unwritable exclude, stays as written */ }
}
@@ -303,23 +347,27 @@ export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFi
}
/** 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);
+export function removeBrainFirst(opts: { harness: string; path: string; dryRun: boolean; server?: string }): BrainFirstOutcome {
+ const prior = readBrainFirstLedger().find((e) => e.harness === opts.harness && e.path === 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 (opts.server !== undefined && prior?.status === 'installed' && prior.access.kind === 'mcp' && prior.access.server !== opts.server) {
+ return out('skip', `the brain-first block in ${opts.path} was last written for the \`${prior.access.server}\` connection, so removing \`${opts.server}\` leaves it`);
+ }
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);
+ const existing = readFileSync(opts.path, 'utf8');
+ const stripped = removeBlock(MARKERS, existing).text;
+ const deleteFile = ownedEmptyFile(prior, opts.path, stripped);
if (deleteFile) unlinkSync(opts.path);
- else atomicWriteTextFile(opts.path, stripped);
+ else writeUnlessChanged(opts.path, existing, false, 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)' : ''}`);
}
@@ -340,7 +388,9 @@ export function brainFirstTargetAt(harness: BrainFirstHarness, path: string): Br
* write or upgrade the block unless opted out, or strip it on removal.
*/
export function installerBrainFirst(opts: { target: BrainFirstTarget; access: BrainFirstAccess; writer: string; instructions?: boolean; remove?: boolean; dryRun?: boolean }): BrainFirstOutcome {
- if (opts.remove) return removeBrainFirst({ harness: opts.target.harness, path: opts.target.path, dryRun: opts.dryRun ?? false });
+ if (opts.remove) {
+ return removeBrainFirst({ harness: opts.target.harness, path: opts.target.path, dryRun: opts.dryRun ?? false, ...(opts.access.kind === 'mcp' ? { server: opts.access.server } : {}) });
+ }
const decision = resolveBrainFirstDecision(opts.instructions, priorBrainFirst(opts.target.harness, opts.target.path));
return syncBrainFirst({ target: opts.target, access: opts.access, decision, writer: opts.writer, dryRun: opts.dryRun ?? false });
}
diff --git a/test/setup-brain-first.test.ts b/test/setup-brain-first.test.ts
index 554a850dd9..71d16fc9db 100644
--- a/test/setup-brain-first.test.ts
+++ b/test/setup-brain-first.test.ts
@@ -13,7 +13,7 @@
* Spawns \`bun src/cli.ts setup\` against a temp HOME / GBRAIN_HOME.
*/
import { afterAll, describe, expect, test } from 'bun:test';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { runCli } from './helpers/cli-spawn.ts';
@@ -24,7 +24,7 @@ import {
renderBrainFirstBlock,
renderBrainFirstSnippet,
} from '../src/core/setup/brain-first.ts';
-import { harnessWiringCheck } from '../src/commands/doctor/checks/harness-wiring.ts';
+import { harnessWiringCheck, instructionBlockViews, withInstructionBlocks, type InstructionBlockView } from '../src/commands/doctor/checks/harness-wiring.ts';
import { installHarnessConnection } from '../src/core/harness/install.ts';
import type { HarnessCredentials } from '../src/core/harness/credentials.ts';
@@ -63,14 +63,15 @@ const read = (p: string) => readFileSync(p, 'utf8');
const blocks = (text: string) => text.split('\n').filter((l) => l === BRAIN_FIRST_BEGIN).length;
const ledger = (b: Box) => JSON.parse(read(join(b.home, '.gbrain', 'agent-instructions.json'))).entries as any[];
-interface Lane { harness: string; file: (b: Box) => string; args?: string[]; prepare?: (b: Box) => void; existing: string }
+/** refusesCreate: a missing file is never created (Hermes uses a non-empty SOUL.md instead of its default identity). */
+interface Lane { harness: string; file: (b: Box) => string; args?: string[]; prepare?: (b: Box) => void; existing: string; refusesCreate?: boolean }
const LANES: Lane[] = [
{ harness: 'claude-code', file: (b) => join(b.home, '.claude', 'CLAUDE.md'), args: ['--instructions-only'], existing: '# My rules\n\nAlways answer in French.\n' },
{ harness: 'codex', file: (b) => join(b.home, '.codex', 'AGENTS.md'), args: ['--instructions-only'], existing: '# Codex house rules\n- run the tests\n' },
{ harness: 'opencode', file: (b) => join(b.home, '.config', 'opencode', 'AGENTS.md'), existing: 'Prefer small diffs.\n' },
{ harness: 'openclaw', file: (b) => join(b.home, '.openclaw', 'workspace', 'AGENTS.md'), existing: '# AGENTS.md\n\n## Tools\nUse the calendar skill.\n' },
- { harness: 'hermes', file: (b) => join(b.home, '.hermes', 'SOUL.md'), existing: 'You are Hermes, a careful assistant named alice-example.\n' },
+ { harness: 'hermes', file: (b) => join(b.home, '.hermes', 'SOUL.md'), existing: 'You are Hermes, a careful assistant named alice-example.\n', refusesCreate: true },
{ harness: 'cursor', file: (b) => join(b.project, '.cursor', 'rules', 'gbrain-brain-first.mdc'), existing: '---\ndescription: team rule\nalwaysApply: true\n---\nUse tabs.\n' },
];
@@ -148,6 +149,11 @@ for (const lane of LANES) {
const created = box();
const write = await run(created);
+ if (lane.refusesCreate) {
+ expect(write.doc.instructions.action).toBe('skip');
+ expect(existsSync(lane.file(created))).toBe(false);
+ return;
+ }
expect(write.doc.instructions.detail).toContain('new file');
expect(existsSync(lane.file(created))).toBe(true);
await run(created, ['--remove']);
@@ -158,7 +164,7 @@ for (const lane of LANES) {
const b = box();
const r = await run(b, ['--dry-run']);
expect(r.exitCode).toBe(0);
- expect(r.doc.instructions).toMatchObject({ action: 'write', state_before: 'no_file' });
+ expect(r.doc.instructions).toMatchObject({ action: lane.refusesCreate ? 'skip' : 'write', state_before: 'no_file' });
expect(existsSync(lane.file(b))).toBe(false);
expect(existsSync(join(b.home, '.gbrain', 'agent-instructions.json'))).toBe(false);
});
@@ -175,6 +181,24 @@ describe('brain-first block: placement rules', () => {
expect(existsSync(join(b.home, '.codex', 'AGENTS.md'))).toBe(false);
});
+ test('codex: an empty AGENTS.override.md is skipped, as Codex skips it, so the block lands in AGENTS.md', async () => {
+ const b = box();
+ mkdirSync(join(b.home, '.codex'), { recursive: true });
+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), '\n');
+ const r = await setup(b, ['codex', '--instructions-only']);
+ expect(r.doc.instructions.path).toBe(join(b.home, '.codex', 'AGENTS.md'));
+ expect(read(join(b.home, '.codex', 'AGENTS.override.md'))).toBe('\n');
+ });
+
+ test('openclaw: OPENCLAW_CONFIG_PATH is read, a sole agent\'s own workspace wins, single-quoted JSON5 parses', async () => {
+ const b = box();
+ const cfg = join(b.root, 'custom', 'openclaw.json');
+ mkdirSync(dirname(cfg), { recursive: true });
+ writeFileSync(cfg, "{ agents: { defaults: { workspace: '~/default-ws' }, list: [{ id: 'main', workspace: '~/main-ws' }] } }\n");
+ const r = await setup(b, ['openclaw'], { OPENCLAW_CONFIG_PATH: cfg });
+ expect(r.doc.instructions.path).toBe(join(b.home, 'main-ws', 'AGENTS.md'));
+ });
+
test('claude-code --scope project writes CLAUDE.local.md and keeps it out of git', async () => {
const b = box();
const git = Bun.spawnSync(['git', 'init', '-q', b.project]);
@@ -233,6 +257,63 @@ describe('brain-first block: placement rules', () => {
});
});
+describe('brain-first block: hardening', () => {
+ test('a CRLF or BOM file keeps one block: upgraded in place, then removed by the opt-out', async () => {
+ const b = box();
+ const path = join(b.home, '.claude', 'CLAUDE.md');
+ mkdirSync(dirname(path), { recursive: true });
+ const stale = renderBrainFirstSnippet('claude-code', { kind: 'mcp', server: 'gbrain' }).replace('finish the whole task', 'stop');
+ writeFileSync(path, `\uFEFFrules\r\n${stale.replace(/\n/g, '\r\n')}tail\r\n`);
+ const up = await setup(b, ['claude-code', '--instructions-only']);
+ expect(up.doc.instructions).toMatchObject({ action: 'write', state_before: 'stale' });
+ expect(read(path).split('\n').filter((l) => l.replace(/\r$/, '') === BRAIN_FIRST_BEGIN)).toHaveLength(1);
+ expect(read(path).startsWith('\uFEFFrules\r\n')).toBe(true);
+ expect(read(path).endsWith('tail\r\n')).toBe(true);
+ const off = await setup(b, ['claude-code', '--instructions-only', '--no-instructions']);
+ expect(off.doc.instructions.action).toBe('remove');
+ expect(read(path)).toBe('\uFEFFrules\r\ntail\r\n');
+ });
+
+ test('a dangling symlink is followed and never deleted on removal', async () => {
+ const b = box();
+ const real = join(b.root, 'dotfiles', 'CLAUDE.md');
+ mkdirSync(dirname(real), { recursive: true });
+ mkdirSync(join(b.home, '.claude'), { recursive: true });
+ symlinkSync(real, join(b.home, '.claude', 'CLAUDE.md'));
+ await setup(b, ['claude-code', '--instructions-only']);
+ expect(blocks(read(real))).toBe(1);
+ expect(ledger(b)[0].created_file).toBe(false);
+ await setup(b, ['claude-code', '--instructions-only', '--remove']);
+ expect(lstatSync(join(b.home, '.claude', 'CLAUDE.md')).isSymbolicLink()).toBe(true);
+ expect(read(real)).toBe('');
+ });
+
+ test('an opt-out survives the Codex target moving to a non-empty AGENTS.override.md; doctor follows the move', async () => {
+ const b = box();
+ await setup(b, ['codex', '--instructions-only']);
+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), 'override rules\n');
+ await withEnv({ ...b.env, CODEX_HOME: join(b.home, '.codex') }, async () => {
+ expect(instructionBlockViews([])).toEqual([expect.objectContaining({ harness: 'codex', path: join(b.home, '.codex', 'AGENTS.override.md'), state: 'missing' })]);
+ });
+ await setup(b, ['codex', '--instructions-only', '--no-instructions']);
+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), 'new override\n');
+ rmSync(join(b.home, '.codex', 'AGENTS.md'), { force: true });
+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), 'newer override\n');
+ const again = await setup(b, ['codex', '--instructions-only']);
+ expect(again.doc.instructions.decision.value).toBe('declined');
+ expect(read(join(b.home, '.codex', 'AGENTS.override.md'))).toBe('newer override\n');
+ });
+
+ test('doctor\'s repair names the recorded connection and surface; a project file is the user\'s to run in place', () => {
+ const views: InstructionBlockView[] = [{ harness: 'codex', path: '/x/.codex/AGENTS.md', state: 'stale', from: 'ledger', access: { kind: 'mcp', server: 'work-brain', surface: 'verbs' } }];
+ const c = withInstructionBlocks({ name: 'harness_wiring', status: 'ok', message: 'wired.' }, views);
+ expect(c.fix?.argv).toEqual(['gbrain', 'setup', 'codex', '--instructions-only', '--name', 'work-brain', '--surface', 'verbs']);
+ const project = withInstructionBlocks({ name: 'harness_wiring', status: 'ok', message: 'wired.' }, [{ harness: 'cursor', path: '/repo/.cursor/rules/gbrain-brain-first.mdc', state: 'missing', from: 'ledger' }]);
+ expect(project.fix?.argv).toBeUndefined();
+ expect(project.fix?.user_message).toContain('From /repo, run: gbrain setup cursor --instructions-only');
+ });
+});
+
describe('brain-first block: text', () => {
test('names the tools the surface lists: search/query/get_page, recall/entity on verbs, the CLI on a thin client', () => {
const full = renderBrainFirstBlock('codex', { kind: 'mcp', server: 'gbrain', surface: 'full' });
@@ -306,6 +387,35 @@ describe('brain-first block: full setup and the installer lanes', () => {
});
}
+ test('removing one connection leaves the block another connection last wrote', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const configPath = join(b.home, '.claude.json');
+ const instructionPath = join(b.home, '.claude', 'CLAUDE.md');
+ await installHarnessConnection(credentials, { harness: 'claude-code', configPath, name: 'alpha' });
+ await installHarnessConnection({ ...credentials, client_id: 'client-beta' }, { harness: 'claude-code', configPath, name: 'beta' });
+ expect(read(instructionPath)).toContain('`beta` MCP server');
+ const removed = await installHarnessConnection(credentials, { harness: 'claude-code', configPath, name: 'alpha', remove: true });
+ expect((removed as any).instructions.action).toBe('skip');
+ expect(read(instructionPath)).toContain('`beta` MCP server');
+ });
+ });
+
+ test('thin-client opt-out: GBRAIN_AGENT_INSTRUCTIONS=0 writes no block, and --no-instructions is kept on the next install', async () => {
+ const b = box();
+ const envRoot = join(b.root, 'thin-env');
+ await withEnv({ ...b.env, GBRAIN_AGENT_INSTRUCTIONS: '0' }, async () => {
+ await installHarnessConnection(credentials, { harness: 'openclaw', root: envRoot });
+ });
+ expect(read(join(envRoot, 'GBRAIN-INSTRUCTIONS.md'))).not.toContain(BRAIN_FIRST_BEGIN);
+ const root = join(b.root, 'thin-flag');
+ await withEnv(b.env, async () => {
+ await installHarnessConnection(credentials, { harness: 'openclaw', root, instructions: false });
+ await installHarnessConnection(credentials, { harness: 'openclaw', root });
+ });
+ expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).not.toContain(BRAIN_FIRST_BEGIN);
+ });
+
test('thin-client install (OpenClaw) puts the CLI-flavored block first in GBRAIN-INSTRUCTIONS.md', async () => {
const b = box();
const root = join(b.root, 'thin');
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 856fb2b8f8..1fd3c0875c 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -434,6 +434,11 @@ describe('gbrain setup: consent and refusals', () => {
for (const [harness, guide] of [['openclaw', 'docs/mcp/OPENCLAW.md'], ['hermes', 'docs/mcp/HERMES.md']] as const) {
test(`${harness}: setup writes only the brain-first block and names its guide for the MCP step`, async () => {
const b = box();
+ if (harness === 'hermes') {
+ // Hermes seeds SOUL.md on first run; setup never creates one (it would replace the default identity).
+ mkdirSync(join(b.home, '.hermes'), { recursive: true });
+ writeFileSync(join(b.home, '.hermes', 'SOUL.md'), 'You are Hermes.\n');
+ }
const r = await setup(b, [harness, '--json'], { OPENCLAW_STATE_DIR: undefined, OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, HERMES_HOME: undefined });
expect(r.exitCode).toBe(0);
expect(r.doc).toMatchObject({ harness, instructions_only: true, mcp: { setup: 'manual', docs: guide }, instructions: { action: 'write' } });