Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
setup --serves several: label each person with a member, a folder rule and a bound key; doctor checks unlabeled people folders (GST-363)
garrytan87f2b9621805
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a2721b2770..c39399fdc5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,23 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**A brain that serves several people can now be set up the safe way in one command: each person gets a member, a folder only they read and a key bound to them, and doctor fails when a person's folder has no owner.** When one bot answers several people from one brain with one unbound key, it pulls one person's notes into another person's answers (garrytan/harness-evals#363 measured 15 to 47.5% of trials; bots reading through member-bound keys stayed at 0 to 0.5%). `gbrain setup claude-code --serves several --members alice-example,bob-example` writes `access.serves = several`, adds the members, adds a folder rule `people/<member>/` per member through the folder-rule path (committed to `.gbrain/access.yml` on a repo brain, the database rule log on a repo-less one), mints one read-write key per member through the `auth create` mint into a 0600 file under `~/.gbrain/member-keys/`, and proves with a bound read per member that each sees only its own folder and world pages. Re-runs keep everything and never replace a key; a partial failure finishes on the next run. A one-person brain sees no change: `--serves one` stays the default and its output is unchanged.++### Itemized changes++- `gbrain setup claude-code|codex --serves one|several`, `--members <id,...>`, `--members-file <file>` (`src/commands/setup.ts`, `src/commands/setup-serves.ts`). Setup stays engine-free: the labelling, the serves read and the bound reads run as children of the launcher. An empty roster refuses `access_serves_roster_empty`.+- On a brain that already serves several people (2+ enabled members, or `access.serves = several`; explicit wins), a plain setup refuses `setup_serves_several` and writes nothing unless the connection is bound: when the brain names an owner (`access.owner_member`), setup writes `mcp.stdio_member = <owner>`; an existing `mcp.stdio_member` is kept.+- `gbrain access serves` (read-only view) and `gbrain access serves several --members ... [--yes]` (`src/commands/access-serves.ts`): the labelling on its own, preview first. Keys are idempotent on the member id (token `member-<id>`); a key whose file is gone is reported with the revoke step, never re-minted on its own. Key files never go inside a git work tree (`access_serves_key_dir_in_git`).+- `src/core/access/serves.ts` (new): `brainServes(engine)`, the one read of whether a brain serves several people.+- `src/commands/auth-mint.ts` (new): the token mint `gbrain auth create` used inline, shared with the labelling; `auth create` output is unchanged.+- `src/commands/access-rules.ts`: `addFolderRules` adds rules through the same preview-then-write path as `gbrain access rule add`.+- Brain-first block and per-turn rule (`src/core/setup/brain-first.ts`): on a several-person install the `source_ids` / "apply your own access rules" line becomes "This connection reads only what the person asking may read." One-person text is unchanged; doctor's `harness_wiring` repair names `--serves several` for such a block.+- New doctor check `unlabeled_people_folders` (`src/commands/doctor/checks/unlabeled-people-folders.ts`): on a several-person brain, fails for each top-level `people/<name>/` folder with pages that no folder rule (on that folder or on `people/`) covers; the fix previews the rule and asks the user who reads it. Not applicable on a one-person brain.+- Docs: `docs/guides/setup.md` ("A brain that serves several people"), `INSTALL_FOR_AGENTS.md`, `skills/setup/SKILL.md`, `skills/conventions/brain-routing.md`.+- Tests: `test/setup-serves-several.test.ts` (PGLite repo-less and Postgres in process with the minted keys verified by the serve --http verifier; spawned setup on PGLite; a repo brain with a real git repository).+## [0.60.634.0] - 2026-11-09**Privacy, trust and access checks written in SQL now give the same answer as their TypeScript versions, so remote callers can't see a page through one path that another path hides.** Several rules are evaluated twice: once in TypeScript on a page already read, and once in SQL for list, search, backlink and scan queries. Postgres `btrim(x)` strips only spaces, while JavaScript's `trim()` strips every Unicode edge whitespace character, and Postgres `lower()` follows the database collation. A page marked private through the `access` or `confidentiality` field, with other whitespace around the value (a YAML block scalar keeps a trailing newline), was hidden from remote `get_page` but not from remote list and search. The fast page filters also skipped the full check for `type: question` pages and pages with a `pinned_question` key, which the full check treats as private.diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex cc658f344f..4ce2658ef3 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -147,6 +147,15 @@ whenever the user gives one. Capture(`--capture`) and providers (`--providers`) stay off unless the user acceptsthem. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) meansanother owner or a hosted brain holds the target; follow its `fix`.+When the brain will answer several people (a team bot, a shared channel), ask the+user who they are and add `--serves several --members <id,...>`: each person gets+a member, a folder `people/<member>/` only they read and a key bound to them+(`~/.gbrain/member-keys/<member>.key`, 0600; relay paths, never key values), and+the receipt proves each member reads only their folder plus world pages.+`setup_serves_several` means the brain already serves several people and the+connection would be bound to nobody: rerun with its fix, or name the owner+(`gbrain access owner set <member>`) first. Doctor's `unlabeled_people_folders`+names any person's folder still without a rule.`--remove` undoes only what setup wrote. Guide:[docs/guides/setup.md](docs/guides/setup.md). Otherwise:diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex b937e5aeb5..40c029ccec 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -4,4 +4,5 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).+- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else 2+ enabled members) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines).- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 396aff9731..77116fc7b5 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -28,7 +28,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. Pinned by `test/setup.test.ts`.+- `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`): `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/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/error-codes.md b/docs/guides/error-codes.mdindex 2b41300bf5..0866bfb8c2 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -152,6 +152,22 @@ More: [docs/guides/write-refusals.md#access_policy_pending](../../docs/guides/wrMore: [docs/guides/write-refusals.md#access_rule_invalid](../../docs/guides/write-refusals.md#access_rule_invalid)+### access_serves_key_dir_in_git++<a id="access_serves_key_dir_in_git"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written. | Key files hold live credentials; a file inside a checkout can be committed and pushed. | Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again. | agent | `repeat the read that failed` | 1 | no |++### access_serves_roster_empty++<a id="access_serves_roster_empty"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written. | Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are. | Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line. | agent | `repeat the read that failed` | 1 | no |+### acknowledgment_unavailable<a id="acknowledgment_unavailable"></a>@@ -4490,6 +4506,14 @@ Reasons: `live_serve`, `unowned_entry`, `other_install`, `harness_lane`.More: [docs/guides/repair.md#setup-owner-conflict](../../docs/guides/repair.md#setup-owner-conflict)+### setup_serves_several++<a id="setup_serves_several"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain setup for one person was run on a brain that serves several people, and the stdio connection it would write is bound to nobody, so setup wrote nothing. | On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one. | Run gbrain setup <harness> --serves several --members <id,...> to label each person, or name the brain owner first (gbrain access owner set <member>) so this harness reads as the owner. Run: gbrain access serves --json | agent | `repeat the read that failed` | 1 | no |+### shared_skills_unavailable<a id="shared_skills_unavailable"></a>diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 85d112c029..033f9ab272 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -151,6 +151,41 @@ leaves it alone. The brain, its notes, unrelated MCP servers and hooks stay.Two installs on one machine (different `GBRAIN_HOME`) each use their own`--name` and remove only their own entries.+## A brain that serves several people++A brain serves several people when config `access.serves` is `several`, or when it is+unset and the brain has two or more enabled members (`gbrain access serves` shows which).+One bot reading for all of them with one unbound key pulls one person's notes into+another person's answers, so setup labels each person instead:++```bash+gbrain setup claude-code --serves several --members alice-example,bob-example+# or --members-file people.txt (one id per line)+```++For each person this adds a member (existing ones are kept), a folder rule+`people/<member>/` that only that member reads (repo brain: committed to+`.gbrain/access.yml` through `gbrain git commit-push`; repo-less brain: the+database rule log), and one key bound to that member, written to+`~/.gbrain/member-keys/<member>.key` (mode 0600, never inside a git checkout; the+receipt prints the path, never the key). It sets `access.serves = several`, then+proves the labels with one read per member (`gbrain find people/ --as <member>`):+each member sees its own folder and world pages, never another member's folder.+When the brain names an owner (`gbrain access owner set <member>`), this harness's+own stdio server is bound to it (`mcp.stdio_member`); a bot that answers several+people runs `gbrain serve --http` with each member's key.++Every step is idempotent on the member id, so a re-run after a failure finishes the+rest. A key whose file is gone is reported, never replaced on its own: revoke it+(`gbrain auth revoke member-<id>`) and run setup again. An empty roster refuses.+`--serves one` (the default) changes nothing, but on a brain that already serves+several people a plain setup refuses (`setup_serves_several`) rather than write a+connection bound to nobody, unless an owner or `mcp.stdio_member` binds it.+`gbrain doctor` fails `unlabeled_people_folders` when such a brain has a+`people/<name>/` folder with pages and no rule naming its readers.+`gbrain access serves several --members ...` does the labelling alone (preview, then+`--yes`).+## Brain-first instructionsRegistering MCP makes the tools available; it does not make agents use them.@@ -159,7 +194,9 @@ brain. So setup also writes one short marked block (`<!-- gbrain:brain-first:beg… `<!-- gbrain:brain-first:end -->`) into the file the harness loads everysession: before answering any turn, search the brain first, read the best hit,fill gaps with other tools, apply your own access rules (`source_ids` narrows a-search to what the current requester may see), then finish the task.+search to what the current requester may see), then finish the task. On a brain+that serves several people the access line says instead that the connection reads+only what the person asking may read (see below).| Harness | File ||---|---|diff --git a/llms-full.txt b/llms-full.txtindex b279ac9f8a..84901b4437 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2839,6 +2839,15 @@ whenever the user gives one. Capture(`--capture`) and providers (`--providers`) stay off unless the user acceptsthem. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) meansanother owner or a hosted brain holds the target; follow its `fix`.+When the brain will answer several people (a team bot, a shared channel), ask the+user who they are and add `--serves several --members <id,...>`: each person gets+a member, a folder `people/<member>/` only they read and a key bound to them+(`~/.gbrain/member-keys/<member>.key`, 0600; relay paths, never key values), and+the receipt proves each member reads only their folder plus world pages.+`setup_serves_several` means the brain already serves several people and the+connection would be bound to nobody: rerun with its fix, or name the owner+(`gbrain access owner set <member>`) first. Doctor's `unlabeled_people_folders`+names any person's folder still without a rule.`--remove` undoes only what setup wrote. Guide:[docs/guides/setup.md](docs/guides/setup.md). Otherwise:diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.mdindex c5a7cfbe74..38aa93af09 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md@@ -28,6 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.+On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.## When to switch braindiff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.mdindex c5a7cfbe74..38aa93af09 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md@@ -28,6 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.+On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.## When to switch braindiff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.mdindex c5a7cfbe74..38aa93af09 100644--- a/plugin/skills/conventions/brain-routing.md+++ b/plugin/skills/conventions/brain-routing.md@@ -28,6 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.+On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.## When to switch braindiff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.mdindex 7b73f848d9..7df9518c10 100644--- a/plugin/skills/setup/SKILL.md+++ b/plugin/skills/setup/SKILL.md@@ -40,6 +40,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys. Fix a `setup_serves_several` refusal with its `fix`. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9e9322a025..113236dc89 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1696 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1+src/core/behavior-change-notice.ts 1697 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GST-363: the serves_several_labels_gst363 rowdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 305e1d4d8b..c96e9b68f5 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -374,6 +374,8 @@ 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-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 5 readFileSync+test/setup-serves-several.test.ts labelling several people (${kind}, repo-less) 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 readFileSynctest/shared-skills-export.serial.test.ts (file-level) 7 readFileSyncdiff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.mdindex c5a7cfbe74..38aa93af09 100644--- a/skills/conventions/brain-routing.md+++ b/skills/conventions/brain-routing.md@@ -28,6 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.+On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.## When to switch braindiff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex f925035bdc..ac18fa4da9 100644--- a/skills/setup/SKILL.md+++ b/skills/setup/SKILL.md@@ -39,6 +39,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys. Fix a `setup_serves_several` refusal with its `fix`. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 00cdb7c2cd..848fde975a 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -46,7 +46,7 @@"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "12c7b876994b96babdffa903326f7e23253d54ad9023248820337f56f8770512","conventions/brain-first.md": "f84f03b9619a1c9302a231bd43957c6987d55084f56eee351434b85ec2646a5c",- "conventions/brain-routing.md": "f11c3e7c4f98163aa6c68aa7d8f09a7acb7b6a8695f42eb7d92d4ee5787d428a",+ "conventions/brain-routing.md": "a8eaf769fbc42cafa0f5ddec65032ffff80739c961f4bdd3d8999ce64104ee21","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933","conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",@@ -212,7 +212,7 @@"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489","schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5","schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",- "setup/SKILL.md": "681574af925998a2b9b363eb8e16c178e891612f4750fed942f4b8efa7335edc",+ "setup/SKILL.md": "951671ffdd21b99e82e2fd2cd770268cd3a663b7f1a93dc93b209b0164febc5f","signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60","skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613","skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",diff --git a/src/commands/access-rules.ts b/src/commands/access-rules.tsindex c717c46fa8..17ff4ad303 100644--- a/src/commands/access-rules.ts+++ b/src/commands/access-rules.ts@@ -156,7 +156,7 @@ function previewLines(p: RulePreview, rerun: string): string[] {];}-interface EditResult {+export interface EditResult {source_id: string;store: AccessStore;operation_id: string;@@ -206,6 +206,26 @@ function editLines(r: EditResult): string[] {];}+/**+ * GST-363: adds folder rules through the same path as `gbrain access rule add`: one desired rulebook (the store's+ * base plus `rules`), previewed, then written with the preview's revision as --expect when `apply` is set.+ */+export async function addFolderRules(engine: BrainEngine, sourceId: string, rules: FolderRule[], opts: { apply: boolean; json: boolean }): Promise<{ preview: RulePreview; result: EditResult | null }> {+ const { store, persisted, root } = await resolveStore(engine, sourceId);+ const base = await baseRules(engine, sourceId, store, root);+ const desired = sortRules([...base.filter(b => !rules.some(r => r.id === b.id)), ...rules]);+ const preview = await previewRules(engine, sourceId, store, persisted, desired);+ if (!opts.apply) return { preview, result: null };+ const message = `access: ${rules.map(r => `rule ${r.id} on ${r.prefix} readable by ${r.readable_by.map(reader).join(', ')}`).join('; ')}`;+ return { preview, result: await writeRules(engine, sourceId, desired, { expect: preview.expect, message, json: opts.json }) };+}++/** The rulebook a new edit would start from (the store's base), for callers that plan rules before adding them. */+export async function currentFolderRules(engine: BrainEngine, sourceId: string): Promise<FolderRule[]> {+ const { store, root } = await resolveStore(engine, sourceId);+ return baseRules(engine, sourceId, store, root);+}+async function ruleCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {const sourceId = flag(args, '--source') ?? 'default';const yes = args.includes('--yes');diff --git a/src/commands/access-serves.ts b/src/commands/access-serves.tsnew file mode 100644index 0000000000..65731425c2--- /dev/null+++ b/src/commands/access-serves.ts@@ -0,0 +1,189 @@+/**+ * GST-363 (PR 1): `gbrain access serves`, the labelling half of a brain that serves several people.+ *+ * gbrain access serves [--json] Read-only: one or several, why, owner, stdio member+ * gbrain access serves several --members a,b [--members-file f] [--source id] [--yes] [--json]+ *+ * `several` previews, then with --yes: writes config access.serves = several, adds each member (existing ones are+ * kept), adds one folder rule per member (people/<member>/ readable by that member) through the folder-rule path+ * (preview, then write at the previewed revision; a git-store source commits .gbrain/access.yml through the commit+ * door, a repo-less source writes the database revision log), and mints one key per member through the auth create+ * mint, bound to that member and written to a 0600 file under <configDir>/member-keys/, never inside a git work tree.+ * Every step is idempotent on the member id, so a re-run after a partial failure converges; the receipt names paths,+ * never key values. `gbrain setup <harness> --serves several` runs this as a child and adds the bound-read proof.+ */+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../core/engine.ts';+import { configDir } from '../core/config.ts';+import { opError } from '../core/ops/contract.ts';+import { usageError } from '../cli/cli-error.ts';+import { normalizeRule, type FolderRule } from '../core/access/folder-rules.ts';+import { addMember, getMember, parseIdList } from '../core/access/members.ts';+import { ownerMemberId } from '../core/access/owner.ts';+import { stdioMemberId } from '../core/access/caller.ts';+import { brainServes, SERVES_KEY, type ServesView } from '../core/access/serves.ts';+import { addFolderRules, currentFolderRules } from './access-rules.ts';+import { mintToken } from './auth-mint.ts';++export const MEMBER_KEY_DIR = 'member-keys';+export const memberKeyName = (member: string): string => `member-${member}`;+export const memberKeyDir = (): string => join(configDir(), MEMBER_KEY_DIR);++export interface ServesStatus extends ServesView { owner: string | null; stdio_member: string | null }++type Step = 'config' | 'members' | 'rules' | 'keys';+export interface ServesReceipt {+ serves: 'several';+ source_id: string;+ applied: boolean;+ config: { key: string; value: 'several'; action: 'write' | 'keep' };+ members: Array<{ id: string; action: 'add' | 'keep' | 'blocked'; detail?: string }>;+ rules: Array<{ id: string; prefix: string; readers: string[]; action: 'add' | 'keep' | 'blocked'; detail?: string }>;+ rule_write?: { store: string; revision: number | null; state: string; git_commit?: string | null };+ keys: Array<{ member: string; token_name: string; path: string; action: 'mint' | 'keep' | 'blocked'; detail?: string }>;+ key_dir: string;+ /** The steps finished before a failure (partial-failure report); every one is idempotent, so a re-run converges. */+ completed: Step[];+ error?: { code: string; message: string };+}++/** Member ids from --members and --members-file (one per line or comma-separated; # starts a comment). */+export function readRoster(members: string | undefined, file: string | undefined): string[] {+ const fromFile = file ? readFileSync(file, 'utf8').split('\n').map(l => l.replace(/#.*/, '')).join(',') : '';+ return parseIdList([members ?? '', fromFile].filter(Boolean).join(','), 'member');+}++export function rosterEmpty(command: string): Error {+ return opError('access_serves_roster_empty', 'A brain that serves several people needs the list of people; none was given, so nothing was written.',+ `Name every person with --members <id,...> or --members-file <file>, for example: ${command} --members alice-example,bob-example`,+ { why: 'Each person gets a member, a folder only they read and a key bound to them; setup never guesses who they are.' });+}++/** The first directory at or above `dir` that holds .git, or null. */+function gitRootAbove(dir: string): string | null {+ for (let d = dir; ; d = dirname(d)) {+ if (existsSync(join(d, '.git'))) return d;+ if (dirname(d) === d) return null;+ }+}++export async function servesStatus(engine: BrainEngine): Promise<ServesStatus> {+ return { ...(await brainServes(engine)), owner: await ownerMemberId(engine), stdio_member: await stdioMemberId(engine) };+}++async function plan(engine: BrainEngine, roster: string[], sourceId: string): Promise<ServesReceipt> {+ const keyDir = memberKeyDir();+ const gitRoot = gitRootAbove(keyDir);+ if (gitRoot) {+ throw opError('access_serves_key_dir_in_git', `Member keys go to ${keyDir}, which is inside the git work tree at ${gitRoot}; a key there could be committed, so nothing was written.`,+ 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory), then run the command again.',+ { why: 'Key files hold live credentials and must never sit where a commit could pick them up.' });+ }+ const explicit = (await engine.getConfig(SERVES_KEY))?.trim();+ const members: ServesReceipt['members'] = [];+ for (const id of roster) {+ const m = await getMember(engine, id);+ members.push(!m ? { id, action: 'add' } : m.status === 'enabled' ? { id, action: 'keep' }+ : { id, action: 'blocked', detail: m.status === 'disabled' ? `member is disabled: enable it with gbrain access member enable ${id}` : 'member id was removed and can never be reused; use a new id' });+ }+ const base = await currentFolderRules(engine, sourceId);+ const rules: ServesReceipt['rules'] = roster.map((id) => {+ const r = normalizeRule({ prefix: `people/${id}/`, readable_by: [id] });+ if ('problem' in r) return { id, prefix: `people/${id}/`, readers: [id], action: 'blocked', detail: r.problem };+ const clash = base.find(b => b.prefix === r.rule.prefix || b.id === r.rule.id);+ if (!clash) return { id: r.rule.id, prefix: r.rule.prefix, readers: r.rule.readable_by, action: 'add' };+ if (clash.prefix === r.rule.prefix && clash.readable_by.includes(`member:${id}`)) return { id: clash.id, prefix: clash.prefix, readers: clash.readable_by, action: 'keep' };+ return { id: r.rule.id, prefix: r.rule.prefix, readers: r.rule.readable_by, action: 'blocked',+ detail: `rule "${clash.id}" on ${clash.prefix} already exists and does not name ${id}; change it with gbrain access rule add --id ${clash.id} --prefix ${clash.prefix} --readers <list>` };+ });+ const keys: ServesReceipt['keys'] = [];+ for (const id of roster) {+ const name = memberKeyName(id);+ const path = join(keyDir, `${id}.key`);+ const [token] = await engine.executeRaw<{ member_id: string | null }>('SELECT member_id FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);+ if (members.find(m => m.id === id)?.action === 'blocked') keys.push({ member: id, token_name: name, path, action: 'blocked', detail: 'the member is not enabled' });+ else if (!token) keys.push({ member: id, token_name: name, path, action: 'mint' });+ else if (token.member_id !== id) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `a token named ${name} exists but is not bound to ${id}; revoke it (gbrain auth revoke ${name}) or bind it (gbrain auth rescope --token ${name} --member ${id})` });+ else if (!existsSync(path)) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `the key ${name} exists but its file is gone and a key is shown only once; revoke it (gbrain auth revoke ${name}) and run this again to mint a new one` });+ else keys.push({ member: id, token_name: name, path, action: 'keep' });+ }+ return { serves: 'several', source_id: sourceId, applied: false, config: { key: SERVES_KEY, value: 'several', action: explicit === 'several' ? 'keep' : 'write' },+ members, rules, keys, key_dir: keyDir, completed: [] };+}++function writeKeyFile(path: string, token: string): void {+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ chmodSync(dirname(path), 0o700);+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, `${token}\n`, { mode: 0o600 });+ chmodSync(tmp, 0o600);+ renameSync(tmp, path);+}++function abortAfter(step: string): void {+ if (process.env.GBRAIN_SETUP_ABORT_AFTER === step) throw new Error(`GBRAIN_SETUP_ABORT_AFTER=${step}: stopped on purpose after ${step}.`);+}++/** Plans, and with `apply` writes, the several-people labelling; a failure is reported in the receipt, never thrown. */+export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean): Promise<ServesReceipt> {+ const receipt = await plan(engine, roster, sourceId);+ if (!apply) return receipt;+ receipt.applied = true;+ try {+ if (receipt.config.action === 'write') await engine.setConfig(SERVES_KEY, 'several');+ receipt.completed.push('config');+ for (const m of receipt.members.filter(x => x.action === 'add')) await addMember(engine, m.id);+ receipt.completed.push('members');+ abortAfter('serves-members');+ const added = receipt.rules.filter(r => r.action === 'add').map((r): FolderRule => ({ id: r.id, prefix: r.prefix, readable_by: r.readers }));+ if (added.length) {+ const { result } = await addFolderRules(engine, sourceId, added, { apply: true, json });+ if (result) receipt.rule_write = { store: result.store, revision: result.revision, state: result.state, ...(result.git ? { git_commit: result.git.commit ?? null } : {}) };+ }+ receipt.completed.push('rules');+ abortAfter('serves-rules');+ for (const k of receipt.keys.filter(x => x.action === 'mint')) {+ const minted = await mintToken(engine, k.token_name, { scopes: ['read', 'write'], binding: { member: k.member } });+ writeKeyFile(k.path, minted.token);+ abortAfter('serves-key');+ }+ receipt.completed.push('keys');+ } catch (e) {+ receipt.error = { code: (e as { code?: string }).code ?? 'internal_error', message: e instanceof Error ? e.message : String(e) };+ }+ return receipt;+}++export function receiptLines(r: ServesReceipt): string[] {+ const verb = (a: string) => (r.applied ? { add: 'added', mint: 'minted', write: 'written', keep: 'kept', blocked: 'BLOCKED' } : { add: 'will add', mint: 'will mint', write: 'will write', keep: 'keep', blocked: 'BLOCKED' })[a] ?? a;+ return [+ `Serves several people (source ${r.source_id}):`,+ ` config ${r.config.key} = ${r.config.value} (${verb(r.config.action)})`,+ ...r.members.map(m => ` member ${m.id} (${verb(m.action)})${m.detail ? `: ${m.detail}` : ''}`),+ ...r.rules.map(x => ` rule ${x.prefix} readable by ${x.readers.map(p => p.replace(/^member:/, '')).join(', ')} (${verb(x.action)})${x.detail ? `: ${x.detail}` : ''}`),+ ...(r.rule_write ? [` ${r.rule_write.store} store, revision ${r.rule_write.revision ?? '-'} ${r.rule_write.state}${r.rule_write.git_commit ? `, committed ${r.rule_write.git_commit.slice(0, 12)}` : ''}`] : []),+ ...r.keys.map(k => ` key ${k.member}: ${k.path} (${verb(k.action)}${k.action === 'blocked' ? '' : ', 0600'}; token ${k.token_name})${k.detail ? `: ${k.detail}` : ''}`),+ ...(r.error ? [`Stopped: ${r.error.message}`, ` Finished before it stopped: ${r.completed.join(', ') || 'nothing'}. Every step is idempotent: run the same command again to finish.`] : []),+ ...(r.applied ? [] : ['Nothing written. Add --yes to apply.']),+ ];+}++export const receiptOk = (r: ServesReceipt): boolean => !r.error && [...r.members, ...r.rules, ...r.keys].every(x => x.action !== 'blocked');++export async function runAccessServes(engine: BrainEngine, mode: string | undefined, args: string[], json: boolean, flagValue: (args: string[], name: string) => string | undefined): Promise<void> {+ if (mode === undefined) {+ const s = await servesStatus(engine);+ console.log(json ? JSON.stringify(s, null, 2) : [+ `This brain serves ${s.serves === 'several' ? 'several people' : 'one person'} (${s.from === 'config' ? `config ${SERVES_KEY}` : `${s.enabled_members.length} enabled member(s)`}).`,+ ` Enabled members: ${s.enabled_members.join(', ') || 'none'}`,+ ` Owner: ${s.owner ?? 'none'}; stdio server reads as: ${s.stdio_member ?? 'nobody in particular (unbound)'}`].join('\n'));+ return;+ }+ if (mode !== 'several') throw usageError(`Unknown access serves mode: ${mode}.`, 'gbrain access serves (read-only), or gbrain access serves several --members <id,...>. A one-person brain needs no step.');+ const roster = readRoster(flagValue(args, '--members'), flagValue(args, '--members-file'));+ if (!roster.length) throw rosterEmpty('gbrain access serves several');+ const r = await labelSeveral(engine, roster, flagValue(args, '--source') ?? 'default', args.includes('--yes'), json);+ console.log(json ? JSON.stringify(r, null, 2) : receiptLines(r).join('\n'));+ if (!receiptOk(r)) process.exitCode = 1;+}diff --git a/src/commands/access.ts b/src/commands/access.tsindex add674ebfc..3306028f43 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -14,6 +14,7 @@import type { BrainEngine } from '../core/engine.ts';import { exitCliError, usageError } from '../cli/cli-error.ts';import { runAccessRules } from './access-rules.ts';+import { runAccessServes } from './access-serves.ts';import { opError } from '../core/ops/contract.ts';import { sqlQueryForEngine } from '../core/sql-query.ts';import { grantFromClient, type PrincipalGrant } from '../core/grants/model.ts';@@ -52,6 +53,13 @@ Owner (one member who owns this brain; credentials bound to it read every page,gbrain access owner set <member> The member must be enabled; bind credentials with --member <id>gbrain access owner clear No owner: every caller reads under the ordinary policy+Serves several people (GST-363):+ gbrain access serves One or several, and why (config access.serves, else 2+ enabled members)+ gbrain access serves several --members a,b [--members-file <file>] [--source <id>] [--yes]+ Preview first; --yes writes access.serves = several, adds each member,+ a folder rule people/<member>/ read only by that member, and one key+ bound to each member in a 0600 file under <config>/member-keys/+Folder rules (one rulebook per source; the database store on a repo-less source, .gbrain/access.yml on a git one):gbrain access rule add --prefix <folder/> --readers a,group:b [--id <rule>] [--source <id>] [--yes]Preview first; narrowing applies at once@@ -85,7 +93,7 @@ function flagValue(args: string[], name: string): string | undefined {return v;}-const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--source', '--token', '--client', '--as', '--qm', '--member']);+const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--members-file', '--source', '--token', '--client', '--as', '--qm', '--member']);function positionals(args: string[]): string[] {const out: string[] = [];@@ -332,6 +340,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<voswitch (cmd) {case 'member': return await memberCmd(engine, rest[0], rest.slice(1), json);case 'owner': return await ownerCmd(engine, rest[0], rest.slice(1), json);+ case 'serves': return await runAccessServes(engine, positionals(rest)[0], rest, json, flagValue);case 'group': return await groupCmd(engine, rest[0], rest.slice(1), json);case 'who-can-read': {const slug = positionals(rest)[0];@@ -357,7 +366,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<vo` ${r.explanation}`]);}default:- throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, owner, group, rule, apply, resume, who-can-read or check (gbrain access --help).', { code: 'unknown_command' });+ throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, owner, serves, group, rule, apply, resume, who-can-read or check (gbrain access --help).', { code: 'unknown_command' });}} catch (e) {exitCliError(e, 'access');diff --git a/src/commands/auth-mint.ts b/src/commands/auth-mint.tsnew file mode 100644index 0000000000..f8f2c70ca2--- /dev/null+++ b/src/commands/auth-mint.ts@@ -0,0 +1,35 @@+/**+ * The token mint behind `gbrain auth create`, shared with `gbrain access serves+ * several` (GST-363), which mints one member-bound key per person through the+ * same path. Returns the token value to the caller; never prints it.+ */+import type { BrainEngine } from '../core/engine.ts';+import { generateToken, hashToken } from '../core/utils.ts';+import { insertUnifiedToken } from '../core/token-mint.ts';+import { setTokenMinTrust } from '../core/trust/min-trust.ts';+import type { TrustTier } from '../core/trust/tier.ts';+import { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';+import { checkBindingTarget } from './auth-binding.ts';++export interface MintTokenOpts { takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier; binding?: BindingPatch | null }+export interface MintedToken { token: string; id: string; takesHolders: string[]; bound: BindingResult | null }++export async function mintToken(engine: BrainEngine, name: string, opts: MintTokenOpts = {}): Promise<MintedToken> {+ const token = generateToken('gbrain_');+ // v0.28: persist per-token takes-holder allow-list. Default ['world'] keeps+ // private hunches hidden from MCP-bound tokens.+ const takesHolders = opts.takesHolders && opts.takesHolders.length > 0 ? opts.takesHolders : ['world'];+ await checkBindingTarget(engine, opts.binding ?? null);+ // F3: the token is born on the unified grant shape (columns + the+ // permissions JSONB mirror older binaries read). Scopes land in the+ // original-schema scopes TEXT[] column; omitted → NULL → the historical+ // grandfathered full-access grant.+ const [row] = await insertUnifiedToken(engine, {+ name, tokenHash: hashToken(token), ...(opts.scopes !== undefined ? { scopes: opts.scopes } : {}),+ grant: { sources: { kind: 'default' }, takesHolders, allowedOperations: null },+ });+ // #5575 (CEO-18): the read floor; the CLI is the only writer of it.+ if (opts.minTrust) await setTokenMinTrust(engine, row!.id, opts.minTrust);+ const bound = opts.binding ? await bindCredential(engine, { kind: 'token', id: String(row!.id) }, opts.binding) : null;+ return { token, id: String(row!.id), takesHolders, bound };+}diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 5d9604589e..00923868c6 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -19,15 +19,14 @@* postgres.js singleton. `test` only hits a remote URL and doesn't need* a local DB.*/-import { createHash } from 'crypto';import { loadConfig, toEngineConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';import type { BrainEngine } from '../core/engine.ts';import { assertAllowedScopes } from '../core/scope.ts';import { isTrustTier, TRUST_TIERS, type TrustTier } from '../core/trust/tier.ts';-import { setMinTrust, setTokenMinTrust } from '../core/trust/min-trust.ts';-import { generateToken, isMissingSchemaObject } from '../core/utils.ts';-import { TOKEN_ID_RE, insertUnifiedToken } from '../core/token-mint.ts';+import { setMinTrust } from '../core/trust/min-trust.ts';+import { isMissingSchemaObject } from '../core/utils.ts';+import { TOKEN_ID_RE } from '../core/token-mint.ts';import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';import type { OAuthTransaction } from '../core/oauth-grants.ts';@@ -39,13 +38,10 @@ import type { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';import { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';import { bindingLine, checkBindingTarget, takeBindingFlags } from './auth-binding.ts';+import { mintToken } from './auth-mint.ts';import { exitCliError } from '../cli/cli-error.ts';import { OperationError } from '../core/ops/contract.ts';-function hashToken(token: string): string {- return createHash('sha256').update(token).digest('hex');-}-/*** Acquire an engine from the active config, run `fn` with a SqlQuery, and* disconnect afterward. Loud-fails when no config is present (matches the@@ -93,28 +89,9 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: stprocess.exit(1);}}- const token = generateToken('gbrain_');- const hash = hashToken(token);-try {await withConfiguredSql(async (_sql, engine) => {- // v0.28: persist per-token takes-holder allow-list. Default ['world'] keeps- // private hunches hidden from MCP-bound tokens.- const takesHolders = opts.takesHolders && opts.takesHolders.length > 0- ? opts.takesHolders- : ['world'];- await checkBindingTarget(engine, opts.binding ?? null);- // F3: the token is born on the unified grant shape (columns + the- // permissions JSONB mirror older binaries read). Scopes land in the- // original-schema scopes TEXT[] column; omitted → NULL → the historical- // grandfathered full-access grant.- const [row] = await insertUnifiedToken(engine, {- name, tokenHash: hash, ...(opts.scopes !== undefined ? { scopes: opts.scopes } : {}),- grant: { sources: { kind: 'default' }, takesHolders, allowedOperations: null },- });- // #5575 (CEO-18): the read floor; the CLI is the only writer of it.- if (opts.minTrust) await setTokenMinTrust(engine, row!.id, opts.minTrust);- const bound = opts.binding ? await bindCredential(engine, { kind: 'token', id: String(row!.id) }, opts.binding) : null;+ const { token, takesHolders, bound } = await mintToken(engine, name, opts);const scopeLine = opts.scopes !== undefined? `scopes=${JSON.stringify(opts.scopes)}`: 'scopes=full access (grandfathered — pass --scopes read,write to narrow)';diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 3e500a6856..082b2ab2c9 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -495,6 +495,7 @@ function repairArgv(v: InstructionBlockView): Action {const argv = ['gbrain', 'setup', v.harness, '--instructions-only',...(access?.kind === 'mcp' && access.server !== 'gbrain' ? ['--name', access.server] : []),...(access?.kind === 'mcp' && access.surface ? ['--surface', access.surface] : []),+ ...(access?.kind === 'mcp' && access.serves === 'several' ? ['--serves', 'several'] : []),...(v.harness === 'openclaw' ? ['--workspace', dirname(v.path)] : []),...(v.harness === 'claude-code' && basename(v.path) === 'CLAUDE.local.md' ? ['--scope', 'project'] : [])];const why = `Writes or upgrades only the marked brain-first block in ${v.path}; text outside the markers is left as it is. \`--no-instructions\` opts out instead.`;diff --git a/src/commands/doctor/checks/unlabeled-people-folders.ts b/src/commands/doctor/checks/unlabeled-people-folders.tsnew file mode 100644index 0000000000..5dfcc1cb44--- /dev/null+++ b/src/commands/doctor/checks/unlabeled-people-folders.ts@@ -0,0 +1,58 @@+/**+ * GST-363 (PR 1): unlabeled_people_folders. On a brain that serves several people (config access.serves, else two or+ * more enabled members: core/access/serves.ts), a top-level people/<x>/ folder that holds pages and that no folder+ * rule covers (a rule on people/<x>/ or on people/) is read by every caller entitled to the source, so one person's+ * bot can read another person's notes. Fails per folder; the fix previews the rule `gbrain setup --serves several`+ * would have added, and the user decides who reads it. Not applicable on a brain that serves one person.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { appliedRules } from '../../../core/access/policy.ts';+import { brainServes } from '../../../core/access/serves.ts';++const NAME = 'unlabeled_people_folders';++async function runUnlabeledPeopleFolders(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ try {+ const view = await brainServes(engine);+ if (view.serves === 'one') {+ checks.push(infoCheck(NAME, 'Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).', 'not_applicable'));+ return checks;+ }+ const folders = await engine.executeRaw<{ source_id: string; folder: string; pages: number }>(+ `SELECT source_id, split_part(slug, '/', 2) AS folder, count(*)::int AS pages FROM pages+ WHERE deleted_at IS NULL AND slug LIKE 'people/%/%' GROUP BY 1, 2 ORDER BY 1, 2`);+ const rulesBySource = new Map<string, string[]>();+ const unlabeled: Array<{ source: string; prefix: string; pages: number }> = [];+ for (const f of folders) {+ if (!rulesBySource.has(f.source_id)) rulesBySource.set(f.source_id, (await appliedRules(engine, f.source_id)).map(r => r.prefix));+ const prefix = `people/${f.folder}/`;+ if (!rulesBySource.get(f.source_id)!.some(p => p === prefix || p === 'people/')) unlabeled.push({ source: f.source_id, prefix, pages: Number(f.pages) });+ }+ const why = view.from === 'config' ? 'config access.serves is several' : `it has ${view.enabled_members.length} enabled members`;+ if (!unlabeled.length) {+ checks.push({ name: 'unlabeled_people_folders', status: 'ok', details: { serves: view, folders: [] }, message: `This brain serves several people (${why}), and every people/<name>/ folder with pages has a folder rule naming its readers.` });+ return checks;+ }+ const first = unlabeled[0]!;+ const member = first.prefix.slice('people/'.length, -1);+ checks.push({ name: 'unlabeled_people_folders', status: 'fail', details: { serves: view, folders: unlabeled },+ message: `This brain serves several people (${why}), but ${unlabeled.length} people folder(s) hold pages with no folder rule naming their readers: `+ + `${unlabeled.map(u => `${u.source}:${u.prefix} (${u.pages} page(s))`).join(', ')}. Every caller entitled to the source reads them, so one person's bot can read another person's notes.`,+ fix: agentFix(['gbrain', 'access', 'rule', 'add', '--prefix', first.prefix, '--readers', member, '--source', first.source],+ `Previews a rule keeping ${first.prefix} to ${member} (writes nothing without --yes). Ask the user who should read each folder; a folder that is not one person's goes to its own readers or a group.`, NAME,+ { ask_user: true, docs: 'docs/guides/setup.md#a-brain-that-serves-several-people' }) });+ } catch (error) {+ checks.push(checkError(NAME, `run ${NAME}`, error));+ }+ return checks;+}++export const unlabeledPeopleFoldersEntry: DoctorEntry = {+ name: 'unlabeled_people_folders',+ emits: ['unlabeled_people_folders'],+ run: runUnlabeledPeopleFolders,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 87a3dfce38..007f89b494 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -138,6 +138,7 @@ import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { memberAccessEntry } from './checks/member-access.ts';import { folderAccessEntry } from './checks/folder-access.ts';+import { unlabeledPeopleFoldersEntry } from './checks/unlabeled-people-folders.ts';import { sharedAgentAccessEntry } from './checks/shared-agent-access.ts';import { originTwinsEntry } from './checks/origin-twins.ts';import { slugPathMismatchEntry } from './checks/slug-path-mismatch.ts';@@ -222,6 +223,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [derivedVisibilityEntry,memberAccessEntry,folderAccessEntry,+ unlabeledPeopleFoldersEntry,sharedAgentAccessEntry,rlsEntry,functionSearchPathEntry,diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.tsnew file mode 100644index 0000000000..03379682d9--- /dev/null+++ b/src/commands/setup-serves.ts@@ -0,0 +1,146 @@+/**+ * GST-363 (PR 1): `gbrain setup <harness> --serves one|several`. Setup stays engine-free, so every brain read and+ * write here is a child of the absolute launcher (as `gbrain init` is):+ *+ * - `gbrain access serves --json` reads whether the brain serves several people, its owner and the member the+ * stdio server reads as. A one-person setup (the default) on a brain that serves several people refuses+ * (setup_serves_several) unless the stdio connection it writes is bound: to config mcp.stdio_member, or to the+ * owner (access.owner_member), which setup then writes as mcp.stdio_member.+ * - `--serves several --members a,b` runs `gbrain access serves several --yes --json` (members, one folder rule per+ * member, one bound key per member in a 0600 file) and proves the labels with one bound read per member+ * (`gbrain find people/ --as <member> --json`): each sees its own folder and world pages, never another+ * member's folder.+ */+import { opError, OperationError } from '../core/ops/contract.ts';+import { readRoster, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';++export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; dryRun: boolean }++export interface ProofLine { member: string; own: number; world: number; leaked: string[] }+export interface ServesOutcome {+ mode: 'one' | 'several';+ /** Whether the brain serves several people once this run is done: the brain-first text follows it. */+ brain_serves: 'one' | 'several';+ note?: string;+ receipt?: ServesReceipt;+ proof?: ProofLine[];+ stdio?: { member: string | null; action: 'write' | 'keep' | 'unbound'; detail: string };+ error?: string;+}++function child(launcher: string, args: string[]): { ok: boolean; stdout: string; stderr: string } {+ const r = Bun.spawnSync([launcher, ...args], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env });+ return { ok: r.exitCode === 0, stdout: r.stdout?.toString() ?? '', stderr: r.stderr?.toString() ?? '' };+}++function parsed<T>(text: string): T | null {+ try { return JSON.parse(text) as T; } catch { return null; }+}++/** The roster for --serves several, validated before setup writes anything; an empty one refuses with the fix. */+export function servesRoster(flags: ServesFlags, harness: string): string[] | OperationError {+ if (flags.serves !== 'several') return [];+ try {+ const roster = readRoster(flags.members, flags.membersFile);+ return roster.length ? roster : rosterEmpty(`gbrain setup ${harness} --serves several`) as OperationError;+ } catch (e) {+ if (e instanceof OperationError) return e;+ return opError('invalid_params', `--members-file could not be read: ${(e as Error).message}`, 'Pass a readable file with one member id per line.');+ }+}++/** The brain's serves view through a child, or null when there is no brain yet or the child cannot read it. */+export function readServesStatus(launcher: string): ServesStatus | null {+ const r = child(launcher, ['access', 'serves', '--json']);+ return r.ok ? parsed<ServesStatus>(r.stdout) : null;+}++/** The refusal for a one-person setup that would write an unbound connection on a brain that serves several people. */+export function servesOneRefusal(status: ServesStatus | null, harness: string): OperationError | null {+ if (!status || status.serves !== 'several' || status.stdio_member || status.owner) return null;+ const why = status.from === 'config' ? 'config access.serves is several' : `it has ${status.enabled_members.length} enabled members (${status.enabled_members.join(', ')})`;+ const argv = ['gbrain', 'setup', harness, '--serves', 'several', '--members', status.enabled_members.join(',') || '<id,...>'];+ return opError('setup_serves_several',+ `This brain serves several people (${why}), and the ${harness} connection setup would write is bound to nobody, so it would read every page no rule restricts for whoever asks. Nothing was written.`,+ `Run ${argv.join(' ')} to label each person, or name the owner first (gbrain access owner set <member>) so this harness reads as the owner.`,+ { fix: { argv, consent: ['credentials'], actor: 'user', ask_user: true, requires_exclusive: false,+ why: 'Adds a member, a folder only that member reads and a bound key for each person, and binds this harness to the owner when one is named.',+ verify: { argv: ['gbrain', 'access', 'serves', '--json'] } } });+}++/** --serves several: the labelling child (preview on a dry run) and, when applied, one bound read per member. */+function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags): Omit<ServesOutcome, 'brain_serves'> {+ const r = child(launcher, ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.dryRun ? [] : ['--yes']), '--json']);+ const receipt = parsed<ServesReceipt>(r.stdout);+ if (!receipt || !('members' in receipt)) return { mode: 'several', error: (r.stderr || r.stdout).trim() || 'gbrain access serves several failed' };+ if (flags.dryRun || receipt.error) return { mode: 'several', receipt };+ const proof: ProofLine[] = [];+ for (const member of roster) {+ const found = child(launcher, ['find', 'people/', '--as', member, '--limit', '500', ...(flags.source ? ['--source-id', flags.source] : []), '--json']);+ const pages = parsed<{ pages?: Array<{ slug: string }> }>(found.stdout)?.pages;+ if (!pages) return { mode: 'several', receipt, proof, error: `the bound read as ${member} failed: ${(found.stderr || found.stdout).trim()}` };+ const others = roster.filter(m => m !== member).map(m => `people/${m}/`);+ proof.push({ member, own: pages.filter(p => p.slug.startsWith(`people/${member}/`)).length,+ world: pages.filter(p => !roster.some(m => p.slug.startsWith(`people/${m}/`))).length,+ leaked: pages.map(p => p.slug).filter(s => others.some(o => s.startsWith(o))) });+ }+ return { mode: 'several', receipt, proof };+}++export interface ServesPlan { roster: string[]; status: ServesStatus | null }++/**+ * Before setup writes anything: the roster (an empty one refuses), the brain's serves view (none for a brain setup is+ * about to create, or while this registration's own stdio serve holds a PGLite brain), and the one-person refusal.+ */+export function servesPreflight(flags: ServesFlags, launcher: string, harness: string, hasBrain: boolean, liveOurs: boolean): ServesPlan | OperationError {+ const roster = servesRoster(flags, harness);+ if (roster instanceof OperationError) return roster;+ if (flags.serves === 'several' && liveOurs) {+ return opError('setup_owner_conflict', 'A live stdio serve started by this registration holds the PGLite brain, and labelling several people needs to write to it; nothing was written.',+ `Quit the ${harness} session that started it, then run setup again.`, { reason: 'live_serve', docs: 'docs/guides/repair.md#setup-owner-conflict' });+ }+ const status = hasBrain && !liveOurs ? readServesStatus(launcher) : null;+ if (flags.serves === 'several') return { roster, status };+ const refusal = servesOneRefusal(status, harness);+ return refusal ?? { roster, status };+}++/** The serves part of a setup run (a preview on a dry run), or null when it has nothing to do or say: a one-person brain. */+export function servesApply(flags: ServesFlags, launcher: string, plan: ServesPlan, hasBrain: boolean): ServesOutcome | null {+ const several = flags.serves === 'several';+ const labelled = !several ? null : hasBrain || !flags.dryRun ? runServesSeveral(launcher, plan.roster, flags)+ : { mode: 'several' as const, note: `the new brain is created first; then ${plan.roster.join(', ')} each get a member, a folder rule and a bound key` };+ const status = several && !flags.dryRun ? readServesStatus(launcher) : plan.status;+ const stdio = bindStdioToOwner(launcher, several && !status ? { serves: 'several', from: 'config', enabled_members: plan.roster, owner: null, stdio_member: null } : status, flags.dryRun);+ if (!labelled && !stdio) return null;+ return { ...(labelled ?? { mode: 'one' as const }), brain_serves: several || status?.serves === 'several' ? 'several' : 'one', ...(stdio ? { stdio } : {}) };+}++/** Binds this harness's stdio server to the owner on a brain that serves several people, when nothing binds it yet. */+export function bindStdioToOwner(launcher: string, status: ServesStatus | null, dryRun: boolean): ServesOutcome['stdio'] {+ if (!status || status.serves !== 'several') return undefined;+ if (status.stdio_member) return { member: status.stdio_member, action: 'keep', detail: `this harness reads as ${status.stdio_member} (config mcp.stdio_member)` };+ if (!status.owner) return { member: null, action: 'unbound', detail: 'this harness reads as nobody in particular: name the owner (gbrain access owner set <member>) and run setup again to bind it' };+ if (!dryRun) {+ const r = child(launcher, ['config', 'set', 'mcp.stdio_member', status.owner]);+ if (!r.ok) return { member: null, action: 'unbound', detail: `gbrain config set mcp.stdio_member ${status.owner} failed: ${r.stderr.trim()}` };+ }+ return { member: status.owner, action: 'write', detail: `this harness reads as the owner, ${status.owner} (config mcp.stdio_member)` };+}++export function servesOk(o: ServesOutcome | null): boolean {+ return !o || (!o.error && (!o.receipt || receiptOk(o.receipt)) && (o.proof ?? []).every(p => p.leaked.length === 0));+}++export function servesLines(o: ServesOutcome, dryRun: boolean): string[] {+ return [+ ...(o.receipt ? receiptLines(o.receipt).filter(l => !(dryRun && l.startsWith('Nothing written'))) : []),+ ...(o.proof ?? []).map(p => p.leaked.length+ ? ` proof ${p.member} reads pages of another member's folder: ${p.leaked.join(', ')}`+ : ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and ${p.world} world page(s) under people/, and no other member's folder`),+ ...(o.stdio ? [` stdio ${o.stdio.detail}`] : []),+ ...(o.note ? [` labels ${o.note}`] : []),+ ...(o.error ? [` error ${o.error}`] : []),+ ];+}diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex d09cde155d..f764d85c4e 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -47,6 +47,7 @@ import { claudeUserSettingsPath, type ClaudeHookEvent } from '../core/bootstrap/import { readHarnessReceiptState } from '../core/bootstrap/format.ts';import { smokeStdioRegistration } from './doctor/checks/harness-wiring.ts';import { finishFreshSetupMigrations } from './setup-migrations.ts';+import { servesApply, servesLines, servesOk, servesPreflight, type ServesOutcome } from './setup-serves.ts';import type { McpSurface } from '../mcp/surface.ts';import {SETUP_CAPABILITIES,@@ -145,6 +146,15 @@ Flags:--name NAME MCP server name (default gbrain); one name per install.--source ID Pin the source the MCP server and hooks use.--gbrain-bin PATH Absolute gbrain launcher (default: the gbrain on PATH).+ --serves one|several Whom the brain serves (default one: nothing changes). several labels each+ person: config access.serves = several, a member, a folder rule+ people/<member>/ only that member reads and one key bound to that member+ (a 0600 file under <config>/member-keys/), then one bound read per member+ proves it; this harness reads as the owner (access.owner_member). A one-+ person setup on a brain that already serves several people (2+ enabled+ members) refuses rather than write a connection bound to nobody.+ --members IDS The people of --serves several, comma-separated (e.g. alice-example,bob-example).+ --members-file PATH The same, one id per line.--remove Remove exactly what setup wrote (unchanged entries only), thebrain-first instruction block included. The brain and yournotes stay. Combine with --dry-run to preview.@@ -230,9 +240,13 @@ interface SetupFlags {skillLoading?: SkillLoading;/** --skill-loading resolve turns the skill-resolver lane on (skill-resolver-setup.ts); off or spring turns it off; unset leaves it as it is. */skillResolver?: 'on' | 'off';+ /** GST-363: whom the brain serves; several labels each person (setup-serves.ts). */+ serves?: 'one' | 'several';+ members?: string;+ membersFile?: string;}-const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading']);+const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--serves', '--members', '--members-file']);function parseFlags(args: string[]): SetupFlags | string {const value = (flag: string): string | undefined => {@@ -251,6 +265,9 @@ function parseFlags(args: string[]): SetupFlags | string {if (args.includes('--capture') && args.includes('--no-capture')) return 'pass --capture or --no-capture, not both';if (args.includes('--providers') && args.includes('--no-providers')) return 'pass --providers or --no-providers, not both';if (args.includes('--instructions') && args.includes('--no-instructions')) return 'pass --instructions or --no-instructions, not both';+ const serves = value('--serves');+ if (serves !== undefined && serves !== 'one' && serves !== 'several') return `unknown --serves '${serves}'; pass one or several`;+ if ((args.includes('--members') || args.includes('--members-file')) && serves !== 'several') return '--members and --members-file name the people of --serves several';const workspace = value('--workspace');if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';const flagLoading = value('--skill-loading');@@ -282,6 +299,9 @@ function parseFlags(args: string[]): SetupFlags | string {workspace,skillLoading: skillLoading as SkillLoading | undefined,...(skillResolver ? { skillResolver } : {}),+ ...(serves ? { serves: serves as 'one' | 'several' } : {}),+ ...(value('--members') !== undefined ? { members: value('--members') } : {}),+ ...(value('--members-file') !== undefined ? { membersFile: value('--members-file') } : {}),};}@@ -493,6 +513,8 @@ export async function runSetup(args: string[]): Promise<number> {actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'],why: 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.', verify: verifyDryRun('claude-code', flags.name) }), out);}+ const servesPlan = servesPreflight(flags, launcher, 'claude-code', !!cfg, !!liveOwner?.ours);+ if (servesPlan instanceof OperationError) return refuse(servesPlan, out);const brainCreate = !cfg;const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), '--json'];@@ -504,10 +526,11 @@ export async function runSetup(args: string[]): Promise<number> {{ step: 'hooks', action: found.hooksCurrent ? 'keep' : 'write', detail: plan.events.length ? `${plan.events.join(', ')} in ${found.settingsPath}` : `no hooks (${found.settingsPath})` },...Object.entries(found.edited).map(([event]) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),];- const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, { scope, projectDir });+ const serves = servesApply(flags, launcher, servesPlan, !!cfg);+ const 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 });+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves });}let notices: Notice[] = [];@@ -516,7 +539,8 @@ export async function runSetup(args: string[]): Promise<number> {beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out, 'claude-code'); } : undefined,});for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);- const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, { scope, projectDir });+ const serves = servesApply(flags, launcher, servesPlan, true);+ const 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);if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills) && !resolverChanged(resolver)) say(out, 'Nothing changed: this install is already wired.');@@ -531,7 +555,7 @@ export async function runSetup(args: string[]): Promise<number> {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 });+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves });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) {@@ -667,6 +691,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConactor: 'agent', argv: harnessLane ? ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'] : ['gbrain', 'setup', 'codex', laneEvents.every((e) => e === 'SessionEnd') ? '--no-capture' : '--no-hooks', '--dry-run', '--json'],why: harnessLane ? 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.' : 'Keep the bootstrap lane for those events and preview setup without them.', verify: verifyDryRun('codex', flags.name) }), out);}+ const servesPlan = servesPreflight(flags, launcher, 'codex', !!cfg, !!liveOwner?.ours);+ if (servesPlan instanceof OperationError) return refuse(servesPlan, out);const brainCreate = !cfg;const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), '--json'];@@ -680,10 +706,11 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon{ step: 'trust', action: found.trustCurrent ? 'keep' : 'write', detail: `trust entries for setup's groups in ${found.configPath}` },...Object.keys(found.edited).map((event) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),];- const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, {});+ const serves = servesApply(flags, launcher, servesPlan, !!cfg);+ const 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 });+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves });}let notices: Notice[] = [];@@ -693,7 +720,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon});for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);for (const n of result.notes) say(out, `note: ${n}`);- const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, {});+ const serves = servesApply(flags, launcher, servesPlan, true);+ const 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);if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills) && !resolverChanged(resolver)) say(out, 'Nothing changed: this install is already wired.');@@ -709,7 +737,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConconst 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 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 });+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook, resolver, serves });if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('codex', turnHook, ['gbrain', 'setup', 'codex']), out);return verify.ok || pluginOwner ? code : 1;} catch (e) {@@ -771,6 +799,11 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,}/** The brain-first block for this run: decided from flags, env and the ledger, then applied (or previewed under --dry-run). */+/** The access the brain-first block names; a brain that serves several people says the connection is already scoped. */+function mcpAccess(server: string, surface: McpSurface, serves: ServesOutcome | null): BrainFirstAccess {+ return { kind: 'mcp', server, surface, ...(serves?.brain_serves === 'several' ? { serves: 'several' as const } : {}) };+}+function brainFirstFor(harness: BrainFirstHarness, flags: SetupFlags, access: BrainFirstAccess, where: { scope?: WiringScope; projectDir?: string }): BrainFirstOutcome | null {const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });if ('error' in target) return null;@@ -847,7 +880,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>const adapter = HARNESS_ADAPTERS.find((a) => a.id === harness)!;const envSurface = process.env.GBRAIN_SURFACE;const surface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined);- const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}) };+ const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}), ...(flags.serves === 'several' ? { serves: 'several' as const } : {}) };const mcp = { setup: flags.instructionsOnly ? 'unchanged' as const : 'manual' as const, docs: adapter.guide };if (!isBrainFirstHarness(harness)) {const pasted: BrainFirstAccess = adapter.connection === 'thin-cli' ? { kind: 'cli', launcher: flags.gbrainBin ?? 'gbrain' } : access;@@ -959,20 +992,23 @@ async function finish(out: Out, doc: {skills?: SkillsBlockOutcome | null;turnHook?: TurnHookVerdict | null;resolver?: ResolverSetupResult | null;+ serves?: ServesOutcome | null;}): Promise<number> {const harness = doc.harness ?? 'claude-code';const state = doc.states.at(-1) ?? null;- const code = skillsFailed(doc.skills ?? null) || doc.resolver?.error ? 1 : 0;+ const code = skillsFailed(doc.skills ?? null) || doc.resolver?.error || !servesOk(doc.serves ?? null) ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({harness, dry_run: doc.dryRun, remove: doc.remove ?? false,...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),steps: doc.steps, preserved: doc.preserved ?? [], 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 } : {}),capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),}, null, 2)}\n`, (t) => process.stdout.write(t));return code;}+ if (doc.serves) for (const line of servesLines(doc.serves, doc.dryRun)) say(out, line);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);diff --git a/src/core/access/serves.ts b/src/core/access/serves.tsnew file mode 100644index 0000000000..bfc9064e5b--- /dev/null+++ b/src/core/access/serves.ts@@ -0,0 +1,26 @@+/**+ * GST-363: whether a brain serves several people. A brain does when config+ * access.serves says `several`, or when it is unset and the brain has two or+ * more enabled members; an explicit `one` or `several` wins over the member+ * count. `gbrain setup <harness> --serves several` writes the explicit value;+ * the doctor check unlabeled_people_folders and setup's refusal read it here.+ * Everything lives in the database, so a repo-less brain gets it unchanged.+ */+import type { BrainEngine } from '../engine.ts';++export const SERVES_KEY = 'access.serves';++export interface ServesView {+ serves: 'one' | 'several';+ /** `config` when access.serves decided it, `members` when the enabled-member count did. */+ from: 'config' | 'members';+ enabled_members: string[];+}++export async function brainServes(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<ServesView> {+ const members = (await engine.executeRaw<{ id: string }>(+ 'SELECT id FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL ORDER BY id')).map(r => r.id);+ const explicit = (await engine.getConfig(SERVES_KEY))?.trim();+ if (explicit === 'one' || explicit === 'several') return { serves: explicit, from: 'config', enabled_members: members };+ return { serves: members.length >= 2 ? 'several' : 'one', from: 'members', enabled_members: members };+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 76e740c1ac..8abca34be1 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1498,6 +1498,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.628.0', id: 'federated_member_writes_8982', text: 'A token or OAuth client bound to a member whose write source is a federated source (`gbrain sources federate <id>`) now writes the pages it creates with `readable_by: [member:<id>]`, as one writing to `default` does, because every credential without a source grant reads federated sources too; `POST /ingest` refuses such a credential. Before this, other members\' no-grant tokens and unbound tokens read those pages. A write source that is not federated is unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },{ since: '0.60.630.0', id: 'commit_push_skipped_paths_gst2116', text: '`gbrain git commit-push` and `scripts/brain-commit-push.sh` now exit 1 when git left a named path out of the commit, instead of exiting 0: a modified file flagged assume-unchanged or skip-worktree, or a file inside a nested Git repository. The other named paths are still committed (and pushed on a classic checkout); the error names each skipped path and its reason: `writer_coordinator_required` for a page in a managed canonical worktree (save it through put_page), `commit_paths_skipped` otherwise. The helper\'s managed-checkout refusal now prints the operator contract (code, why, fix, next). Existing brains get the new helper on the next `gbrain sources harden`.' },{ since: '0.60.632.0', id: 'pending_ledger_flagged_gst2118', text: 'A page write that git could not commit because the file is flagged assume-unchanged or skip-worktree now stays in the write-through pending ledger, so `gbrain doctor` reports it as `dirty_age`, and `gbrain git commit-push --pending` exits 1 with `commit_paths_skipped` naming it instead of exiting 0 with nothing_to_commit. `gbrain git commit-push` naming a modified skip-worktree file now commits the other paths and fails `commit_paths_skipped` (reason `skip_worktree`) instead of `commit_paths_invalid` with nothing committed.' },+ { since: 'TBD', id: 'serves_several_labels_gst363', text: 'A brain now says whether it serves one person or several: config `access.serves` (`one` or `several`), else two or more enabled members means several (`gbrain access serves` shows which and why). `gbrain setup <harness> --serves several --members <id,...>` (or `--members-file`) labels each person: a member, a folder rule `people/<member>/` only that member reads, and one key bound to that member in a 0600 file under `~/.gbrain/member-keys/` (the receipt prints paths, never keys), then proves it with one bound read per member; `gbrain access serves several` does the labelling alone. On such a brain a plain `gbrain setup claude-code|codex` now refuses `setup_serves_several` and writes nothing, unless an owner (`gbrain access owner set <member>`, which setup then writes as `mcp.stdio_member`) or `mcp.stdio_member` binds the connection; its brain-first block says the connection reads only what the person asking may read. `gbrain doctor` fails the new `unlabeled_people_folders` check when such a brain has a `people/<name>/` folder with pages and no folder rule naming its readers. A one-person brain sees no change.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex faf21bc240..fdfe261370 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,7 +14,7 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -78,14 +78,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -123,7 +123,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', '--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', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--mcp-only', '--mcp-url', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--names-only', '--out', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--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'],@@ -134,7 +134,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 1e31097331..ec29f4d63c 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -25,5 +25,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers'persistence.adopt_quiet_ms', // persistence/local-edit-adoption.ts (GST-1601): how long a local edit must be quiet before it is adopted, default 5000'access.owner_member', // access/owner.ts (GST-2059): the member who owns this brain; credentials bound to it read private pages (gbrain access owner set)+ 'access.serves', // access/serves.ts (GST-363): one or several; explicit wins over the enabled-member count (gbrain setup --serves several writes it)'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience];diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 5d76f1c17b..b8371c587d 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -97,6 +97,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_policy_widening_held','access_policy_invalid','access_policy_store_mismatch',+ // GST-363: a brain that serves several people keeps each people/<name>/ folder to its readers (doctor/checks/unlabeled-people-folders.ts).+ 'unlabeled_people_folders',// GBRA-231: shared agents (doctor/checks/shared-agent-access.ts).'access_may_act_for_wildcard','extractor_facts_expired',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 902eb0be6b..7cd4494f6b 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -76,6 +76,8 @@ export const CODES = {access_policy_widening_held: { class: 'consent', actor: 'user', summary: "A change to a source's folder rules widens who may read (a rule removed, readers added, the old folder of a moved prefix), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host.", why: 'Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval.', suggestion: 'Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>.', fix: { argv: ['gbrain', 'access', 'apply', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the held widening (pages and members gaining access) and prints the plan hash an approval binds; changes nothing.' } },access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },+ access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },+ access_serves_key_dir_in_git: { class: 'caller', summary: 'The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written.', why: 'Key files hold live credentials; a file inside a checkout can be committed and pushed.', suggestion: 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again.' },access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },@@ -720,6 +722,7 @@ export const CODES = {setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },+ setup_serves_several: { class: 'caller', summary: 'gbrain setup for one person was run on a brain that serves several people, and the stdio connection it would write is bound to nobody, so setup wrote nothing.', why: 'On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one.', suggestion: 'Run gbrain setup <harness> --serves several --members <id,...> to label each person, or name the brain owner first (gbrain access owner set <member>) so this harness reads as the owner.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows why the brain counts as several people, its members, its owner and the member the stdio server reads as.' } },hook_session_cwd: { class: 'caller', summary: "A gbrain hook or stdio MCP entry (setup, the turn-rule lane, gbrain bootstrap's lanes) starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks and stdio MCP servers in the session directory, so a cloned repository could run code on every prompt or session.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex a6e066e715..871c8b0ca5 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -48,7 +48,10 @@ export function isBrainFirstHarness(v: string | undefined): v is BrainFirstHarne}/** How the agent reaches the brain, which decides the tool names the block uses. */-export type BrainFirstAccess = { kind: 'mcp'; server: string; surface?: McpSurface } | { kind: 'cli'; launcher: string };+export type BrainFirstAccess = { kind: 'mcp'; server: string; surface?: McpSurface; serves?: 'several' } | { kind: 'cli'; launcher: string };++/** GST-363: on a brain that serves several people the connection is bound to the person asking, so the agent does no scoping of its own. */+export const SERVES_SEVERAL_LINE = 'This connection reads only what the person asking may read.';/** The block interior (without markers). */export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess, optOut = `gbrain setup ${harness} --instructions-only --no-instructions`): string {@@ -65,7 +68,8 @@ export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess,'',lookup,'- Fill gaps with your other tools. On an empty or thin result, retry with words the notes would use: synonyms, the formal name, the owner, several joined with OR.',- access.kind === 'cli'+ access.kind === 'mcp' && access.serves === 'several' ? `- ${SERVES_SEVERAL_LINE}`+ : access.kind === 'cli'? `- Brain results span every source the brain holds. Pass \`--source-ids <ids>\` to a search or query to narrow it to what the current requester may see, and apply your own access rules to what comes back.`: access.surface === 'verbs'? '- Brain results span every source the token can read, so apply your own access rules to what comes back.'@@ -90,7 +94,7 @@ export function renderBrainFirstTurnRule(access: BrainFirstAccess, harness?: strconst how = access.kind === 'cli' ? `\`${access.launcher} search "<names>"\` or \`${access.launcher} query "<question>"\``: access.surface === 'verbs' ? `\`recall\` or \`entity\` on the \`${access.server}\` MCP server`: `\`search\` or \`query\` on the \`${access.server}\` MCP server`;- return `GBrain: before answering this turn, check GBrain first (${how}) for the people, companies, projects, meetings and decisions it touches.${access.kind === 'mcp' ? turnRuleDiscovery(harness, access) : ''} Results span every source it holds: use only what the current requester may see. Then answer and finish the task.`;+ return `GBrain: before answering this turn, check GBrain first (${how}) for the people, companies, projects, meetings and decisions it touches.${access.kind === 'mcp' ? turnRuleDiscovery(harness, access) : ''} ${access.kind === 'mcp' && access.serves === 'several' ? SERVES_SEVERAL_LINE : 'Results span every source it holds: use only what the current requester may see.'} Then answer and finish the task.`;}/**diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 196a0c5ffa..978c6237e2 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1028,6 +1028,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unlabeled_people_folders",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 39d1b0086d..4c2e0840a8 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1075,6 +1075,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unlabeled_people_folders",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 269fb522e4..6594d02ef3 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1071,6 +1071,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unlabeled_people_folders",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 3b063dd0cd..067aab09df 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -389,6 +389,10 @@"category": "brain","name": "access_policy_store_mismatch"},+ {+ "category": "brain",+ "name": "unlabeled_people_folders"+ },{"category": "brain","name": "access_may_act_for_wildcard"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 5216e93a68..9ad3edd7da 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6841,7 +6841,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 9abf710fb7..6fd5c549c9 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -515,6 +515,7 @@ test/search/rerank-gate-hybrid.test.tstest/search/rerank-gate-telemetry.test.tstest/segmented-untiled-hold-gst1209.test.tstest/serve-head-watcher-managed.serial.test.ts+test/setup-serves-several.test.tstest/shared-content-freshness.test.tstest/shared-skills-catalog.test.tstest/shared-skills-retention-capacity.test.tsdiff --git a/test/setup-serves-several.test.ts b/test/setup-serves-several.test.tsnew file mode 100644index 0000000000..232bc098e1--- /dev/null+++ b/test/setup-serves-several.test.ts@@ -0,0 +1,300 @@+/**+ * GST-363 (PR 1): `gbrain setup <harness> --serves several` labels each person, and doctor checks it.+ *+ * 1. Protects: on a brain that serves several people every person gets a member, a folder rule people/<member>/ only+ * that member reads, and one key bound to that member in a 0600 file outside any git tree; a read through that+ * key sees its own folder plus world pages and never another member's folder. Re-runs keep everything (no key is+ * ever replaced on its own), a partial failure converges on the next run, a plain one-person setup is unchanged+ * on a one-person brain and refuses on a brain that serves several people, and doctor fails an unlabeled people+ * folder until a rule names its readers. The brain-first text says the connection is already scoped.+ * 2. Fails when: a member's key reads another member's folder, a re-run mints a second key or rewrites a key file, a+ * key value reaches the receipt, a key file is group- or world-readable or lands in a checkout, an empty roster+ * writes anything, the default setup output changes, or an unbound connection is written on a several brain.+ * 3. Existing coverage: setup.test.ts (the one-person install), access-folder-rules*.test.ts (the rule path),+ * member-read-access.test.ts (bound reads).+ * 4. Real seams: the minted key verified by the serve --http verifier and dispatched remote=true (PGLite repo-less,+ * Postgres when DATABASE_URL is set); `bun src/cli.ts setup` spawned against a temp HOME / GBRAIN_HOME; a real+ * git repository for the repo-brain arm.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { labelSeveral, type ServesReceipt } from '../src/commands/access-serves.ts';+import { unlabeledPeopleFoldersEntry } from '../src/commands/doctor/checks/unlabeled-people-folders.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { addFolderRules } from '../src/commands/access-rules.ts';+import { renderBrainFirstBlock, renderBrainFirstTurnRule, SERVES_SEVERAL_LINE } from '../src/core/setup/brain-first.ts';+import { runCli, type CliResult } from './helpers/cli-spawn.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const ROSTER = ['alice-example', 'bob-example'];+const PAGES: Record<string, string> = {+ 'people/alice-example/plan': 'alicecanary',+ 'people/bob-example/plan': 'bobcanary',+ 'people/carol-public': 'carolcanary',+ 'notes/world-topic': 'worldcanary',+};+const pageText = (slug: string, canary: string) => `---\ntype: note\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`;+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });+const tempDir = (prefix: string) => { const d = mkdtempSync(join(tmpdir(), prefix)); roots.push(d); return d; };+const mode = (path: string) => (statSync(path).mode & 0o777).toString(8);++describe('brain-first text for the two shapes', () => {+ test('one person keeps the source_ids / own-access-rules lines; several says the connection is already scoped', () => {+ const one = renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'starter' });+ const several = renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'starter', serves: 'several' });+ expect(one).toContain('Pass `source_ids` to narrow a request to what the current requester may see, and apply your own access rules to what comes back.');+ expect(one).not.toContain(SERVES_SEVERAL_LINE);+ expect(several).toContain(`- ${SERVES_SEVERAL_LINE}`);+ expect(several).not.toMatch(/source_ids|apply your own access rules/);+ expect(several.split('\n').length).toBe(one.split('\n').length);+ expect(renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain', surface: 'verbs' })).toContain('Results span every source it holds: use only what the current requester may see.');+ expect(renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain', surface: 'verbs', serves: 'several' })).toContain(SERVES_SEVERAL_LINE);+ });+});++for (const kind of testBackends()) {+ describe(`labelling several people (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let home: string;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const label = (roster: string[], env: Record<string, string | undefined> = {}) => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined, ...env }, () => labelSeveral(engine, roster, 'default', true, true));+ const doctor = async () => (await unlabeledPeopleFoldersEntry.run({ engine } as unknown as DoctorContext) as Array<Record<string, any>>)[0]!;++ /** The canaries a keyword search through `member`'s key file returns, read remotely as the serve --http verifier does. */+ async function boundSearch(member: string): Promise<string[]> {+ const token = readFileSync(join(home, '.gbrain', 'member-keys', `${member}.key`), 'utf8').trim();+ const auth = await provider().verifyAccessToken(token) as unknown as AuthInfo;+ const sourceId = auth.sourceId ?? 'default';+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);+ const out = await dispatchToolCall(engine, 'search', { query: 'harbor ledger notes', match: 'keyword', fields: 'full', limit: 20 }, {+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'], ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });+ const text = out.content.map(c => c.text).join('\n');+ return Object.values(PAGES).filter(c => text.includes(c)).sort();+ }++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ home = tempDir('gbrain-serves-');+ for (const [slug, canary] of Object.entries(PAGES)) await importFromContent(engine, slug, pageText(slug, canary), { sourceId: 'default', noEmbed: true });+ }, 120_000);+ afterAll(async () => { await close?.(); }, 60_000);++ test('doctor: not applicable for one person, fails each unlabeled people folder once the brain serves several', async () => {+ expect(await doctor()).toMatchObject({ name: 'unlabeled_people_folders', status: 'ok', readiness_state: 'not_applicable' });+ await engine.setConfig('access.serves', 'several');+ const c = await doctor();+ expect(c.status).toBe('fail');+ expect(c.details.folders).toEqual([+ { source: 'default', prefix: 'people/alice-example/', pages: 1 },+ { source: 'default', prefix: 'people/bob-example/', pages: 1 },+ ]);+ expect(c.fix).toMatchObject({ argv: ['gbrain', 'access', 'rule', 'add', '--prefix', 'people/alice-example/', '--readers', 'alice-example', '--source', 'default'], ask_user: true });+ await engine.unsetConfig('access.serves');+ }, 60_000);++ test('labels each person: members, folder rules, a bound read-write key per member in a 0600 file outside git', async () => {+ const r = await label(ROSTER);+ expect(r.error).toBeUndefined();+ expect(r.completed).toEqual(['config', 'members', 'rules', 'keys']);+ expect(r.members.map(m => m.action)).toEqual(['add', 'add']);+ expect(r.rules.map(x => [x.prefix, x.readers, x.action])).toEqual([['people/alice-example/', ['member:alice-example'], 'add'], ['people/bob-example/', ['member:bob-example'], 'add']]);+ expect(r.rule_write).toMatchObject({ store: 'database', state: 'applied' });+ expect(await engine.getConfig('access.serves')).toBe('several');+ for (const k of r.keys) {+ expect(k.action).toBe('mint');+ expect(mode(k.path)).toBe('600');+ expect(mode(join(home, '.gbrain', 'member-keys'))).toBe('700');+ expect(readFileSync(k.path, 'utf8')).toMatch(/^gbrain_\S+\n$/);+ expect(JSON.stringify(r)).not.toContain(readFileSync(k.path, 'utf8').trim());+ const [row] = await engine.executeRaw<{ member_id: string; scopes: string[] }>('SELECT member_id, scopes FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [k.token_name]);+ expect(row).toMatchObject({ member_id: k.member, scopes: ['read', 'write'] });+ }+ expect(() => execFileSync('git', ['-C', join(home, '.gbrain', 'member-keys'), 'rev-parse', '--show-toplevel'], { stdio: 'ignore' })).toThrow();+ }, 60_000);++ test("a search through each member's key sees its own folder and world pages, never the other member's folder", async () => {+ expect(await boundSearch('alice-example')).toEqual(['alicecanary', 'carolcanary', 'worldcanary']);+ expect(await boundSearch('bob-example')).toEqual(['bobcanary', 'carolcanary', 'worldcanary']);+ }, 60_000);++ test('doctor passes once every people folder is labelled; a rule on people/ also counts', async () => {+ expect(await doctor()).toMatchObject({ status: 'ok' });+ await importFromContent(engine, 'people/dana-example/notes', pageText('people/dana-example/notes', 'danacanary'), { sourceId: 'default', noEmbed: true });+ expect((await doctor()).details.folders).toEqual([{ source: 'default', prefix: 'people/dana-example/', pages: 1 }]);+ await addFolderRules(engine, 'default', [{ id: 'people-dana-example', prefix: 'people/dana-example/', readable_by: ['member:alice-example'] }], { apply: true, json: true });+ expect(await doctor()).toMatchObject({ status: 'ok' });+ }, 60_000);++ test('a re-run keeps everything and never replaces a key', async () => {+ const before = Object.fromEntries(ROSTER.map(m => [m, readFileSync(join(home, '.gbrain', 'member-keys', `${m}.key`), 'utf8')]));+ const r = await label(ROSTER);+ expect(r.error).toBeUndefined();+ expect([r.config.action, ...r.members.map(m => m.action), ...r.rules.map(x => x.action), ...r.keys.map(k => k.action)]).toEqual(['keep', 'keep', 'keep', 'keep', 'keep', 'keep', 'keep']);+ expect(r.rule_write).toBeUndefined();+ for (const m of ROSTER) expect(readFileSync(join(home, '.gbrain', 'member-keys', `${m}.key`), 'utf8')).toBe(before[m]!);+ const [n] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM access_tokens WHERE name LIKE 'member-%' AND revoked_at IS NULL");+ expect(Number(n!.n)).toBe(2);+ }, 60_000);++ test('a partial failure reports what it finished, and the next run converges', async () => {+ const roster = [...ROSTER, 'erin-example', 'finn-example'];+ const stopped = await label(roster, { GBRAIN_SETUP_ABORT_AFTER: 'serves-key' });+ expect(stopped.error?.message).toContain('serves-key');+ expect(stopped.completed).toEqual(['config', 'members', 'rules']);+ const keyDir = join(home, '.gbrain', 'member-keys');+ expect(existsSync(join(keyDir, 'erin-example.key'))).toBe(true);+ expect(existsSync(join(keyDir, 'finn-example.key'))).toBe(false);+ const erin = readFileSync(join(keyDir, 'erin-example.key'), 'utf8');+ const again: ServesReceipt = await label(roster);+ expect(again.error).toBeUndefined();+ expect(again.keys.map(k => [k.member, k.action])).toEqual([['alice-example', 'keep'], ['bob-example', 'keep'], ['erin-example', 'keep'], ['finn-example', 'mint']]);+ expect(readFileSync(join(keyDir, 'erin-example.key'), 'utf8')).toBe(erin);+ expect(await boundSearch('finn-example')).toEqual(['carolcanary', 'worldcanary']);+ }, 60_000);++ test('a key whose file is gone is reported with the revoke step, never replaced on its own', async () => {+ const path = join(home, '.gbrain', 'member-keys', 'bob-example.key');+ unlinkSync(path);+ const r = await label(ROSTER);+ expect(r.keys.find(k => k.member === 'bob-example')).toMatchObject({ action: 'blocked' });+ expect(r.keys.find(k => k.member === 'bob-example')!.detail).toContain('gbrain auth revoke member-bob-example');+ expect(existsSync(path)).toBe(false);+ }, 60_000);+ });+}++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const CLEAN = { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };+interface Box { root: string; home: string; bin: string }++function box(): Box {+ const root = tempDir('gbrain-setup-serves-');+ const home = join(root, 'home');+ mkdirSync(home, { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ mkdirSync(join(root, 'bin'));+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ return { root, home, bin };+}+const gbrain = (b: Box, args: string[], env: Record<string, string | undefined> = {}) => runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, ...env }, timeoutMs: 120_000 });+async function setup(b: Box, args: string[]): Promise<CliResult & { doc: any }> {+ const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin]);+ let doc: any = null;+ if (args.includes('--json')) { try { doc = JSON.parse(r.stdout); } catch { doc = null; } }+ return { ...r, doc };+}+async function brainWithPages(b: Box): Promise<void> {+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ for (const [slug, canary] of Object.entries(PAGES)) expect((await gbrain(b, ['put', slug, '--content', pageText(slug, canary)])).exitCode).toBe(0);+}+const claudeMd = (b: Box) => readFileSync(join(b.home, '.claude', 'CLAUDE.md'), 'utf8');+const normalized = (doc: any) => JSON.parse(JSON.stringify(doc).replace(/\d{4}-\d\d-\d\dT[\d:.]+Z/g, 'T'));++describe('gbrain setup --serves (spawned, PGLite)', () => {+ test('--serves several labels each person, proves it with bound reads, prints key paths never values; a re-run keeps it all', async () => {+ const b = box();+ await brainWithPages(b);+ const first = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example']);+ expect(first.exitCode).toBe(0);+ for (const m of ROSTER) {+ const key = readFileSync(join(b.home, '.gbrain', 'member-keys', `${m}.key`), 'utf8').trim();+ expect(first.stdout + first.stderr).not.toContain(key);+ expect(first.stdout).toContain(`key ${m}: ${join(b.home, '.gbrain', 'member-keys', `${m}.key`)} (minted, 0600; token member-${m})`);+ expect(first.stdout).toContain(`proof a read bound to ${m} sees its own folder (1 page(s)) and 1 world page(s) under people/, and no other member's folder`);+ }+ expect(first.stdout).toContain('stdio this harness reads as nobody in particular');+ expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);+ const again = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--json']);+ expect(again.exitCode).toBe(0);+ expect(again.doc.serves.receipt.keys.map((k: any) => k.action)).toEqual(['keep', 'keep']);+ expect(again.doc.serves.proof).toEqual([+ { member: 'alice-example', own: 1, world: 1, leaked: [] },+ { member: 'bob-example', own: 1, world: 1, leaked: [] },+ ]);+ }, 240_000);++ test('an empty roster refuses with the fix and writes nothing', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--serves', 'several', '--json']);+ expect(r.exitCode).not.toBe(0);+ expect(r.stdout + r.stderr).toContain('access_serves_roster_empty');+ expect(r.stdout + r.stderr).toContain('--members alice-example,bob-example');+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);+ expect(existsSync(join(b.home, '.gbrain'))).toBe(false);+ }, 120_000);++ test('--serves one on a one-person brain is the default install: the same document, no serves key, the one-person block', async () => {+ const plain = box();+ const explicit = box();+ for (const b of [plain, explicit]) expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ const a = await setup(plain, ['claude-code', '--json']);+ const c = await setup(explicit, ['claude-code', '--serves', 'one', '--json']);+ expect(a.exitCode).toBe(0);+ expect(c.exitCode).toBe(0);+ expect(a.doc.serves).toBeUndefined();+ expect(normalized(c.doc).serves).toBeUndefined();+ const strip = (doc: any, b: Box) => JSON.parse(JSON.stringify(normalized(doc)).replaceAll(b.root, '<root>'));+ expect(strip(c.doc, explicit)).toEqual(strip(a.doc, plain));+ expect(claudeMd(plain)).toContain(renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'verbs' }).split('\n').slice(1).join('\n'));+ }, 240_000);++ test('a plain setup on a brain that serves several people refuses and writes nothing; once an owner is named it binds this harness to the owner', async () => {+ const b = box();+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);+ const refused = await setup(b, ['claude-code', '--json']);+ expect(refused.exitCode).not.toBe(0);+ expect(refused.stdout).toContain('setup_serves_several');+ expect(refused.stdout).toContain('2 enabled members (alice-example, bob-example)');+ expect(refused.stdout).toContain('gbrain setup claude-code --serves several --members alice-example,bob-example');+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);+ expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);+ const bound = await setup(b, ['claude-code', '--json']);+ expect(bound.exitCode).toBe(0);+ expect(bound.doc.serves).toMatchObject({ mode: 'one', brain_serves: 'several', stdio: { member: 'alice-example', action: 'write' } });+ expect((await gbrain(b, ['config', 'get', 'mcp.stdio_member'])).stdout.trim()).toBe('alice-example');+ expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);+ }, 240_000);++ test('a repo brain commits the folder rules to .gbrain/access.yml through the commit door, and the bound reads hold', async () => {+ const b = box();+ const repo = join(b.root, 'repo');+ mkdirSync(repo);+ const git = (...args: string[]) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).trim();+ git('init', '-q', '-b', 'main');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 't');+ for (const [slug, canary] of Object.entries(PAGES)) { mkdirSync(join(repo, slug, '..'), { recursive: true }); writeFileSync(join(repo, `${slug}.md`), pageText(slug, canary)); }+ git('add', '-A');+ git('commit', '-qm', 'pages');+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await gbrain(b, ['sources', 'add', 'team', '--path', repo])).exitCode).toBe(0);+ expect((await gbrain(b, ['sync', '--source', 'team', '--no-pull', '--no-embed'])).exitCode).toBe(0);+ const r = await gbrain(b, ['access', 'serves', 'several', '--members', ROSTER.join(','), '--source', 'team', '--yes', '--json']);+ expect(r.exitCode).toBe(0);+ const receipt = JSON.parse(r.stdout) as ServesReceipt;+ expect(receipt.rule_write).toMatchObject({ store: 'git', state: 'applied' });+ expect(git('log', '-1', '--format=%H')).toBe(receipt.rule_write!.git_commit!);+ expect(git('status', '--porcelain')).toBe('');+ expect(readFileSync(join(repo, '.gbrain', 'access.yml'), 'utf8')).toContain('prefix: people/bob-example/');+ const seen = JSON.parse((await gbrain(b, ['find', 'people/', '--as', 'bob-example', '--source-id', 'team', '--json'])).stdout).pages.map((p: any) => p.slug);+ expect(seen).toEqual(['people/bob-example/plan', 'people/carol-public']);+ }, 240_000);+});