Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Setup can make a company brain: a company source, starter pages and your docs (GST-2731) (#9419)

Garry Tanedded7825477
diff --git a/changelog.d/setup-company-brain.md b/changelog.d/setup-company-brain.md
new file mode 100644
index 0000000000..a6a2f76cca
--- /dev/null
+++ b/changelog.d/setup-company-brain.md
@@ -0,0 +1,8 @@
+**`gbrain setup claude-code --shape company` (or `both`, and the same for `codex`) gives a brain a company part: a `company` source in a folder gbrain owns, six empty company pages, your docs folder imported read only, and lines in the agent's instructions that say which pages to read.** The pages are `company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls` and `company/playbooks`. Each is an empty form marked `status: stub`, so nothing about the company is invented, and a re-run never overwrites a page you have edited. `--docs DIR` imports that folder's markdown once without writing into it; above 500 files setup prints the import command instead of running it. On a brain that serves one person the company pages join default search. On a brain more than one person reads they stay out of it, and setup asks you before adding them. `--shape both` sets up the personal and company parts together. `--team` creates nothing for the company part and explains where a shared company brain lives, either in a hosted workspace or on a self-hosted brain that serves several people. If the company folder already holds files, setup leaves it alone, keeps the company lines out of the agent's instructions and asks you to move the files before you run it again.
+
+### Itemized changes
+
+- `src/commands/setup-brain-layout.ts`: the company and both shapes, the company starter pages, the `company` source and its read-only docs import, company lines in the managed `gbrain:brain-layout` block (now version 2), the team route, and new options in the `brain_shape` question. Personal pages are written before the company source is added, so they stay in your default source. A company folder that already exists and is not an empty folder (a file included) is refused instead of adopted. The re-run command setup hands back keeps `--team`, and after a refused company folder it asks you first instead of re-running by itself. Both reply formats of `sources add --json` are read when checking whether the company source joined default search.
+- `src/commands/setup.ts`: `--shape company|both`, `--docs DIR` and `--team` for `claude-code` and `codex`.
+- Docs: `docs/guides/brain-layout.md` covers the company part and a team company brain.
+- Tests: `test/setup-brain-layout.test.ts`.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index bd475a7956..422f697867 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -29,7 +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/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--team|--solo]` (GST-2731; guide `docs/guides/brain-layout.md`). Every page is written create-only through `gbrain get` then `gbrain put` children, and only when `get` reports `page_not_found` (empty forms, `status: stub`, one "Example (delete me)" line each): `me/facts`, `me/voice`, `me/how-i-decide` in the run's source, and `COMPANY_PAGES` (`company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls`, `company/playbooks`) in the `company` source. The company source is kept when it exists, else added with `gbrain sources add company --path <dir>` on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with an `ask_user` `brain_layout_pages_pending` and the block is written without company lines) with no federation flag, so `sources add` federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns `source_not_in_default_search` with `ask_user`. `--notes` and `--docs` import read only with one `gbrain import DIR --no-embed --json` child each (GBRAIN_SOURCE pins the source; over `IMPORT_INLINE_MAX` = 500 markdown files it returns `brain_layout_import_pending` instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). `--team` creates nothing for the company part and returns `brain_layout_team_next`. A `<!-- gbrain:brain-layout:begin/end -->` block (lines per part) goes into the brain-first target only when the brain-first decision is accepted; `--no-instructions` removes it, `--shape none` removes it and keeps pages and source. 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.md
index 0b3f2726b2..d404df7b0b 100644
--- a/docs/guides/brain-layout.md
+++ b/docs/guides/brain-layout.md
@@ -1,16 +1,17 @@
-# A personal brain in one command
+# A personal or company 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.
+`gbrain setup` gives an agent memory. `--shape` also gives that memory a starting shape:
+a few pages the agent reads, and your existing notes or company docs, searchable from the
+first session.
```bash
gbrain setup claude-code --shape personal --notes ~/notes
-# or
-gbrain setup codex --shape personal --notes ~/notes
+gbrain setup claude-code --shape company --docs ~/acme-example/docs
+gbrain setup claude-code --shape both --notes ~/notes --docs ~/acme-example/docs
+# Codex: the same with gbrain setup codex
```
-## What it writes
+## Personal: 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)"
@@ -21,32 +22,76 @@ gbrain setup codex --shape personal --notes ~/notes
(`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.
+## Company: what it writes
+
+- **A `company` source** in the same brain, kept in a folder gbrain owns next to the
+ brain's own content (never your docs folder). When the brain serves one person it joins
+ default search, so a question that names no source finds company pages too. When the
+ brain may serve several people (`gbrain access serves` says several, or
+ `brain.audience` is `shared`), it stays out of default search and setup asks you first:
+ `gbrain sources federate company` puts it in. If that folder already exists and is not
+ an empty folder, setup leaves it alone, keeps the company lines out of the instruction
+ block and asks you to move it before you run setup again.
+- **Six starter pages** in that source, only when they don't exist yet: `company/facts`
+ (numbers agents may quote, each dated with where it came from), `company/decisions`
+ (a dated log: what, why, who, what would make you revisit it), `company/pricing`, and
+ index pages `company/customers`, `company/calls` and `company/playbooks`. Each is an
+ empty form marked `status: stub`.
+- **Your company docs, read only.** `--docs DIR` imports that folder into the `company`
+ source the same way `--notes` does, with the same 500-file limit.
+
+`--shape both` does both parts.
+
+## The instruction block
+
+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 names the
+pages to read for the parts you chose, says to state facts about you only from `me/facts`
+and company numbers only from `company/facts`, to add decisions to `company/decisions` as
+dated entries, to save company facts with `--source company`, 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 or docs by its title (for
+company docs, through default search when the source is in it) and prints a question to
+try in a new session. With no docs folder, it suggests `gbrain sources demo company-brain`
+to see how a company brain answers.
+
+## A team company brain
+
+A company brain your team shares belongs on its own brain, so teammates never reach the
+personal pages on your laptop. `--team` (with `--shape company` or `both`) creates
+nothing for the company part. It writes the personal part if you asked for it, and tells
+you where the shared brain lives:
+
+- **Hosted:** a workspace at [gbrain.io](https://gbrain.io) (`gbrainio workspace new`),
+ which teammates join by invite.
+- **Self-hosted:** a Postgres brain, with `gbrain access serves several` naming who it
+ serves.
+
+Then connect your harness to the shared brain as well. Pages only some teammates may read
+use `readable_by` in their frontmatter, or `gbrain access rule add --prefix <folder>/` for
+a whole folder. A company source you set up alone with `--solo` (the default) stays on
+this brain; moving it to a shared brain later is a separate step.
## 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.
+A brand-new brain set up without `--shape` asks once when a person is at the terminal:
+personal, company, both or skip, then the folders, then just you or a team. 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.
+`gbrain setup <harness> --shape none` removes the block. The pages and the `company`
+source stay; delete pages with `gbrain delete <slug>` (company ones with
+`--source company`) 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`.
+> Install gbrain and give it a shape: run `gbrain setup claude-code --shape personal`
+> (or `company`, or `both`). If I have a notes folder, add `--notes <that folder>`; for
+> company docs, add `--docs <that folder>`; if my team will share the company brain, add
+> `--team`. Then tell me what it wrote and the question to try.
diff --git a/src/commands/setup-brain-layout.ts b/src/commands/setup-brain-layout.ts
index e61a0a5613..7f26a14b60 100644
--- a/src/commands/setup-brain-layout.ts
+++ b/src/commands/setup-brain-layout.ts
@@ -1,59 +1,66 @@
/**
- * GBRA-529 (GST-2731), PR 1: `gbrain setup <harness> --shape personal [--notes <dir>]`.
+ * GBRA-529 (GST-2731): `gbrain setup <harness> --shape personal|company|both [--notes <dir>] [--docs <dir>] [--team]`.
*
- * The personal branch of the branching install. After setup has wired the
- * harness, it gives the brain a shape:
+ * 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.
+ * - starter pages, written create-only through `gbrain put` (the one writer door: on a source 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 or the
+ * company is invented. Personal pages go to the run's source, company pages to the `company` source;
+ * - the `company` source itself, a gbrain-owned folder beside the default source's content root (never the
+ * person's docs folder), added with no federation choice so `sources add` puts it in default search only
+ * when the brain serves one person; otherwise its `source_not_in_default_search` notice asks the user;
+ * - a one-shot import of the notes folder (personal) and the docs folder (company), 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 which pages to read and to quote
+ * facts and numbers only from the facts pages. `--shape none` removes the block and keeps the pages;
+ * - a keyless check that default search finds an imported file, 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
+ * `--team` with a company shape creates nothing for the company part: it prints where a shared company brain
+ * lives (hosted or self-hosted) and runs nothing. 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 { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
-import { basename, join, resolve } from 'node:path';
+import { basename, dirname, join, resolve } from 'node:path';
import type { Decision, Notice } from '../core/agent-output.ts';
+import { gbrainPath } from '../core/config.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 type BrainShape = 'personal' | 'company' | 'both' | 'none';
export interface LayoutFlags {
brain?: BrainShape;
/** An absolute notes folder; null for an explicit `--notes none`. */
notes?: string | null;
+ /** An absolute company docs folder; null for an explicit `--docs none`. */
+ docs?: string | null;
+ /** --team: the company part belongs on a shared brain, so setup prints the route and creates nothing for it. */
+ team?: boolean;
dryRun: boolean;
}
export const IMPORT_INLINE_MAX = 500;
-export const LAYOUT_VERSION = 1;
+export const LAYOUT_VERSION = 2;
export const LAYOUT_BEGIN = '<!-- gbrain:brain-layout:begin -->';
export const LAYOUT_END = '<!-- gbrain:brain-layout:end -->';
+export const COMPANY_SOURCE = 'company';
export type LayoutScope = 'user' | 'project';
+const hasPersonal = (s: BrainShape | undefined): boolean => s === 'personal' || s === 'both';
+const hasCompany = (s: BrainShape | undefined): boolean => s === 'company' || s === 'both';
+
/** 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(' ') });
+const markers = (harness: string, scope: LayoutScope, source: string | null, shape: BrainShape): BlockMarkers => ({ begin: LAYOUT_BEGIN, end: LAYOUT_END, label: 'brain-layout', rerun: [...setupArgv(harness, scope, source), '--shape', shape === 'none' ? 'personal' : shape].join(' ') });
export interface StarterPage { slug: string; title: string; body: string }
@@ -82,20 +89,75 @@ export const PERSONAL_PAGES: readonly StarterPage[] = [
},
];
+/** The company starter pages, in the company source: empty forms with one marked example line each. */
+export const COMPANY_PAGES: readonly StarterPage[] = [
+ {
+ slug: 'company/facts',
+ title: 'Company facts',
+ body: 'Numbers and facts agents may quote. One line each, with a date and where it came from. '
+ + 'Never overwrite a line: when a number changes, add a new dated line.\n\n'
+ + '- Example (delete me): 2026-01-01: 12 paying customers. Source: billing export.',
+ },
+ {
+ slug: 'company/decisions',
+ title: 'Decisions',
+ body: 'A dated log of decisions: what we decided, why, who decided, and what would make us revisit it. '
+ + 'Add new entries at the bottom; never rewrite an old one.\n\n'
+ + '- Example (delete me): 2026-01-01: Decision: annual plans only. Why: churn. Who: founders. Revisit if: churn drops below 2%.',
+ },
+ {
+ slug: 'company/pricing',
+ title: 'Pricing',
+ body: 'Current prices and plans, each with the date it took effect.\n\n'
+ + '- Example (delete me): 2026-01-01: Team plan, $20 per seat per month.',
+ },
+ {
+ slug: 'company/customers',
+ title: 'Customers',
+ body: 'An index of customer pages: one line per customer, linking its page.\n\n'
+ + '- Example (delete me): acme-example, customer since 2026-01.',
+ },
+ {
+ slug: 'company/calls',
+ title: 'Calls',
+ body: 'An index of call notes: one line per call, with its date, who was on it and a link to its page.\n\n'
+ + '- Example (delete me): 2026-01-01, acme-example renewal call.',
+ },
+ {
+ slug: 'company/playbooks',
+ title: 'Playbooks',
+ body: 'An index of how we do recurring work: one line per playbook, linking its page.\n\n'
+ + '- Example (delete me): onboarding a new customer.',
+ },
+];
+
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 [
+/** The shape the block describes: the company part only when setup made it locally (not --team). */
+const blockShape = (shape: BrainShape, team: boolean): BrainShape =>
+ !team || !hasCompany(shape) ? shape : shape === 'both' ? 'personal' : 'none';
+
+export function renderLayoutBlock(harness: string, scope: LayoutScope = 'user', source: string | null = null, shape: BrainShape = 'personal'): string {
+ const lines = [
`<!-- 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');
+ ];
+ if (hasPersonal(shape)) {
+ lines.push('- 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.');
+ }
+ if (hasCompany(shape)) {
+ lines.push(`- Before a task that needs the company's context, read company/facts, company/decisions and company/pricing (source ${COMPANY_SOURCE}).`,
+ '- Quote company numbers only from company/facts, and name it.',
+ '- Add a new decision to company/decisions as a dated entry with why, who and what would make us revisit it.',
+ `- Save company facts and decisions with --source ${COMPANY_SOURCE}; personal ones go to the default source.`);
+ }
+ lines.push('- 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.');
+ return lines.join('\n');
}
/** Markdown files under `dir` (dot folders skipped), counted up to `cap` + 1, with the first one found. */
@@ -144,43 +206,56 @@ export function candidateNoteFolders(home: string = homedir()): string[] {
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`;
+/** --shape / --notes / --docs / --team 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; docs?: string | null; team?: boolean } | string {
+ const brain = value('--shape') as BrainShape | undefined;
+ if (brain !== undefined && !['personal', 'company', 'both', 'none'].includes(brain)) return `unknown --shape '${brain}'; pass personal, company, both or none`;
+ const out: { brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = brain ? { brain } : {};
+ const folders = [['--notes', 'notes', hasPersonal, 'personal or both'], ['--docs', 'docs', hasCompany, 'company or both']] as const;
+ for (const [flag, key, needs, shapes] of folders) {
+ const raw = value(flag);
+ if (raw === undefined) continue;
+ if (!needs(brain)) return `${flag} needs --shape ${shapes}`;
+ if (raw === 'none') { out[key] = null; continue; }
+ const abs = raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw;
+ if (!abs.startsWith('/')) return `${flag} needs an absolute path (or ~/...)`;
+ try { if (!statSync(abs).isDirectory()) return `${flag} ${raw} is not a folder`; } catch { return `${flag} ${raw} does not exist`; }
+ if (has('--remove')) return `${flag} and --remove do not go together`;
+ out[key] = resolve(abs);
+ }
+ if (has('--team') && has('--solo')) return '--team and --solo do not go together';
+ if ((has('--team') || has('--solo')) && !hasCompany(brain)) return '--team and --solo need --shape company or both';
+ if (has('--team')) {
+ if (out.docs) return `--docs imports into this machine's company source, and with --team the company part lives on a shared brain; drop --docs or use --solo (gbrain setup ${harness ?? '<harness>'} --shape ${brain} --solo)`;
+ out.team = true;
}
- 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) };
+ return out;
}
+export interface ImportOutcome { dir: string; files: number; action: 'imported' | 'deferred' | 'failed'; argv: string[]; detail?: string }
+
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;
+ pages: Array<{ slug: string; source: string | null; action: 'write' | 'keep' | 'failed'; detail?: string }>;
+ notes: ImportOutcome | null;
+ docs: ImportOutcome | null;
+ company: { source: string; action: 'created' | 'kept' | 'team' | 'failed'; federated: boolean | null; root: string | null; 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) });
+/** A gbrain child; `source` pins it to one source through GBRAIN_SOURCE (null: the caller's environment as it is). */
+type Run = (argv: string[], stdin?: string, source?: string | null) => { code: number; stdout: string; stderr: string };
+const run: Run = (argv, stdin, source) => {
+ const env = source ? { ...process.env, GBRAIN_SOURCE: source } : process.env;
+ const child = bunSpawnSync(argv, { stdin: stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin), stdout: 'pipe', stderr: 'pipe', env });
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 m = markers(harness, scope, source, shape);
const exists = existsSync(path);
const text = exists ? readFileSync(path, 'utf8') : '';
const probe = probeBlock(m, text);
@@ -190,63 +265,129 @@ function syncLayoutBlock(path: string | null, harness: string, scope: LayoutScop
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);
+ const body = renderLayoutBlock(harness, scope, source, shape);
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}` };
}
+/** Each page create-only: written only when `get` says page_not_found, so a read error never becomes an overwrite. */
+function writePages(exec: Run, launcher: string, pages: readonly StarterPage[], source: string | null, dryRun: boolean): LayoutOutcome['pages'] {
+ return pages.map((page) => {
+ if (dryRun) return { slug: page.slug, source, action: 'write', detail: 'would write if missing' };
+ const got = exec([launcher, 'get', page.slug, '--json'], undefined, source);
+ if (got.code === 0) return { slug: page.slug, source, action: 'keep' };
+ if (errorCode(got.stdout) !== 'page_not_found') return { slug: page.slug, source, action: 'failed', detail: lastLine(got.stderr || got.stdout) };
+ const put = exec([launcher, 'put', page.slug, '--json'], renderStarterPage(page), source);
+ return put.code === 0 ? { slug: page.slug, source, action: 'write' } : { slug: page.slug, source, action: 'failed', detail: lastLine(put.stderr) };
+ });
+}
+
+/** One read-only import of `dir` into `source`, deferred to the agent above IMPORT_INLINE_MAX; returns the first file's title to search for. */
+function importFolder(exec: Run, launcher: string, dir: string, source: string | null, dryRun: boolean): { outcome: ImportOutcome; title: string | null } {
+ const { count, first } = countNotes(dir);
+ const argv = ['gbrain', 'import', dir, '--no-embed', ...(source ? ['--source', source] : [])];
+ if (count > IMPORT_INLINE_MAX) return { outcome: { dir, files: count, action: 'deferred', argv, detail: `more than ${IMPORT_INLINE_MAX} markdown files; run the import as its own step` }, title: null };
+ if (dryRun) return { outcome: { dir, files: count, action: 'imported', argv, detail: 'would import (read only)' }, title: null };
+ const imp = exec([launcher, 'import', dir, '--no-embed', '--json'], undefined, source);
+ if (imp.code !== 0) return { outcome: { dir, files: count, action: 'failed', argv, detail: lastLine(imp.stderr) }, title: null };
+ return { outcome: { dir, files: count, action: 'imported', argv }, title: first ? noteTitle(first) : null };
+}
+
+/** Whether keyless search (scoped to `source`, or default search for null) puts `title` in its top 5. */
+function searchFinds(exec: Run, launcher: string, title: string, source: string | null): boolean {
+ const hits = exec([launcher, 'search', title, '--json'], undefined, source);
+ try { return (JSON.parse(hits.stdout) as Array<{ title?: string }>).slice(0, 5).some(h => (h.title ?? '').trim().toLowerCase() === title.toLowerCase()); } catch { return false; }
+}
+
+/** The company source: kept when it exists, else added on a gbrain-owned folder beside the default source's content root. */
+function ensureCompanySource(exec: Run, launcher: string, dryRun: boolean): NonNullable<LayoutOutcome['company']> {
+ const failed = (detail: string) => ({ source: COMPANY_SOURCE, action: 'failed' as const, federated: null, root: null, detail });
+ const listed = exec([launcher, 'sources', 'list', '--json'], undefined, null);
+ let sources: Array<{ id: string; local_path: string | null; federated: boolean }> = [];
+ try { sources = (JSON.parse(listed.stdout) as { sources?: typeof sources }).sources ?? []; } catch { return failed(lastLine(listed.stderr || listed.stdout)); }
+ const existing = sources.find(s => s.id === COMPANY_SOURCE);
+ if (existing) return { source: COMPANY_SOURCE, action: 'kept', federated: existing.federated, root: existing.local_path };
+ const defaultRoot = sources.find(s => s.id === 'default')?.local_path;
+ const root = defaultRoot ? join(dirname(defaultRoot), COMPANY_SOURCE) : gbrainPath('content', COMPANY_SOURCE);
+ if (dryRun) return { source: COMPANY_SOURCE, action: 'created', federated: null, root, detail: 'would add' };
+ const st = lstatSync(root, { throwIfNoEntry: false });
+ if (st && (!st.isDirectory() || readdirSync(root).length > 0)) return failed(`${root} already exists and is not an empty folder; move it or add a folder yourself with gbrain sources add ${COMPANY_SOURCE} --path <folder>`);
+ mkdirSync(root, { recursive: true });
+ const add = exec([launcher, 'sources', 'add', COMPANY_SOURCE, '--path', root, '--json'], undefined, null);
+ if (add.code !== 0) return failed(lastLine(add.stderr || add.stdout));
+ let federated = false;
+ try { const doc = JSON.parse(add.stdout) as { federated?: unknown; config?: { federated?: unknown } }; federated = doc.federated === true || doc.config?.federated === true; } catch { /* unreadable: not federated */ }
+ return { source: COMPANY_SOURCE, action: 'created', federated, root };
+}
+
/**
- * 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.
+ * The 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. `source` is
+ * the run's pinned source, where personal pages and notes go; company pages and docs always go to COMPANY_SOURCE.
*/
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 team = !!flags.team;
+ const empty = (shape: BrainShape, block: LayoutOutcome['block']): LayoutOutcome => ({ shape, pages: [], notes: null, docs: null, company: null, block, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null });
+ const written = flags.brain ? blockShape(flags.brain, team) : undefined;
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 };
+ const block = opts.instructionsDeclined ? (removed?.action === 'skip' ? null : removed)
+ : written && written !== 'none' ? syncLayoutBlock(opts.instructionsPath, harness, scope, source, written, flags.dryRun)
+ : flags.brain === 'none' ? syncLayoutBlock(opts.instructionsPath, harness, scope, source, 'none', flags.dryRun) : null;
+ if (!flags.brain) return block && opts.instructionsDeclined ? empty('none', block) : null;
+ const exec = opts.run ?? run;
+ const outcome = empty(flags.brain, block);
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 (hasPersonal(flags.brain)) {
+ outcome.pages.push(...writePages(exec, launcher, PERSONAL_PAGES, source, flags.dryRun));
+ if (flags.notes) {
+ const { outcome: notes, title } = importFolder(exec, launcher, flags.notes, source, flags.dryRun);
+ outcome.notes = notes;
+ if (title) {
+ const found = searchFinds(exec, launcher, title, source);
+ 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 (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)' };
+ if (hasCompany(flags.brain)) {
+ if (team) {
+ outcome.company = { source: COMPANY_SOURCE, action: 'team', federated: null, root: null, detail: 'a shared company brain is set up on its own; nothing was created here' };
} 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}?"`;
+ const company = outcome.company = ensureCompanySource(exec, launcher, flags.dryRun);
+ if (company.action === 'failed' && !opts.instructionsDeclined) outcome.block = syncLayoutBlock(opts.instructionsPath, harness, scope, source, blockShape(flags.brain, true), flags.dryRun);
+ if (company.action !== 'failed') {
+ outcome.pages.push(...writePages(exec, launcher, COMPANY_PAGES, COMPANY_SOURCE, flags.dryRun));
+ if (flags.docs) {
+ const { outcome: docs, title } = importFolder(exec, launcher, flags.docs, COMPANY_SOURCE, flags.dryRun);
+ outcome.docs = docs;
+ if (title) {
+ const inDefault = company.federated === true;
+ const found = searchFinds(exec, launcher, title, inDefault ? null : COMPANY_SOURCE);
+ const where = inDefault ? 'default search' : `search of the ${COMPANY_SOURCE} source`;
+ outcome.check = found
+ ? { ok: outcome.check.ok, query: title, detail: `keyless ${where} found "${title}" from your company docs` }
+ : { ok: false, query: title, detail: `keyless ${where} did not find "${title}" in its top 5; run gbrain search "${title}"${inDefault ? '' : ` --source ${COMPANY_SOURCE}`} to see what it returns` };
+ if (found) outcome.next_question = `In a new session, ask: "what did we decide about ${title}, and why?"`;
+ }
+ }
+ if (!outcome.next_question && !flags.dryRun && !hasPersonal(flags.brain)) {
+ outcome.next_question = 'Run gbrain sources demo company-brain to see how a company brain answers, then add one dated line to company/decisions and ask about it in a new session.';
+ }
+ }
}
}
- 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' }
+
+ if (!outcome.next_question && !flags.dryRun && hasPersonal(flags.brain)) {
+ const facts = exec([launcher, 'get', 'me/facts', '--json'], undefined, source);
+ outcome.check = facts.code === 0 ? { ...outcome.check, 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?"';
}
@@ -267,31 +408,63 @@ 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.company) {
+ const c = o.company;
+ lines.push(c.action === 'team' ? ` company team: ${c.detail}`
+ : c.action === 'failed' ? ` company failed: ${c.detail}`
+ : ` company ${would}${c.action === 'kept' ? 'keep' : 'add'} source ${c.source}${c.root ? ` at ${c.root}` : ''}${c.federated === null ? '' : c.federated ? ' (in default search)' : ' (not in default search)'}`);
+ }
+ for (const p of o.pages) lines.push(` page ${p.action.padEnd(7)} ${p.slug}${p.source === COMPANY_SOURCE ? ` (source ${COMPANY_SOURCE})` : ''}${p.detail ? ` (${p.detail})` : ''}`);
+ for (const [label, i] of [['notes', o.notes], ['docs', o.docs]] as const) {
+ if (i) lines.push(` ${label.padEnd(8)} ${i.action === 'imported' ? `${would}import ${i.files} file(s) from ${i.dir} (read only)` : `${i.action}: ${i.detail ?? ''} (${i.argv.join(' ')})`}`);
+ }
+ if (!dryRun && o.shape !== 'none' && o.check.detail !== 'nothing to check') 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. */
+/** Notices for what the agent still has to do: a deferred or failed import, a failed page, the company source left out of search, the team route. */
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') {
+ for (const i of [o.notes, o.docs]) {
+ if (!i || i.action === 'imported') continue;
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.' },
+ why: i.action === 'deferred' ? `${i.dir} holds more than ${IMPORT_INLINE_MAX} markdown files, so setup did not import it inline.`
+ : `The import of ${i.dir} did not finish (${i.detail ?? 'unknown error'}); nothing else changed.`,
+ fix: { argv: i.argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'Imports the folder (read only) into the brain; run it as its own step.' },
});
}
const failed = o.pages.filter(p => p.action === 'failed');
- if (failed.length) {
+ if (failed.length || o.company?.action === 'failed') {
+ const what = [...failed.map(p => p.slug), ...(o.company?.action === 'failed' ? [`the ${COMPANY_SOURCE} source`] : [])];
+ const companyFailed = o.company?.action === 'failed';
+ const detail = companyFailed ? o.company!.detail : failed[0]!.detail;
+ const argv = [...setupArgv(harness, scope, source), '--shape', o.shape, ...(o.company?.action === 'team' ? ['--team'] : [])];
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.' },
+ why: `Setup could not write ${what.join(', ')} (${detail}); the rest of the install finished.`,
+ fix: companyFailed
+ ? { ask_user: true, argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'The company source needs the user to fix its folder first; existing pages are kept.',
+ user_message: `Setup could not add the ${COMPANY_SOURCE} source: ${detail}. Once that is fixed, rerun ${argv.join(' ')}` }
+ : { argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'Rerun once the brain is free; existing pages are kept.' },
+ });
+ }
+ if (o.company && o.company.federated === false) {
+ out.push({
+ code: 'source_not_in_default_search', kind: 'info',
+ why: `The ${COMPANY_SOURCE} source is not in default search: this brain does not read as serving one person, so searches that name no source skip the company pages until the user federates it.`,
+ fix: { ask_user: true, argv: ['gbrain', 'sources', 'federate', COMPANY_SOURCE], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Puts the company pages in default search; on a brain more than one person reads, that is the user\'s call.',
+ user_message: `Your company pages are kept out of default search because this brain may serve more than one person. Should searches include them? (gbrain sources federate ${COMPANY_SOURCE})` },
+ });
+ }
+ if (o.company?.action === 'team') {
+ out.push({
+ code: 'brain_layout_team_next', kind: 'coaching',
+ why: 'A company brain a team shares lives on its own brain, so teammates never reach this machine\'s personal pages. Setup created nothing for the company part.',
+ user_message: 'For a team company brain: create a hosted workspace at https://gbrain.io (gbrainio workspace new), or self-host on Postgres and run gbrain access serves several. Then connect this harness to it too. Guide: docs/guides/brain-layout.md#a-team-company-brain.',
});
}
return out;
@@ -302,14 +475,18 @@ export function layoutNotices(o: LayoutOutcome | null, harness: string, scope: L
* 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'];
+ const shape = (s: BrainShape) => [...setupArgv(harness, scope, source), '--shape', s];
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.',
+ question: 'Give this brain a shape? A personal brain gets three empty starter pages (facts about you, your voice, how you decide) and '
+ + 'a notes folder you pick, imported read only. A company brain gets empty pages for company facts, decisions, pricing, customers, '
+ + 'calls and playbooks in a company source, and a docs folder you pick. Setup tells the agent to read them. Nothing 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 },
+ ...folders.slice(0, 3).map((f, i) => ({ id: `personal_notes_${i + 1}`, label: `Personal brain, importing ${f}`, argv: [...shape('personal'), '--notes', f] })),
+ { id: 'personal', label: 'Personal brain, no notes folder yet', argv: shape('personal') },
+ { id: 'company', label: 'Company brain, just me (add --docs <folder> to import company docs)', argv: shape('company') },
+ { id: 'both', label: 'Personal and company brain, just me', argv: shape('both') },
+ { id: 'company_team', label: 'Company brain shared with a team (prints where it lives; creates nothing)', argv: [...shape('company'), '--team'] },
{ id: 'none', label: 'No starter pages (memory works as it is)' },
],
default: 'none',
@@ -317,25 +494,34 @@ export function brainShapeDecision(harness: string, folders: string[] = candidat
};
}
-/** 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 };
+/** The inline brain_shape questions; readLine answers eof (decline) unless isInteractive(). */
+export async function askBrainShape(folders: string[] = candidateNoteFolders()): Promise<{ brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean }> {
+ const line = async (prompt: string): Promise<string | null> => { const r = await readLine({ prompt }); return r.kind === 'line' ? r.text.trim() : null; };
+ const pick = await line('What are you making? 1) a personal brain 2) a company brain 3) both 4) skip [4]: ');
+ const brain = ({ '1': 'personal', '2': 'company', '3': 'both' } as Record<string, BrainShape>)[pick ?? ''];
+ if (!brain) return {};
+ const folder = async (prompt: string, hint?: string): Promise<string | null> => {
+ const raw = (await line(`${prompt} (Enter ${hint ? 'for the one shown' : 'to skip'}, "none" to skip)${hint ? ` [${hint}]` : ''}: `)) ?? 'none';
+ const picked = raw === 'none' ? null : raw || hint || null;
+ if (!picked) return null;
+ const abs = resolve(picked.startsWith('~/') ? join(homedir(), picked.slice(2)) : picked);
+ try { if (statSync(abs).isDirectory()) return abs; } catch { /* below */ }
+ process.stderr.write(`${picked} is not a folder; skipping that import (run gbrain import <dir> --no-embed later)\n`);
+ return null;
+ };
+ const out: { brain: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = { brain };
+ if (hasPersonal(brain)) out.notes = await folder('Notes folder to import, read only', folders[0]);
+ if (hasCompany(brain)) {
+ out.team = (await line('Just you, or a team? 1) just me 2) a team [1]: ')) === '2';
+ if (!out.team) out.docs = await folder('Company docs folder to import, read only');
+ }
+ return out;
}
/** 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.';
+ const line = ' Want a personal or company brain? I can add starter pages (facts, voice and decisions) and import a notes or docs 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];
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index e2c1b7b396..d827b13d4d 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -217,11 +217,19 @@ Flags:
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 company Adds a company source (in default search only when the brain
+ serves one person) with empty pages for company facts,
+ decisions, pricing, customers, calls and playbooks, and the
+ matching lines in that block. --shape both does personal too.
--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
+ --notes DIR With --shape personal or both: 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.
+ --docs DIR With --shape company or both: import a company docs folder into
+ the company source the same way, read only.
+ --team | --solo With a company shape: --team prints where a team's shared company
+ brain lives and creates nothing for it; --solo (the default) makes
+ the company part on this brain.
--skills-index-only Refresh every skills index recorded for this harness (its
file, launcher and skill set as recorded) and change
nothing else; with --skill-loading off, remove them.
@@ -303,9 +311,13 @@ interface SetupFlags {
brain?: BrainShape;
/** GST-2731: the notes folder imported read only with --shape personal; null for --notes none. */
notes?: string | null;
+ /** GST-2731: the company docs folder imported read only with --shape company; null for --docs none. */
+ docs?: string | null;
+ /** GST-2731: --team, the company part lives on a shared brain; setup prints the route and creates nothing for it. */
+ team?: boolean;
}
-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']);
+const VALUE_FLAGS = new Set(['--shape', '--notes', '--docs', '--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 => {
@@ -715,13 +727,13 @@ function liveServeConflict(live: NonNullable<Target['live_owner']>, harness: Set
* (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 };
+ let shape: { brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = { brain: flags.brain, notes: flags.notes, docs: flags.docs, team: flags.team };
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 } });
+ flags: { brain: shape.brain, notes: shape.notes, docs: shape.docs, team: shape.team, dryRun: flags.dryRun } });
return { outcome, notices: (base) => [...(ask && !shape.brain ? withBrainShape(base, brainShapeDecision(harness, undefined, scope, source)) : base), ...layoutNotices(outcome, harness, scope, source)] };
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 67f88c65c1..7d2470d467 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-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'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--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', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--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.ts
index 61896cb31f..e85acf1aef 100644
--- a/test/setup-brain-layout.test.ts
+++ b/test/setup-brain-layout.test.ts
@@ -1,13 +1,15 @@
/**
- * GST-2731: \`gbrain setup <harness> --shape personal [--notes <dir>]\` (setup-brain-layout.ts).
+ * GST-2731: \`gbrain setup <harness> --shape personal|company|both [--notes <dir>] [--docs <dir>] [--team]\` (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.
+ * 1. Protects: the starter pages are create-only empty forms, the notes and docs
+ * folders are read and never written, a new brain set up by an agent gets the
+ * brain_shape decision and no pages, the layout block lives beside the brain-first
+ * block, and the company source joins default search only on a one-person brain.
* 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.
+ * or docs folder, a page written before the shape question is answered (--yes
+ * included), an inline import of a huge folder, a company source federated on a
+ * shared brain, anything created for the company part with --team.
* 3. New flags on an existing command; test/setup.test.ts keeps the rest of setup.
*/
import { afterAll, describe, expect, test } from 'bun:test';
@@ -16,7 +18,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn
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';
+import { COMPANY_PAGES, 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[] = [];
@@ -152,18 +154,86 @@ describe('setup --shape personal', () => {
expect(readFileSync(join(b.home, '.codex', 'AGENTS.md'), 'utf8')).toContain(LAYOUT_BEGIN);
}, 120_000);
- test('--shape company is refused before anything is written', async () => {
+ test('an unknown shape is refused before anything is written', async () => {
const b = box();
- const r = await setup(b, ['claude-code', '--shape', 'company']);
+ const r = await setup(b, ['claude-code', '--shape', 'team']);
expect(r.exitCode).not.toBe(0);
- expect(r.stderr + r.stdout).toContain('later gbrain release');
+ expect(r.stderr + r.stdout).toContain('pass personal, company, both or none');
expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
}, 60_000);
});
+function docsDir(b: Box): string {
+ const dir = join(b.root, 'company-docs');
+ mkdirSync(join(dir, 'pricing'), { recursive: true });
+ writeFileSync(join(dir, 'pricing', 'q3.md'), '# Q3 pricing review\n\nWe moved the team plan to annual billing.\n');
+ writeFileSync(join(dir, 'onboarding.md'), '# Onboarding playbook\n\nSend the welcome email first.\n');
+ return dir;
+}
+const sourceIds = async (b: Box): Promise<any[]> => JSON.parse((await gbrain(b, ['sources', 'list', '--json'])).stdout).sources;
+
+describe('setup --shape company', () => {
+ test('a one-person brain gets a company source in default search, its pages, and the docs read only', async () => {
+ const b = box();
+ const docs = docsDir(b);
+ const before = treeHash(docs);
+ const r = await setup(b, ['claude-code', '--shape', 'company', '--docs', docs]);
+ expect(r.exitCode).toBe(0);
+ const layout = r.doc.brain_layout;
+ expect(layout.company).toMatchObject({ source: 'company', action: 'created', federated: true });
+ expect(layout.company.root.startsWith(join(b.home, '.gbrain'))).toBe(true);
+ expect(layout.pages.map((p: any) => [p.slug, p.source, p.action])).toEqual(COMPANY_PAGES.map((p) => [p.slug, 'company', 'write']));
+ expect(layout.docs).toMatchObject({ action: 'imported', files: 2 });
+ expect(layout.check).toMatchObject({ ok: true, query: 'Onboarding playbook' });
+ expect(layout.check.detail).toContain('default search');
+ expect(layout.next_question).toContain('what did we decide about Onboarding playbook');
+ expect(r.doc.notices.some((n: any) => n.code === 'source_not_in_default_search')).toBe(false);
+ expect(treeHash(docs)).toBe(before);
+ const md = readFileSync(claudeMd(b), 'utf8');
+ expect(md).toContain('company/decisions');
+ expect(md).not.toContain('me/facts');
+ expect((await gbrain(b, ['get', 'company/facts', '--source', 'company'])).stdout).toContain('status: stub');
+ const again = await setup(b, ['claude-code', '--shape', 'company']);
+ expect(again.exitCode).toBe(0);
+ expect(again.doc.brain_layout.company.action).toBe('kept');
+ expect(again.doc.brain_layout.pages.every((p: any) => p.action === 'keep')).toBe(true);
+ }, 240_000);
+
+ test('a brain declared shared keeps the company source out of default search and asks the user', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--shape', 'personal'])).exitCode).toBe(0);
+ expect((await gbrain(b, ['config', 'set', 'brain.audience', 'shared'])).exitCode).toBe(0);
+ const docs = docsDir(b);
+ const r = await setup(b, ['claude-code', '--shape', 'both', '--docs', docs]);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.company).toMatchObject({ action: 'created', federated: false });
+ expect((await sourceIds(b)).find((s) => s.id === 'company').federated).toBe(false);
+ const n = r.doc.notices.find((x: any) => x.code === 'source_not_in_default_search');
+ expect(n.fix.next).toBe('ask_user');
+ expect(n.fix.argv.slice(0, 4)).toEqual(['gbrain', 'sources', 'federate', 'company']);
+ expect(r.doc.brain_layout.check.detail).toContain('search of the company source');
+ const md = readFileSync(claudeMd(b), 'utf8');
+ expect(md).toContain('me/facts');
+ expect(md).toContain('company/decisions');
+ }, 300_000);
+
+ test('--team writes the personal part, creates nothing for the company part and prints the route', async () => {
+ const b = box();
+ const r = await setup(b, ['claude-code', '--shape', 'both', '--team']);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.company).toMatchObject({ action: 'team' });
+ expect(r.doc.brain_layout.pages.map((p: any) => p.slug)).toEqual(['me/facts', 'me/voice', 'me/how-i-decide']);
+ expect((await sourceIds(b)).some((s) => s.id === 'company')).toBe(false);
+ expect(r.doc.notices.find((x: any) => x.code === 'brain_layout_team_next').user_message).toContain('gbrain access serves several');
+ const md = readFileSync(claudeMd(b), 'utf8');
+ expect(md).toContain('me/facts');
+ expect(md).not.toContain('company/decisions');
+ }, 180_000);
+});
+
describe('layout units', () => {
test('the starter pages hold only template text', () => {
- for (const p of PERSONAL_PAGES) {
+ for (const p of [...PERSONAL_PAGES, ...COMPANY_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);
@@ -172,9 +242,15 @@ describe('layout units', () => {
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(['--notes', '/tmp'])).toContain('--shape personal or both');
expect(parse(['--shape', 'personal', '--notes', 'rel/dir'])).toContain('absolute');
- expect(parse(['--shape', 'both'])).toContain('later gbrain release');
+ expect(parse(['--shape', 'personal', '--docs', '/tmp'])).toContain('--shape company or both');
+ expect(parse(['--shape', 'personal', '--team'])).toContain('need --shape company or both');
+ expect(parse(['--shape', 'company', '--team', '--solo'])).toContain('do not go together');
+ expect(parse(['--shape', 'company', '--team', '--docs', '/tmp'])).toContain('--solo');
+ expect(parse(['--shape', 'both'])).toEqual({ brain: 'both' });
+ expect(parse(['--shape', 'company', '--team'])).toEqual({ brain: 'company', team: true });
+ expect(parse(['--shape', 'both', '--notes', 'none', '--docs', '/tmp'])).toEqual({ brain: 'both', notes: null, docs: '/tmp' });
expect(parse(['--shape', 'personal', '--notes', 'none'])).toEqual({ brain: 'personal', notes: null });
});
@@ -219,6 +295,56 @@ describe('layout units', () => {
expect(wrote.pages.map((p) => p.action)).toEqual(['write', 'write', 'write']);
});
+ test('a rerun handed out after a --team run keeps --team', () => {
+ const o = (company: any) => ({ shape: 'both', pages: [{ slug: 'me/facts', source: null, action: 'failed', detail: 'busy' }], notes: null, docs: null, company, block: null, check: { ok: true, query: null, detail: '' }, next_question: null }) as any;
+ const fix = (company: any) => layoutNotices(o(company), 'claude-code').find((n) => n.code === 'brain_layout_pages_pending')!.fix!;
+ expect(fix({ source: 'company', action: 'team', federated: null, root: null }).argv).toEqual(['gbrain', 'setup', 'claude-code', '--shape', 'both', '--team']);
+ expect(fix(null).argv).toEqual(['gbrain', 'setup', 'claude-code', '--shape', 'both']);
+ });
+
+ test('a company folder that is not an empty folder is never adopted, and the block and the fix say so', () => {
+ for (const occupy of [(p: string) => { mkdirSync(p); writeFileSync(join(p, 'mine.md'), '# Mine\n'); }, (p: string) => writeFileSync(p, 'a file\n')]) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-occupied-'));
+ roots.push(root);
+ occupy(join(root, 'company'));
+ const instructions = join(root, 'CLAUDE.md');
+ const calls: string[][] = [];
+ const o = applyBrainLayout({ harness: 'claude-code', launcher: 'gbrain', instructionsPath: instructions, flags: { brain: 'both', notes: null, docs: null, dryRun: false },
+ run: (argv) => {
+ calls.push(argv);
+ if (argv[1] === 'sources') return { code: 0, stdout: JSON.stringify({ sources: [{ id: 'default', local_path: join(root, 'default'), federated: true }] }), stderr: '' };
+ return argv[1] === 'get' ? { code: 1, stdout: '{"code":"page_not_found"}', stderr: '' } : { code: 0, stdout: '', stderr: '' };
+ } })!;
+ expect(o.company!.action).toBe('failed');
+ expect(calls.some((c) => c[1] === 'sources' && c[2] === 'add')).toBe(false);
+ expect(o.pages.map((p) => p.slug)).toEqual(PERSONAL_PAGES.map((p) => p.slug));
+ const block = readFileSync(instructions, 'utf8');
+ expect(block).toContain('me/facts');
+ expect(block).not.toContain('company/facts');
+ const fix = layoutNotices(o, 'claude-code').find((n) => n.code === 'brain_layout_pages_pending')!.fix!;
+ expect(fix.ask_user).toBe(true);
+ expect(fix.user_message).toContain(join(root, 'company'));
+ }
+ });
+
+ test('personal pages land before the company source exists, and either sources add reply reads as federated', () => {
+ for (const reply of [{ federated: true }, { config: { federated: true } }]) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-order-'));
+ roots.push(root);
+ const calls: string[][] = [];
+ const o = applyBrainLayout({ harness: 'claude-code', launcher: 'gbrain', instructionsPath: null, flags: { brain: 'both', notes: null, docs: null, dryRun: false },
+ run: (argv) => {
+ calls.push(argv);
+ if (argv[1] === 'sources' && argv[2] === 'list') return { code: 0, stdout: JSON.stringify({ sources: [{ id: 'default', local_path: join(root, 'default'), federated: true }] }), stderr: '' };
+ if (argv[1] === 'sources' && argv[2] === 'add') return { code: 0, stdout: JSON.stringify({ id: 'company', ...reply }), stderr: '' };
+ return argv[1] === 'get' ? { code: 1, stdout: '{"code":"page_not_found"}', stderr: '' } : { code: 0, stdout: '', stderr: '' };
+ } })!;
+ const added = calls.findIndex((c) => c[1] === 'sources' && c[2] === 'add');
+ for (const p of PERSONAL_PAGES) expect(calls.findIndex((c) => c[1] === 'put' && c[2] === p.slug)).toBeLessThan(added);
+ expect(o.company!.federated).toBe(true);
+ }
+ });
+
test('the notes count does not follow symlinked folders', () => {
const root = mkdtempSync(join(tmpdir(), 'gbrain-layout-loop-'));
roots.push(root);