Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Setup can make a personal brain: starter pages, your notes and agent instructions (GST-2731) (#9387)
Garry Tan7af133a01629
diff --git a/changelog.d/setup-personal-brain.md b/changelog.d/setup-personal-brain.mdnew file mode 100644index 0000000000..24f091f800--- /dev/null+++ b/changelog.d/setup-personal-brain.md@@ -0,0 +1,9 @@+**`gbrain setup claude-code --shape personal` (or `codex`) gives a new brain a starting shape: three empty starter pages about you, your notes folder imported read only, and a short block that tells the agent to read those pages.** The pages are `me/facts`, `me/voice` and `me/how-i-decide`. Each is an empty form marked `status: stub`, so nothing about you is invented, and a re-run never overwrites a page you have edited. `--notes DIR` imports that folder's markdown without writing into it; above 500 files setup prints the import command instead of running it. Setup then checks that keyless search finds one of your notes and prints a question to try in a new session. A brand-new brain set up by an agent without `--shape` gets a `brain_shape` question in its first-run decisions, and nothing is written until it is answered. `--shape none` removes the block and keeps the pages. Every command setup hands back keeps the run's `--scope project` and `--source`, and the import and page writes go to the pinned source. The draft-in-voice skill now treats a stub page as missing.++### Itemized changes++- `src/commands/setup-brain-layout.ts` (new): the starter pages, the managed `gbrain:brain-layout` block, the read-only notes import and search check, and the `brain_shape` decision. A page is written only when `gbrain get` reports `page_not_found`; any other read error is reported as pending instead of overwriting. The notes count skips symlinked folders.+- `src/commands/setup.ts`: new `--shape personal|none` and `--notes DIR` flags for `claude-code` and `codex`; `--shape company` is refused for now. `--no-instructions` also takes out a layout block an earlier run wrote.+- `skills/draft-in-voice/SKILL.md` (and the plugin copy): a `status: stub` page counts as missing.+- Docs: new `docs/guides/brain-layout.md`.+- Tests: new `test/setup-brain-layout.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 7b11f1ce75..bd475a7956 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -29,6 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners; on the brain it just created it runs the setup migrations init left pending (`finishFreshSetupMigrations`, `src/commands/setup-migrations.ts`: one `apply-migrations --yes --no-autopilot-install --json` child built by `setupMigrationsArgv` in `migrations/fresh-install.ts`, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing `~/.claude/AGENTS.md`, `~/.openclaw/AGENTS.md` or OpenClaw cron manifest (`hostRewriteTargets`)) and replaces init's `[init] Migrations:` line with `[setup] Migrations: …` (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a `Memory:` line naming `remember` (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt that wired the configuration setup would write (a target in that config directory, compared after symlink resolution; project-scoped hooks; or a receipt recording no paths for the host) or another gbrain marker on a wanted event; #7771, `test/setup-harness-lane-scope-7771.test.ts`). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex (in the same scoped sense) or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. `--serves one|several` (GST-363, `src/commands/setup-serves.ts`; tests `test/setup-serves-several.test.ts`, `test/setup-serves-stdio-member.test.ts`, `test/setup-serves-upgrade.test.ts`): `several` runs `gbrain access serves several --yes --json` and one `gbrain find people/ --as <member> --json` per member as children and prints the receipt (paths, never keys); a one-person setup on a several-person brain refuses `setup_serves_several` unless the owner (written as `mcp.stdio_member`) or `mcp.stdio_member` binds the connection; the brain-first access then carries `serves: 'several'`. Pinned by `test/setup.test.ts` and `test/setup-serves-several.test.ts`.+- `src/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal [--notes DIR]` (GST-2731; guide `docs/guides/brain-layout.md`). Writes `me/facts`, `me/voice` and `me/how-i-decide` create-only through `gbrain get` then `gbrain put` children (empty forms, `status: stub`, one "Example (delete me)" line each; `put` already refuses an existing page without `--expected-revision`), imports `--notes` read only with one `gbrain import DIR --no-embed --json` child (over `IMPORT_INLINE_MAX` = 500 markdown files it returns the `brain_layout_import_pending` notice instead), checks keyless search finds the first note's title in the top 5, and splices a `<!-- gbrain:brain-layout:begin/end -->` block into the brain-first target only when the brain-first decision is accepted. `--shape none` removes the block and keeps the pages; `--shape company|both` refuses before any write. A brand-new brain set up without `--shape` asks inline only when `isInteractive()`, otherwise `brain_shape` joins the `first_run_decisions` bundle (default none, nothing written). The flag is `--shape` because `--brain` is the global brain-id flag (`cli-options.ts`). Pinned by `test/setup-brain-layout.test.ts`.- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer (`underInstructionLedgerLock` holds one lock, `<configDir>/agent-instructions.lock`, shared with `skill-loading.json`, across the ledger read, the file and permission edits and the ledger write, re-reads a recorded decision under it, reports a lock it cannot take within 10 seconds as `preserve`, and a dry run takes none; `test/instruction-ledger-lock.test.ts`, `test/instruction-ledger-lock-timeout.slow.test.ts`), so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`); `gbrain post-upgrade` prints the same command (`brain-first-upgrade-notice.ts`, `instructionBlockUpgradeHints`). The Claude Code and Codex plugin manifests declare setup's UserPromptSubmit hook with `GBRAIN_HOOK_LANE=plugin`; it yields when another gbrain lane wires the event (`bootstrap/plugin-lanes.ts` `pluginHookYields`; `test/plugin-turn-hook.test.ts`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).- `src/core/setup/turn-hook.ts` + `src/core/setup/turn-hook-check.ts` — the per-turn rule hook for installs whose MCP came from a plain `mcp add` or another installer: a `turn-rule-v1` Claude Code UserPromptSubmit entry or a Codex `hooks.json` group plus its `config.toml` trust entry, running `GBRAIN_HOOK_LANE=turn-rule <hook launcher> gbrain hook user-prompt` (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by `setup <claude-code|codex> --instructions-only`, `connect --install`, the hosted `harness connect --install` and `bootstrap harness` (not in registrar mode); with no absolute binary the outcome is `print` with the one-line next step. `inspectTurnHook` (files only; it also reads Claude Code's managed `managed-settings.json` and `managed-settings.d/*.json`, and `turnRuleHookYields` counts a managed gbrain hook, #8057) feeds doctor `harness_wiring` (`turnHookViews`, `withTurnHooks`: untrusted, or missing beside a ledger block, warns with code `turn_hook_not_loaded`); `verifyTurnHook` runs the hook (Claude Code, Codex), `openclaw plugins inspect gbrain-turn-rule --runtime --json` or `hermes hooks doctor`, and every install path exits non-zero with `turn_hook_not_loaded` when it fails (`docs/guides/repair.md#turn-hook-not-loaded`). OpenClaw and Hermes rules name the gbrain tools and the `tool_search` route (`renderBrainFirstTurnRule(access, harness)`; `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`).- `src/core/setup/hook-launcher.ts` + `src/core/setup/hook-launcher-refresh.ts` — the trusted-directory hook launcher (#8424): `<config dir>/hook-launcher/gbrain-hook`, a POSIX sh script that records the session directory in `GBRAIN_HOOK_CWD`, changes into its own directory and execs gbrain there, so a script-mode install never lets the session directory's `bunfig.toml` preload or `.env` load; it refuses (exit 1, one stderr line) when its directory holds anything else. Every setup-lane and turn-rule hook command names it (`buildClaudeHookCommand(…, launcher)`, `codexSetupHookGroup(…, launcher)`, `buildCodexSessionEndCommand(bin, launcher)`); `ensureHookLauncher` writes it before any hook that names it, and `gbrain hook` reads the session directory through `hookSessionCwd()`. `hookLauncherProblem` (turn-hook-check.ts) feeds doctor `harness_wiring` (`withHookLaunchers`, code `hook_session_cwd`, reasons `session_cwd|missing|stale|foreign`); `refreshHookLaunchers` runs in `gbrain post-upgrade` and moves the turn-rule entries and each installed user-scope setup receipt's hooks onto the launcher through their own writers. The stdio MCP entries (`desiredMcpEntry`, `desiredCodexMcpEntry`, `registerClaudeMcp`/`registerCodexMcp` with `hookLauncher`) and the bootstrap, harness and Codex SessionEnd lanes use it too (#8426, #8428); `gbrain serve` captures `GBRAIN_HOOK_CWD` through `src/core/session-cwd.ts` and never changes directory. `src/core/setup/launcher-lanes.ts` (`launcherLaneFindings`) finds those entries for doctor and post-upgrade; post-upgrade rewrites only a Claude Code setup MCP entry setup still owns, under the setup lock, and names every Codex and bootstrap entry. Tests: `test/launcher-lanes-bunfig.serial.test.ts`. Tests: `test/hook-launcher-bunfig.test.ts` (a hostile checkout's preload never runs from any shape), `test/setup.test.ts` (#8424 block).diff --git a/docs/guides/brain-layout.md b/docs/guides/brain-layout.mdnew file mode 100644index 0000000000..0b3f2726b2--- /dev/null+++ b/docs/guides/brain-layout.md@@ -0,0 +1,52 @@+# A personal brain in one command++`gbrain setup` gives an agent memory. `--shape personal` also gives that memory a+starting shape: a few pages about you that the agent reads, and your existing notes,+searchable from the first session.++```bash+gbrain setup claude-code --shape personal --notes ~/notes+# or+gbrain setup codex --shape personal --notes ~/notes+```++## What it writes++- **Three starter pages**, only when they don't exist yet: `me/facts`, `me/voice` and+ `me/how-i-decide`. Each is an empty form with one line marked "Example (delete me)"+ and `status: stub` in its frontmatter. Nothing about you is invented. Fill them in+ yourself, or tell the agent a fact and it saves it with `gbrain remember`. A re-run+ never overwrites a page.+- **Your notes, read only.** `--notes DIR` imports the markdown in that folder+ (`gbrain import DIR --no-embed`). Setup never writes into the folder. Above 500+ markdown files it prints the import command for the agent to run as its own step,+ so setup stays quick.+- **A short block in the agent's instruction file**, next to the brain-first block+ (`~/.claude/CLAUDE.md` for Claude Code, `$CODEX_HOME/AGENTS.md` for Codex). It tells+ the agent to read those pages, to state facts about you only from `me/facts`, and that+ a `status: stub` page holds no facts yet. `--no-instructions` skips it, and takes it+ out again if an earlier run wrote it.++Then setup checks that keyless search finds one of your notes by its title and prints a+question to try in a new session.++## Without the flag++A brand-new brain set up without `--shape` asks once when a person is at the terminal.+When an agent runs setup (`--json`, or no terminal), the question comes back as the+`brain_shape` decision in the `first_run_decisions` notice, with the exact command for+each answer. Nothing is written until it is answered, `--yes` included.++## Undo++`gbrain setup <harness> --shape none` removes the block. The pages stay; delete them+with `gbrain delete me/facts` (and the others) if you want them gone.++## Paste this to your agent++> Install gbrain and make it my personal brain: run+> `gbrain setup claude-code --shape personal`, and if I have a notes folder, add+> `--notes <that folder>`. Then tell me what it wrote and the question to try.++A company brain (`--shape company`) arrives in a later release. To see one answer+questions today: `gbrain sources demo company-brain`.diff --git a/plugin/skills/draft-in-voice/SKILL.md b/plugin/skills/draft-in-voice/SKILL.mdindex 8199f64368..027ec30405 100644--- a/plugin/skills/draft-in-voice/SKILL.md+++ b/plugin/skills/draft-in-voice/SKILL.md@@ -62,7 +62,8 @@ is worse than asking.1. **The validated voice profile** — `gbrain get people/<slug>-voice`. Thefingerprint, quantitative stats (median length, diction, rhythm), and the"how to write as this person" directive block. **This is binding.** If the- page is missing, or its `status` is anything other than `validated`, STOP+ page is missing, or its `status` is anything other than `validated` (a+ `status: stub` page, such as the empty me/voice form setup writes, is missing), STOPdrafting and go to the builder appendix.2. **First-party context** — the subject's main page (`gbrain getpeople/<slug>`) plus timeline and backlinks (`gbrain timeline <slug>`,diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 37fa18866f..56ad6ca96c 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -386,6 +386,7 @@ test/serve-http-github-webhook.test.ts handler wiring (source pin) 1 source-surftest/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 source-surface-helpertest/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 source-surface-helpertest/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync+test/setup-brain-layout.test.ts setup --shape personal 7 readFileSynctest/setup-pi-skill-extension.test.ts (file-level) 7 readFileSynctest/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSynctest/shared-skills-catalog.test.ts (file-level) 22 readFileSyncdiff --git a/skills/draft-in-voice/SKILL.md b/skills/draft-in-voice/SKILL.mdindex 7596b34836..b10cd28e3f 100644--- a/skills/draft-in-voice/SKILL.md+++ b/skills/draft-in-voice/SKILL.md@@ -61,7 +61,8 @@ is worse than asking.1. **The validated voice profile** — `gbrain get people/<slug>-voice`. Thefingerprint, quantitative stats (median length, diction, rhythm), and the"how to write as this person" directive block. **This is binding.** If the- page is missing, or its `status` is anything other than `validated`, STOP+ page is missing, or its `status` is anything other than `validated` (a+ `status: stub` page, such as the empty me/voice form setup writes, is missing), STOPdrafting and go to the builder appendix.2. **First-party context** — the subject's main page (`gbrain getpeople/<slug>`) plus timeline and backlinks (`gbrain timeline <slug>`,diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.jsonindex cae18a5b26..ee212c744b 100644--- a/skills/skills.lock.history.json+++ b/skills/skills.lock.history.json@@ -461,7 +461,8 @@"draft-in-voice/SKILL.md": ["0634fce165700cc8f9a4433e02229ef9b98f52d1ac88848cc7529f9bc43496a7","237ce9c0701d8d2161b118ea41050958e5623a7e507bdbb674ffdd7db96d0061",- "8bf8a3c622d454f760d675eb883ff823e300b7f5dcd5b2329d523413e0a516d9"+ "8bf8a3c622d454f760d675eb883ff823e300b7f5dcd5b2329d523413e0a516d9",+ "c95168cb603bef213477193ce6f91fcf36a8344f49eb65b14d1a45df8cd721fa"],"draft-in-voice/routing-eval.jsonl": ["590fc16277ed7c3338776e7fac6daf1270b91058941f8101079bb295d2d8f787"diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 4f65a10c0c..f014379dd0 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -77,7 +77,7 @@"data-research/SKILL.md": "39f9648a21a7074d6ad7db789e93e6d7085449a6cdaffacf8b1660eb68636b9d","db-repair/SKILL.md": "87a34fe18812f3b6ec37381ae69c205e30747300098ebe3fe41f8460d0ba8346","db-repair/routing-eval.jsonl": "45791b0bf2cb9f98b8e58d82e95288ff17ad44cab484ab570cfc2ccb14583935",- "draft-in-voice/SKILL.md": "8bf8a3c622d454f760d675eb883ff823e300b7f5dcd5b2329d523413e0a516d9",+ "draft-in-voice/SKILL.md": "c95168cb603bef213477193ce6f91fcf36a8344f49eb65b14d1a45df8cd721fa","draft-in-voice/routing-eval.jsonl": "590fc16277ed7c3338776e7fac6daf1270b91058941f8101079bb295d2d8f787","eiirp/SKILL.md": "507249ce40746c0f3d5ae2a374164797798c6ebbc6209b312e3404a2f4902e6c","eiirp/routing-eval.jsonl": "d0000eec8154ba48488eed07e8f1a6a0ccb66d0b39e41f29d279a875c1673227",@@ -226,7 +226,7 @@"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e","skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb","skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",- "skills.lock.history.json": "781fc8f8e22bfcf36a173788953f108df91f04aac186700df58cf2b82acdc3a0",+ "skills.lock.history.json": "32d383ea0cd961b0d1cc8e8f7308e5abf23a7971833334e6cffde799d87a7e90","smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5","soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8","storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",diff --git a/src/commands/setup-brain-layout.ts b/src/commands/setup-brain-layout.tsnew file mode 100644index 0000000000..e61a0a5613--- /dev/null+++ b/src/commands/setup-brain-layout.ts@@ -0,0 +1,347 @@+/**+ * GBRA-529 (GST-2731), PR 1: `gbrain setup <harness> --shape personal [--notes <dir>]`.+ *+ * The personal branch of the branching install. After setup has wired the+ * harness, it gives the brain a shape:+ *+ * - three starter pages, written create-only through `gbrain put` (the one+ * writer door: on a brain with a working tree the file is written and+ * queued for commit before the database sees it; on a repo-less brain the+ * database is the record). Each is an empty form marked `status: stub`;+ * nothing about the person is invented;+ * - a one-shot import of a notes folder the person picked (`gbrain import+ * <dir> --no-embed`), read only, never written. Over IMPORT_INLINE_MAX+ * markdown files setup hands the agent the import command instead;+ * - a managed layout block beside the brain-first block, telling the agent+ * to read those pages and to quote facts about the person only from+ * me/facts. `--shape none` removes the block and keeps the pages;+ * - a keyless check that search finds an imported note, and one question+ * to ask in a new session.+ *+ * Setup stays engine-free: every brain read and write is a child of the+ * absolute launcher. Nothing here reads stdin unless isInteractive() is true+ * (two TTYs, no agent marker, not CI); an agent-driven run gets the+ * `brain_shape` decision in the first-run bundle instead, and no starter+ * page is written until it is answered.+ */+import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { basename, join, resolve } from 'node:path';+import type { Decision, Notice } from '../core/agent-output.ts';+import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../core/managed-block.ts';+import { writeUnlessChanged } from '../core/setup/brain-first.ts';+import { bunSpawnSync } from '../core/spawn.ts';+import { readLine } from '../core/interaction.ts';++export type BrainShape = 'personal' | 'none';++export interface LayoutFlags {+ brain?: BrainShape;+ /** An absolute notes folder; null for an explicit `--notes none`. */+ notes?: string | null;+ dryRun: boolean;+}++export const IMPORT_INLINE_MAX = 500;+export const LAYOUT_VERSION = 1;+export const LAYOUT_BEGIN = '<!-- gbrain:brain-layout:begin -->';+export const LAYOUT_END = '<!-- gbrain:brain-layout:end -->';++export type LayoutScope = 'user' | 'project';++/** The setup command that targets this run's harness, wiring scope and pinned source; every rerun, remove and option argv starts with it. */+export const setupArgv = (harness: string, scope: LayoutScope = 'user', source: string | null = null): string[] =>+ ['gbrain', 'setup', harness, ...(scope === 'project' ? ['--scope', 'project'] : []), ...(source ? ['--source', source] : [])];++const markers = (harness: string, scope: LayoutScope, source: string | null): BlockMarkers => ({ begin: LAYOUT_BEGIN, end: LAYOUT_END, label: 'brain-layout', rerun: [...setupArgv(harness, scope, source), '--shape', 'personal'].join(' ') });++export interface StarterPage { slug: string; title: string; body: string }++/** The personal starter pages: empty forms with one marked example line each. */+export const PERSONAL_PAGES: readonly StarterPage[] = [+ {+ slug: 'me/facts',+ title: 'Facts about me',+ body: 'True things about me that agents may say. One dated line per fact, with where it came from. '+ + 'Never overwrite a line: when something changes, add a new dated line.\n\n'+ + '- Example (delete me): 2026-01-01: I live in example-city. Source: I said so.',+ },+ {+ slug: 'me/voice',+ title: 'My voice',+ body: 'How I write, so drafts sound like me.\n\n'+ + '## Words I never use\n\n- Example (delete me): "synergy"\n\n'+ + '## Writing I like (links)\n\n- Example (delete me): https://example.com/a-post-i-like\n\n'+ + '## Writing I dislike (links)\n\n- Example (delete me): https://example.com/a-post-i-dislike',+ },+ {+ slug: 'me/how-i-decide',+ title: 'How I decide',+ body: 'The rules of thumb I use, so agents can apply them. One line each, dated.\n\n'+ + '- Example (delete me): 2026-01-01: I say no to a meeting without an agenda.',+ },+];++export function renderStarterPage(p: StarterPage): string {+ return `---\ntitle: ${p.title}\nstatus: stub\n---\n# ${p.title}\n\n${p.body}\n\n`+ + '_This page is an empty form (status: stub). It holds no facts until you add your own lines; then remove the stub line from the frontmatter._\n';+}++export function renderLayoutBlock(harness: string, scope: LayoutScope = 'user', source: string | null = null): string {+ return [+ `<!-- gbrain brain-layout v${LAYOUT_VERSION}: managed by gbrain setup and replaced on upgrade; edit outside these markers. Remove: ${[...setupArgv(harness, scope, source), '--shape', 'none'].join(' ')} -->`,+ '## My brain layout (gbrain)',+ '- Before a task that needs my context, read the gbrain pages me/facts, me/voice and me/how-i-decide.',+ '- State facts about me only from me/facts, and say they came from there.',+ '- Never overwrite a page: add a new dated line. Save facts I tell you with remember, naming where they came from.',+ '- A page whose frontmatter says status: stub is an empty form: it holds no facts yet.',+ ].join('\n');+}++/** Markdown files under `dir` (dot folders skipped), counted up to `cap` + 1, with the first one found. */+export function countNotes(dir: string, cap = IMPORT_INLINE_MAX): { count: number; first: string | null } {+ let count = 0;+ let first: string | null = null;+ const walk = (d: string): void => {+ let names: string[];+ try { names = readdirSync(d).sort(); } catch { return; }+ for (const name of names) {+ if (count > cap) return;+ if (name.startsWith('.')) continue;+ const p = join(d, name);+ let st;+ try { st = lstatSync(p); } catch { continue; }+ if (st.isSymbolicLink()) continue;+ if (st.isDirectory()) walk(p);+ else if (/\.(md|markdown)$/i.test(name)) { count++; first ??= p; }+ }+ };+ walk(dir);+ return { count, first };+}++/** The title search should find for a note: its first heading, else its file name. */+export function noteTitle(path: string): string {+ try {+ const text = readFileSync(path, 'utf8');+ const fm = /^---\n[\s\S]*?\ntitle:\s*["']?([^"'\n]+)["']?\s*\n[\s\S]*?---/.exec(text)?.[1]?.trim();+ if (fm) return fm;+ const h = /^#\s+(.+)$/m.exec(text)?.[1]?.trim();+ if (h) return h;+ } catch { /* fall through */ }+ return basename(path).replace(/\.(md|markdown)$/i, '');+}++/** Notes folders a person commonly has, for the agent to offer; never imported unless picked. */+export function candidateNoteFolders(home: string = homedir()): string[] {+ const fixed = ['notes', 'Notes', 'Documents/notes', 'Documents/Notes', 'Obsidian', 'Documents/Obsidian'].map(p => join(home, p));+ const vaults: string[] = [];+ for (const base of [home, join(home, 'Documents'), join(home, 'Library/Mobile Documents/iCloud~md~obsidian/Documents')]) {+ let names: string[] = [];+ try { names = readdirSync(base); } catch { continue; }+ for (const n of names) if (!n.startsWith('.') && existsSync(join(base, n, '.obsidian'))) vaults.push(join(base, n));+ }+ return [...new Set([...vaults, ...fixed])].filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } });+}++/** --shape / --notes validation; a string is the refusal (nothing written). */+export function parseLayoutFlags(value: (flag: string) => string | undefined, has: (flag: string) => boolean, harness: string | undefined): { brain?: BrainShape; notes?: string | null } | string {+ const brain = value('--shape');+ if (brain === 'company' || brain === 'both') {+ return `--shape ${brain} arrives in a later gbrain release; nothing was written. Today: gbrain setup ${harness ?? '<harness>'} --shape personal, and gbrain sources demo company-brain to see a company brain answer questions`;+ }+ if (brain !== undefined && brain !== 'personal' && brain !== 'none') return `unknown --shape '${brain}'; pass personal or none`;+ const raw = value('--notes');+ if (raw === undefined) return { ...(brain ? { brain } : {}) };+ if (brain !== 'personal') return '--notes names the notes folder of --shape personal';+ if (raw === 'none') return { brain, notes: null };+ const abs = raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw;+ if (!abs.startsWith('/')) return '--notes needs an absolute path (or ~/...)';+ try { if (!statSync(abs).isDirectory()) return `--notes ${raw} is not a folder`; } catch { return `--notes ${raw} does not exist`; }+ if (has('--remove')) return '--notes and --remove do not go together';+ return { brain, notes: resolve(abs) };+}++export interface LayoutOutcome {+ shape: BrainShape;+ pages: Array<{ slug: string; action: 'write' | 'keep' | 'failed'; detail?: string }>;+ notes: { dir: string; files: number; action: 'imported' | 'deferred' | 'failed'; argv: string[]; detail?: string } | null;+ block: { path: string; action: 'write' | 'keep' | 'remove' | 'skip' | 'preserve'; detail: string } | null;+ check: { ok: boolean; query: string | null; detail: string };+ next_question: string | null;+}++type Run = (argv: string[], stdin?: string) => { code: number; stdout: string; stderr: string };+const childEnv = (source: string | null): NodeJS.ProcessEnv => (source ? { ...process.env, GBRAIN_SOURCE: source } : process.env);+const runIn = (source: string | null): Run => (argv, stdin) => {+ const child = bunSpawnSync(argv, { stdin: stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin), stdout: 'pipe', stderr: 'pipe', env: childEnv(source) });+ return { code: child.exitCode ?? 1, stdout: child.stdout?.toString() ?? '', stderr: child.stderr?.toString() ?? '' };+};++function syncLayoutBlock(path: string | null, harness: string, scope: LayoutScope, source: string | null, shape: BrainShape, dryRun: boolean): LayoutOutcome['block'] {+ if (!path) return null;+ const m = markers(harness, scope, source);+ const exists = existsSync(path);+ const text = exists ? readFileSync(path, 'utf8') : '';+ const probe = probeBlock(m, text);+ if (probe.state === 'damaged') return { path, action: 'preserve', detail: `the brain-layout markers in ${path} were hand-edited; fix or delete them, then re-run` };+ if (shape === 'none') {+ if (probe.state === 'absent') return { path, action: 'skip', detail: `no brain-layout block in ${path}` };+ if (!dryRun) writeUnlessChanged(path, text, false, removeBlock(m, text).text);+ return { path, action: 'remove', detail: `brain-layout block removed from ${path}; the pages stay` };+ }+ const body = renderLayoutBlock(harness, scope, source);+ if (probe.state === 'present' && probe.interior?.trim() === body.trim()) return { path, action: 'keep', detail: `brain-layout block in ${path} is current` };+ if (!dryRun) writeUnlessChanged(path, text, !exists, spliceBlock(m, text, body));+ return { path, action: 'write', detail: `brain-layout block ${probe.state === 'present' ? 'upgraded in' : 'appended to'} ${path}` };+}++/**+ * The personal layout for this run. `instructionsPath` is the file the brain-first block lives in (null when the+ * harness has none); the layout block goes there too, and comes out of it when the person declined instructions.+ */+export function applyBrainLayout(opts: { harness: string; scope?: LayoutScope; source?: string | null; launcher: string; flags: LayoutFlags; instructionsPath: string | null; instructionsDeclined?: boolean; run?: Run }): LayoutOutcome | null {+ const { flags, launcher, harness } = opts;+ const source = opts.source ?? null;+ const scope = opts.scope ?? 'user';+ const removed = opts.instructionsDeclined ? syncLayoutBlock(opts.instructionsPath, harness, scope, source, 'none', flags.dryRun) : null;+ const block = opts.instructionsDeclined ? (removed?.action === 'skip' ? null : removed) : flags.brain ? syncLayoutBlock(opts.instructionsPath, harness, scope, source, flags.brain, flags.dryRun) : null;+ if (!flags.brain) return block && opts.instructionsDeclined ? { shape: 'none', pages: [], notes: null, block, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null } : null;+ const exec = opts.run ?? runIn(source);+ const outcome: LayoutOutcome = { shape: flags.brain, pages: [], notes: null, block, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null };+ if (flags.brain === 'none') return outcome;++ for (const page of PERSONAL_PAGES) {+ if (flags.dryRun) { outcome.pages.push({ slug: page.slug, action: 'write', detail: 'would write if missing' }); continue; }+ const got = exec([launcher, 'get', page.slug, '--json']);+ if (got.code === 0) { outcome.pages.push({ slug: page.slug, action: 'keep' }); continue; }+ if (errorCode(got.stdout) !== 'page_not_found') { outcome.pages.push({ slug: page.slug, action: 'failed', detail: lastLine(got.stderr || got.stdout) }); continue; }+ const put = exec([launcher, 'put', page.slug, '--json'], renderStarterPage(page));+ outcome.pages.push(put.code === 0 ? { slug: page.slug, action: 'write' }+ : { slug: page.slug, action: 'failed', detail: lastLine(put.stderr) });+ }++ if (flags.notes) {+ const { count, first } = countNotes(flags.notes);+ const argv = ['gbrain', 'import', flags.notes, '--no-embed', ...(source ? ['--source', source] : [])];+ if (count > IMPORT_INLINE_MAX) {+ outcome.notes = { dir: flags.notes, files: count, action: 'deferred', argv, detail: `more than ${IMPORT_INLINE_MAX} markdown files; run the import as its own step` };+ } else if (flags.dryRun) {+ outcome.notes = { dir: flags.notes, files: count, action: 'imported', argv, detail: 'would import (read only)' };+ } else {+ const imp = exec([launcher, 'import', flags.notes, '--no-embed', '--json']);+ outcome.notes = imp.code === 0 ? { dir: flags.notes, files: count, action: 'imported', argv }+ : { dir: flags.notes, files: count, action: 'failed', argv, detail: lastLine(imp.stderr) };+ }+ if (outcome.notes.action === 'imported' && first && !flags.dryRun) {+ const title = noteTitle(first);+ const hits = exec([launcher, 'search', title, '--json']);+ let found = false;+ try { found = (JSON.parse(hits.stdout) as Array<{ title?: string }>).slice(0, 5).some(h => (h.title ?? '').trim().toLowerCase() === title.toLowerCase()); } catch { /* unreadable: not found */ }+ outcome.check = found+ ? { ok: true, query: title, detail: `keyless search found "${title}" from your notes` }+ : { ok: false, query: title, detail: `keyless search did not find "${title}" in its top 5; run gbrain search "${title}" to see what it returns` };+ if (found) outcome.next_question = `In a new session, ask: "what do my notes say about ${title}?"`;+ }+ }+ if (!outcome.next_question && !flags.dryRun) {+ const facts = exec([launcher, 'get', 'me/facts', '--json']);+ outcome.check = facts.code === 0 ? { ...outcome.check, ok: outcome.check.ok, detail: outcome.check.query ? outcome.check.detail : 'me/facts is readable' }+ : { ok: false, query: null, detail: 'me/facts could not be read back' };+ outcome.next_question = 'Add one dated line to me/facts, then in a new session ask: "what does my brain say about me?"';+ }+ return outcome;+}++/** The `code` of a gbrain --json error document, or null when stdout is not one. */+function errorCode(stdout: string): string | null {+ try { const doc = JSON.parse(stdout) as { code?: unknown }; return typeof doc.code === 'string' ? doc.code : null; } catch { return null; }+}++function lastLine(text: string): string {+ return text.trim().split('\n').filter(Boolean).at(-1)?.slice(0, 300) ?? 'no output';+}++/** Lines for the human report. */+export function describeLayout(o: LayoutOutcome, dryRun: boolean): string[] {+ const would = dryRun ? 'would ' : '';+ const lines = [`Brain layout: ${o.shape}`];+ if (o.block) lines.push(` instructions ${o.block.detail}`);+ for (const p of o.pages) lines.push(` page ${p.action.padEnd(7)} ${p.slug}${p.detail ? ` (${p.detail})` : ''}`);+ if (o.notes) lines.push(` notes ${o.notes.action === 'imported' ? `${would}import ${o.notes.files} file(s) from ${o.notes.dir} (read only)` : `${o.notes.action}: ${o.notes.detail ?? ''} (${o.notes.argv.join(' ')})`}`);+ if (!dryRun && o.shape === 'personal') lines.push(` check ${o.check.ok ? 'ok' : 'not verified'}: ${o.check.detail}`);+ if (o.next_question) lines.push(`Next question: ${o.next_question}`);+ return lines;+}++/** Notices for what the agent still has to do: a deferred or failed import, a failed page. */+export function layoutNotices(o: LayoutOutcome | null, harness: string, scope: LayoutScope = 'user', source: string | null = null): Notice[] {+ if (!o) return [];+ const out: Notice[] = [];+ if (o.notes && o.notes.action !== 'imported') {+ out.push({+ code: 'brain_layout_import_pending', kind: 'coaching',+ why: o.notes.action === 'deferred' ? `${o.notes.dir} holds more than ${IMPORT_INLINE_MAX} markdown files, so setup did not import it inline.`+ : `The import of ${o.notes.dir} did not finish (${o.notes.detail ?? 'unknown error'}); nothing else changed.`,+ fix: { argv: o.notes.argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'Imports the notes folder (read only) into the brain; run it as its own step.' },+ });+ }+ const failed = o.pages.filter(p => p.action === 'failed');+ if (failed.length) {+ out.push({+ code: 'brain_layout_pages_pending', kind: 'coaching',+ why: `Setup could not write ${failed.map(p => p.slug).join(', ')} (${failed[0]!.detail}); the rest of the install finished.`,+ fix: { argv: [...setupArgv(harness, scope, source), '--shape', 'personal'], consent: [], actor: 'agent', requires_exclusive: true, why: 'Rerun once the brain is free; existing pages are kept.' },+ });+ }+ return out;+}++/**+ * The `brain_shape` decision for a brand-new brain set up without --shape. Nothing is written until it is+ * answered (default none); each option is the exact command that applies it.+ */+export function brainShapeDecision(harness: string, folders: string[] = candidateNoteFolders(), scope: LayoutScope = 'user', source: string | null = null): Decision {+ const base = [...setupArgv(harness, scope, source), '--shape', 'personal'];+ return {+ id: 'brain_shape',+ question: 'Make this a personal brain? Setup adds three empty starter pages (facts about you, your voice, how you decide), '+ + 'tells the agent to read them, and imports a notes folder you pick, read only. Nothing about you is invented.',+ options: [+ ...folders.slice(0, 3).map((f, i) => ({ id: `personal_notes_${i + 1}`, label: `Personal brain, importing ${f}`, argv: [...base, '--notes', f] })),+ { id: 'personal', label: 'Personal brain, no notes folder yet', argv: base },+ { id: 'none', label: 'No starter pages (memory works as it is)' },+ ],+ default: 'none',+ default_reason: 'Nothing is written until the user picks; memory already works without it.',+ };+}++/** The inline brain_shape question; readLine answers eof (decline) unless isInteractive(). */+export async function askBrainShape(folders: string[] = candidateNoteFolders()): Promise<{ brain?: BrainShape; notes?: string | null }> {+ const line = async (prompt: string): Promise<string | null> => { const r = await readLine({ prompt }); return r.kind === 'line' ? r.text : null; };+ const yes = (await line('Make this a personal brain? Three empty starter pages (facts about you, your voice, how you decide); nothing about you is invented. [y/N] '))?.toLowerCase();+ if (yes !== 'y' && yes !== 'yes') return {};+ const hint = folders[0] ? ` [${folders[0]}]` : '';+ const raw = (await line(`Notes folder to import, read only (Enter ${hint ? 'for the one shown' : 'to skip'}, "none" to skip)${hint}: `)) ?? 'none';+ const picked = raw === 'none' ? null : raw || folders[0] || null;+ if (!picked) return { brain: 'personal', notes: null };+ const abs = resolve(picked.startsWith('~/') ? join(homedir(), picked.slice(2)) : picked);+ try { if (statSync(abs).isDirectory()) return { brain: 'personal', notes: abs }; } catch { /* below */ }+ process.stderr.write(`${picked} is not a folder; skipping the import (run gbrain import <dir> --no-embed later)\n`);+ return { brain: 'personal', notes: null };+}++/** Add brain_shape to setup's first-run bundle (one bundle, never a second notice). */+export function withBrainShape(notices: Notice[], decision: Decision): Notice[] {+ const i = notices.findIndex(n => n.code === 'first_run_decisions');+ const line = ' Want a personal brain? I can add starter pages for facts about you, your voice and how you decide, and import a notes folder you pick.';+ if (i < 0) {+ return [{ code: 'first_run_decisions', kind: 'ask', why: 'Setup is complete and memory works now. One optional choice remains; nothing is written until the user answers.',+ user_message: `gbrain is set up, so memory works now.${line}`, decisions: [decision] }, ...notices];+ }+ const n = notices[i]!;+ const next = [...notices];+ next[i] = { ...n, user_message: `${n.user_message ?? ''}${line}`, decisions: [...(n.decisions ?? []), decision] };+ return next;+}diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 00a67c46ec..e2c1b7b396 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -125,6 +125,8 @@ import {type BrainFirstOutcome,} from '../core/setup/brain-first.ts';import { HARNESS_ADAPTERS } from '../core/harness/registry.ts';+import { applyBrainLayout, askBrainShape, brainShapeDecision, describeLayout, layoutNotices, parseLayoutFlags, withBrainShape, type BrainShape, type LayoutOutcome } from './setup-brain-layout.ts';+import { isInteractive } from '../core/interaction.ts';export const SETUP_HELP = `gbrain setup <harness> — give an agent harness memory in one command@@ -208,6 +210,18 @@ Flags:--wakeshift OpenClaw: install Wakeshift's OpenClaw plugin (@wakeshift/openclaw, pinned)so gbrain can wake an OpenClaw session when a job finishes. Asksconsent (--yes), runs OpenClaw's own installer, changes nothing else.+ --shape personal claude-code, codex: give the brain a personal shape. Writes three+ empty starter pages, create-only (me/facts, me/voice,+ me/how-i-decide, each marked status: stub; nothing about you is+ invented) and a short block beside the brain-first block that+ tells the agent to read them. A brand-new brain set up without+ --shape asks (at a terminal) or returns the brain_shape decision+ (agents); nothing is written until it is answered.+ --shape none Remove that block; the pages stay.+ --notes DIR With --shape personal: import a notes folder (absolute or ~/),+ read only, then check keyless search finds a note in it. Over+ 500 markdown files, setup prints the import command instead.+ A company brain (--shape company) arrives in a later release.--skills-index-only Refresh every skills index recorded for this harness (itsfile, launcher and skill set as recorded) and changenothing else; with --skill-loading off, remove them.@@ -285,9 +299,13 @@ interface SetupFlags {/** GST-363: written into this harness's MCP entry as serve --stdio-member; never into config. */stdioMember?: string;noStdioMember: boolean;+ /** GST-2731: the brain's shape (setup-brain-layout.ts); unset leaves it as it is. */+ brain?: BrainShape;+ /** GST-2731: the notes folder imported read only with --shape personal; null for --notes none. */+ notes?: string | null;}-const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member']);+const VALUE_FLAGS = new Set(['--shape', '--notes', '--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member']);function parseFlags(args: string[]): SetupFlags | string {const value = (flag: string): string | undefined => {@@ -318,6 +336,9 @@ function parseFlags(args: string[]): SetupFlags | string {if (memberFlag && (!['claude-code', 'codex'].includes(positionals[0] ?? '') || args.includes('--instructions-only') || args.includes('--remove'))) return `${memberFlag} changes the stdio MCP entry setup writes for claude-code or codex (not --instructions-only or --remove); nothing was written`;const shared = stdioMember === undefined ? null : sharedStdioHarness();if (shared) return `--stdio-member refused: ${shared} is installed on this host, and its sessions serve several people, so a stdio entry bound to one member is not something setup writes here; give each person their own key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> per person); nothing was written`;+ const layout = parseLayoutFlags(value, (f) => args.includes(f), positionals[0]);+ if (typeof layout === 'string') return layout;+ if (layout.brain && (!['claude-code', 'codex'].includes(positionals[0] ?? '') || args.includes('--instructions-only') || args.includes('--remove'))) return '--shape shapes the brain behind gbrain setup claude-code or codex (not --instructions-only or --remove); nothing was written';const workspace = value('--workspace');if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';const flagLoading = value('--skill-loading');@@ -373,6 +394,7 @@ function parseFlags(args: string[]): SetupFlags | string {...(args.includes('--labelled-only') ? { labelledOnly: true } : {}),...(stdioMember !== undefined ? { stdioMember } : {}),noStdioMember,+ ...layout,};}@@ -608,7 +630,8 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: stringconst instructions = brainFirstFor('claude-code', flags, mcpAccess(flags.name, plan.advertise ?? surface, serves), { scope, projectDir });const skills = skillsFor('claude-code', flags, launcher, { scope, projectDir }, instructions);const resolver = await resolverFor('claude-code', flags, launcher);- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves, launcher });+ const layout = await layoutFor('claude-code', flags, launcher, instructions, brainCreate);+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves, launcher, layout: layout.outcome });}let notices: Notice[] = [];@@ -632,8 +655,9 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string}const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('claude-code', { projectDir }) : null;- 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' })), instructions, skills, turnHook, resolver, serves, launcher });+ const layout = await layoutFor('claude-code', flags, launcher, instructions, brainCreate);+ const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices: layout.notices(notices), notes,+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves, launcher, layout: layout.outcome });if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('claude-code', turnHook, ['gbrain', 'setup', 'claude-code', ...(scope === 'project' ? ['--scope', 'project'] : [])]), out);return verify.ok || pluginOwner ? code : 1;} catch (e) {@@ -685,6 +709,22 @@ function liveServeConflict(live: NonNullable<Target['live_owner']>, harness: Setverify: verifyDryRun(harness, name) });}+/**+ * GST-2731: the brain's shape for this run. An explicit --shape applies it; a brand-new brain without one asks+ * inline when a person is at the terminal, and otherwise adds the brain_shape decision to the first-run bundle+ * (nothing is written until it is answered, --yes included).+ */+async function layoutFor(harness: SetupHarnessId, flags: SetupFlags, launcher: string, instructions: BrainFirstOutcome | null, brainCreate: boolean): Promise<{ outcome: LayoutOutcome | null; notices: (base: Notice[]) => Notice[] }> {+ let shape: { brain?: BrainShape; notes?: string | null } = { brain: flags.brain, notes: flags.notes };+ const ask = brainCreate && !shape.brain;+ if (ask && !flags.json && isInteractive()) shape = await askBrainShape();+ const scope = flags.scope ?? 'user';+ const source = flags.source ?? (process.env.GBRAIN_SOURCE && isValidSourceId(process.env.GBRAIN_SOURCE) ? process.env.GBRAIN_SOURCE : null);+ const outcome = applyBrainLayout({ harness, scope, source, launcher, instructionsPath: instructions?.path ?? null, instructionsDeclined: instructions?.decision.value === 'declined',+ flags: { brain: shape.brain, notes: shape.notes, dryRun: flags.dryRun } });+ return { outcome, notices: (base) => [...(ask && !shape.brain ? withBrainShape(base, brainShapeDecision(harness, undefined, scope, source)) : base), ...layoutNotices(outcome, harness, scope, source)] };+}+/** Run the `gbrain init --json` child that creates a new keyless brain; returns setup's form of its first-run bundle. */function runBrainInit(initArgv: string[], out: Out, harness: SetupHarnessId): Notice[] {say(out, `Creating the brain: ${initArgv.join(' ')}`);@@ -791,7 +831,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConconst instructions = brainFirstFor('codex', flags, mcpAccess(flags.name, plan.advertise ?? surface, serves), {});const skills = skillsFor('codex', flags, launcher, {}, instructions);const resolver = await resolverFor('codex', flags, launcher);- return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves });+ const layout = await layoutFor('codex', flags, launcher, instructions, brainCreate);+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves, layout: layout.outcome });}let notices: Notice[] = [];@@ -817,8 +858,9 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConconst 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 turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('codex') : null;+ const layout = await layoutFor('codex', flags, launcher, instructions, brainCreate);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, instructions, skills, turnHook, resolver, serves });+ steps: result.steps, states, verify, notices: layout.notices(notices), notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook, resolver, serves, layout: layout.outcome });if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('codex', turnHook, ['gbrain', 'setup', 'codex']), out);return verify.ok || pluginOwner ? code : 1;} catch (e) {@@ -1254,6 +1296,7 @@ async function finish(out: Out, doc: {resolver?: ResolverSetupResult | null;serves?: ServesOutcome | null;launcher?: string;+ layout?: LayoutOutcome | null;}): Promise<number> {const harness = doc.harness ?? 'claude-code';const state = doc.states.at(-1) ?? null;@@ -1267,6 +1310,7 @@ async function finish(out: Out, doc: {...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, skills: doc.skills ?? null, ...(doc.resolver ? { skill_resolver: doc.resolver } : {}), ...(doc.turnHook ? { turn_hook_check: doc.turnHook } : {}), states: doc.states, state, verify: doc.verify,...(doc.serves ? { serves: doc.serves } : {}),+ ...(doc.layout ? { brain_layout: doc.layout } : {}),capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,notes: doc.notes, notices: notices.map((n) => renderNotice(n, cliRenderContext())),}, null, 2)}\n`, (t) => process.stdout.write(t));@@ -1276,6 +1320,7 @@ async function finish(out: Out, doc: {if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));if (doc.skills && skillsOutcomeShown(doc.skills)) say(out, describeSkillsBlockOutcome(doc.skills, doc.dryRun));if (doc.resolver) for (const line of describeResolverSetup(doc.resolver, doc.dryRun)) say(out, line);+ if (doc.layout) for (const line of describeLayout(doc.layout, doc.dryRun)) say(out, line);if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);if (doc.turnHook?.ok) say(out, `Turn hook: ok (${doc.turnHook.reason}): ${doc.turnHook.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.'}`);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1655528e0b..67f88c65c1 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -125,7 +125,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', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--backend', '--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', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--command', '--credentials-file', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--command', '--credentials-file', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],'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', '--loop', '--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'],diff --git a/test/setup-brain-layout.test.ts b/test/setup-brain-layout.test.tsnew file mode 100644index 0000000000..61896cb31f--- /dev/null+++ b/test/setup-brain-layout.test.ts@@ -0,0 +1,230 @@+/**+ * GST-2731: \`gbrain setup <harness> --shape personal [--notes <dir>]\` (setup-brain-layout.ts).+ *+ * Authoring gate:+ * 1. Protects: the starter pages are create-only empty forms, the notes folder is+ * read and never written, a new brain set up by an agent gets the brain_shape+ * decision and no pages, and the layout block lives beside the brain-first block.+ * 2. Fails on: a re-run that overwrites an edited page, a byte changed in the notes+ * folder, a page written before the shape question is answered (--yes included),+ * an inline import of a huge folder, a company brain accepted before it exists.+ * 3. New flags on an existing command; test/setup.test.ts keeps the rest of setup.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { runCli, type CliResult } from './helpers/cli-spawn.ts';+import { LAYOUT_BEGIN, PERSONAL_PAGES, parseLayoutFlags, renderStarterPage, withBrainShape, brainShapeDecision, renderLayoutBlock, layoutNotices, applyBrainLayout, countNotes } from '../src/commands/setup-brain-layout.ts';++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { root: string; home: string; bin: string }+function box(): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-'));+ roots.push(root);+ const home = join(root, 'home');+ mkdirSync(join(root, 'bin'), { recursive: true });+ mkdirSync(home, { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ return { root, home, bin };+}++const CLEAN = { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1', CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };+const envOf = (b: Box) => ({ ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home });++async function setup(b: Box, args: string[]): Promise<CliResult & { doc: any }> {+ const r = await runCli(['setup', ...args, '--json', '--gbrain-bin', b.bin], { env: envOf(b) });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc };+}+const gbrain = (b: Box, args: string[]) => runCli(args, { env: envOf(b) });+const claudeMd = (b: Box) => join(b.home, '.claude', 'CLAUDE.md');++function notesDir(b: Box, extra = 0): string {+ const dir = join(b.root, 'notes');+ mkdirSync(join(dir, 'sub'), { recursive: true });+ writeFileSync(join(dir, 'pricing.md'), '# Pricing thoughts\n\nCharge per seat, not per query.\n');+ writeFileSync(join(dir, 'sub', 'hiring.md'), '---\ntitle: Hiring notes\n---\nHire slowly.\n');+ for (let i = 0; i < extra; i++) writeFileSync(join(dir, `bulk-${i}.md`), `# Bulk ${i}\n`);+ return dir;+}+function treeHash(dir: string): string {+ const h = createHash('sha256');+ const walk = (d: string): void => {+ for (const n of readdirSync(d, { withFileTypes: true }).sort((a, z) => a.name.localeCompare(z.name))) {+ const p = join(d, n.name);+ h.update(p);+ if (n.isDirectory()) walk(p); else h.update(readFileSync(p));+ }+ };+ walk(dir);+ return h.digest('hex');+}++describe('setup --shape personal', () => {+ test('a new brain set up by an agent gets the brain_shape decision and no pages, --yes included', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--yes']);+ expect(r.exitCode).toBe(0);+ const bundle = r.doc.notices.find((n: any) => n.code === 'first_run_decisions');+ const shape = bundle.decisions.find((d: any) => d.id === 'brain_shape');+ expect(shape.default).toBe('none');+ expect(shape.options.find((o: any) => o.id === 'personal').argv).toEqual(['gbrain', 'setup', 'claude-code', '--shape', 'personal']);+ expect(r.doc.brain_layout).toBeUndefined();+ expect((await gbrain(b, ['get', 'me/facts', '--json'])).exitCode).not.toBe(0);+ expect(readFileSync(claudeMd(b), 'utf8')).not.toContain(LAYOUT_BEGIN);+ }, 120_000);++ test('writes the stubs create-only, imports notes read only, and search finds a note', async () => {+ const b = box();+ const notes = notesDir(b);+ const before = treeHash(notes);+ const r = await setup(b, ['claude-code', '--shape', 'personal', '--notes', notes]);+ expect(r.exitCode).toBe(0);+ expect(r.doc.brain_layout.pages.map((p: any) => p.action)).toEqual(['write', 'write', 'write']);+ expect(r.doc.brain_layout.notes).toMatchObject({ action: 'imported', files: 2 });+ expect(r.doc.brain_layout.check.ok).toBe(true);+ expect(r.doc.brain_layout.next_question).toContain('Pricing thoughts');+ expect(r.doc.notices.some((n: any) => n.decisions?.some((d: any) => d.id === 'brain_shape'))).toBe(false);+ expect(treeHash(notes)).toBe(before);+ expect(readFileSync(claudeMd(b), 'utf8')).toContain(LAYOUT_BEGIN);+ const facts = await gbrain(b, ['get', 'me/facts']);+ expect(facts.stdout).toContain('status: stub');++ const edited = '---\ntitle: Facts about me\n---\n# Facts about me\n\n- 2026-11-15: I like tea. Source: I said so.\n';+ const put = Bun.spawnSync([b.bin, 'put', 'me/facts', '--force'], { stdin: new TextEncoder().encode(edited), stdout: 'pipe', stderr: 'pipe', env: Object.fromEntries(Object.entries({ ...process.env, ...envOf(b) }).filter(([, v]) => v !== undefined)) as Record<string, string> });+ expect(put.exitCode).toBe(0);+ const again = await setup(b, ['claude-code', '--shape', 'personal']);+ expect(again.exitCode).toBe(0);+ expect(again.doc.brain_layout.pages.map((p: any) => p.action)).toEqual(['keep', 'keep', 'keep']);+ expect(again.doc.brain_layout.block.action).toBe('keep');+ expect((await gbrain(b, ['get', 'me/facts'])).stdout).toContain('I like tea');++ const none = await setup(b, ['claude-code', '--shape', 'none']);+ expect(none.exitCode).toBe(0);+ expect(none.doc.brain_layout.block.action).toBe('remove');+ expect(readFileSync(claudeMd(b), 'utf8')).not.toContain(LAYOUT_BEGIN);+ expect((await gbrain(b, ['get', 'me/facts'])).stdout).toContain('I like tea');+ }, 240_000);++ test('a folder over the inline limit is handed to the agent as a command', async () => {+ const b = box();+ const notes = notesDir(b, 500);+ const r = await setup(b, ['claude-code', '--shape', 'personal', '--notes', notes]);+ expect(r.exitCode).toBe(0);+ expect(r.doc.brain_layout.notes.action).toBe('deferred');+ const n = r.doc.notices.find((x: any) => x.code === 'brain_layout_import_pending');+ expect(n.fix.argv.slice(0, 4)).toEqual(['gbrain', 'import', notes, '--no-embed']);+ expect(r.doc.brain_layout.pages.every((p: any) => p.action === 'write')).toBe(true);+ }, 180_000);++ test('--no-instructions writes the pages and no layout block', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--shape', 'personal', '--no-instructions']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.brain_layout.block).toBeNull();+ expect(r.doc.brain_layout.pages.every((p: any) => p.action === 'write')).toBe(true);+ expect(existsSync(claudeMd(b)) ? readFileSync(claudeMd(b), 'utf8') : '').not.toContain(LAYOUT_BEGIN);+ }, 120_000);++ test('--no-instructions after a personal layout takes the layout block out too', async () => {+ const b = box();+ expect((await setup(b, ['claude-code', '--shape', 'personal'])).exitCode).toBe(0);+ expect(readFileSync(claudeMd(b), 'utf8')).toContain(LAYOUT_BEGIN);+ const off = await setup(b, ['claude-code', '--no-instructions']);+ expect(off.exitCode).toBe(0);+ expect(off.doc.brain_layout.block.action).toBe('remove');+ expect(readFileSync(claudeMd(b), 'utf8')).not.toContain(LAYOUT_BEGIN);+ }, 180_000);++ test('codex gets the block in its AGENTS.md', async () => {+ const b = box();+ const r = await setup(b, ['codex', '--shape', 'personal']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.brain_layout.block.path).toBe(join(b.home, '.codex', 'AGENTS.md'));+ expect(readFileSync(join(b.home, '.codex', 'AGENTS.md'), 'utf8')).toContain(LAYOUT_BEGIN);+ }, 120_000);++ test('--shape company is refused before anything is written', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--shape', 'company']);+ expect(r.exitCode).not.toBe(0);+ expect(r.stderr + r.stdout).toContain('later gbrain release');+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);+ }, 60_000);+});++describe('layout units', () => {+ test('the starter pages hold only template text', () => {+ for (const p of PERSONAL_PAGES) {+ const text = renderStarterPage(p);+ expect(text).toContain('status: stub');+ for (const line of text.split('\n').filter((l) => l.startsWith('- '))) expect(line.startsWith('- Example (delete me):')).toBe(true);+ }+ });++ test('flag validation', () => {+ const parse = (args: string[]) => parseLayoutFlags((f) => { const i = args.indexOf(f); return i < 0 ? undefined : args[i + 1]; }, (f) => args.includes(f), 'claude-code');+ expect(parse(['--notes', '/tmp'])).toContain('--shape personal');+ expect(parse(['--shape', 'personal', '--notes', 'rel/dir'])).toContain('absolute');+ expect(parse(['--shape', 'both'])).toContain('later gbrain release');+ expect(parse(['--shape', 'personal', '--notes', 'none'])).toEqual({ brain: 'personal', notes: null });+ });++ test('brain_shape joins the existing first-run bundle', () => {+ const merged = withBrainShape([{ code: 'first_run_decisions', kind: 'ask', why: 'x', user_message: 'Hi.', decisions: [] } as any], brainShapeDecision('codex', []));+ expect(merged).toHaveLength(1);+ expect(merged[0]!.decisions!.map((d) => d.id)).toEqual(['brain_shape']);+ });++ test('a project-scope run keeps --scope project in every command it hands out', () => {+ const argvs = (scope?: 'user' | 'project') => {+ const d = brainShapeDecision('claude-code', ['/notes'], scope);+ const failed = { shape: 'personal', pages: [{ slug: 'me/facts', action: 'failed', detail: 'locked' }], notes: null, block: null, check: { ok: true, query: null, detail: '' }, next_question: null } as any;+ return [...d.options.filter((o) => o.argv).map((o) => o.argv!), ...layoutNotices(failed, 'claude-code', scope).map((n) => n.fix!.argv!)];+ };+ for (const argv of argvs('project')) expect(argv.slice(0, 5)).toEqual(['gbrain', 'setup', 'claude-code', '--scope', 'project']);+ for (const argv of argvs()) expect(argv).not.toContain('--scope');+ expect(renderLayoutBlock('claude-code', 'project')).toContain('Remove: gbrain setup claude-code --scope project --shape none');+ expect(renderLayoutBlock('claude-code')).toContain('Remove: gbrain setup claude-code --shape none');+ });++ test('a pinned source rides every command and child the layout runs', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-src-'));+ roots.push(root);+ writeFileSync(join(root, 'a.md'), '# A\n');+ const calls: string[][] = [];+ const o = applyBrainLayout({ harness: 'claude-code', source: 'private', launcher: 'gbrain', instructionsPath: null, flags: { brain: 'personal', notes: root, dryRun: false },+ run: (argv) => { calls.push(argv); return { code: 0, stdout: '[]', stderr: '' }; } })!;+ expect(o.notes!.argv).toEqual(['gbrain', 'import', root, '--no-embed', '--source', 'private']);+ expect(brainShapeDecision('claude-code', [], 'user', 'private').options.find((x) => x.id === 'personal')!.argv).toEqual(['gbrain', 'setup', 'claude-code', '--source', 'private', '--shape', 'personal']);+ expect(renderLayoutBlock('claude-code', 'user', 'private')).toContain('Remove: gbrain setup claude-code --source private --shape none');+ });++ test('a starter page is written only when get says page_not_found', () => {+ const calls: string[][] = [];+ const o = applyBrainLayout({ harness: 'claude-code', launcher: 'gbrain', instructionsPath: null, flags: { brain: 'personal', notes: null, dryRun: false },+ run: (argv) => { calls.push(argv); return argv[1] === 'get' ? { code: 1, stdout: '{"code":"file_held"}', stderr: 'Error [file_held]: held' } : { code: 0, stdout: '', stderr: '' }; } })!;+ expect(o.pages.map((p) => p.action)).toEqual(['failed', 'failed', 'failed']);+ expect(calls.some((c) => c[1] === 'put')).toBe(false);+ const wrote = applyBrainLayout({ harness: 'claude-code', launcher: 'gbrain', instructionsPath: null, flags: { brain: 'personal', notes: null, dryRun: false },+ run: (argv) => (argv[1] === 'get' ? { code: 1, stdout: '{"code":"page_not_found"}', stderr: '' } : { code: 0, stdout: '', stderr: '' }) })!;+ expect(wrote.pages.map((p) => p.action)).toEqual(['write', 'write', 'write']);+ });++ test('the notes count does not follow symlinked folders', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-loop-'));+ roots.push(root);+ symlinkSync(root, join(root, 'loop-a'));+ symlinkSync(root, join(root, 'loop-b'));+ writeFileSync(join(root, 'n.md'), '# N\n');+ expect(countNotes(root)).toEqual({ count: 1, first: join(root, 'n.md') });+ });+});